text:
Gradle build failed after adding ads
There is problem with Android building. After adding ads, when I click on build, it shows the following error:

Issue with Android dependencies detected: The SDK has resolved to an incompatible version with the Package. This may result in unexpected behaviour. To avoid this, include the mainTemplate.gradle file by checking the checkbox (Custom Main Gradle Template) in Edit > Project Settings > Player > Publishing
Settings. Would you like to cancel the build?`

And when I check 'Custom Main Gradle Template' and click build it shows the following error:

Gradle build failed. See Console for details.

These are the details shown in the Console:
UnityEditor.BuildPlayerWindow+BuildMethodException: 5 errors
  at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002da] in <63965ae56af7489797f355b7c1211ab2>:0
  at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <63965ae56af7489797f355b7c1211ab2>:0
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

[Mediation]: Only copying gradle lock files, no lockfile generation
UnityEngine.Logger:Log (string,object)
Unity.Services.Mediation.MediationLogger:Log (object) (at Library/PackageCache/com.unity.services.mediation@1.0.5/Runtime/Tools/Logger/MediationLogger.cs:21)
Unity.Mediation.Build.Editor.AndroidLockFilePostGenerateGradleProject:CopyExistingLockFiles (string,string) (at Library/PackageCache/com.unity.services.mediation@1.0.5/Editor/Build/PostGradle/AndroidLockFilePostGenerateGradleProject.cs:140)
Unity.Mediation.Build.Editor.AndroidLockFilePostGenerateGradleProject:OnPostGenerateGradleAndroidProject (string) (at Library/PackageCache/com.unity.services.mediation@1.0.5/Editor/Build/PostGradle/AndroidLockFilePostGenerateGradleProject.cs:82)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

> Configure project :launcher
WARNING: The option setting 'android.enableR8=false' is deprecated.
It will be removed in version 5.0 of the Android Gradle plugin.
You will no longer be able to disable R8
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\build-tools\30.0.2\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platform-tools\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platforms\android-29\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\tools\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\build-tools\30.0.2\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platform-tools\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platforms\android-29\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\tools\package.xml. Probably the SDK is read-only

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':launcher:lintVitalRelease'.
> This project uses AndroidX dependencies, but the 'android.useAndroidX' property is not enabled. Set this property to true in the gradle.properties file and retry.
  The following AndroidX dependencies are detected: androidx.lifecycle:lifecycle-runtime:2.5.1, androidx.core:core:1.6.0, androidx.room:room-runtime:2.2.5, androidx.fragment:fragment:1.0.0, androidx.slidingpanelayout:slidingpanelayout:1.0.0, androidx.versionedparcelable:versionedparcelable:1.1.1, androidx.customview:customview:1.0.0, androidx.swiperefreshlayout:swiperefreshlayout:1.0.0, androidx.lifecycle:lifecycle-common-java8:2.5.1, androidx.interpolator:interpolator:1.0.0, androidx.sqlite:sqlite:2.1.0, androidx.annotation:annotation-experimental:1.1.0, androidx.loader:loader:1.0.0, androidx.drawerlayout:drawerlayout:1.0.0, androidx.sqlite:sqlite-framework:2.1.0, androidx.collection:collection:1.1.0, androidx.viewpager:viewpager:1.0.0, androidx.work:work-runtime:2.7.0, androidx.localbroadcastmanager:localbroadcastmanager:1.0.0, androidx.arch.core:core-common:2.1.0, androidx.annotation:annotation:1.2.0, androidx.lifecycle:lifecycle-service:2.1.0, androidx.lifecycle:lifecycle-common:2.5.1, androidx.startup:startup-runtime:1.1.1, androidx.concurrent:concurrent-futures:1.0.0, androidx.room:room-common:2.2.5, androidx.lifecycle:lifecycle-livedata:2.1.0, androidx.tracing:tracing:1.0.0, androidx.legacy:legacy-support-core-ui:1.0.0, androidx.lifecycle:lifecycle-viewmodel:2.0.0, androidx.browser:browser:1.4.0, androidx.lifecycle:lifecycle-process:2.5.1, androidx.lifecycle:lifecycle-livedata-core:2.1.0, androidx.arch.core:core-runtime:2.1.0, androidx.legacy:legacy-support-core-utils:1.0.0, androidx.documentfile:documentfile:1.0.0, androidx.cursoradapter:cursoradapter:1.0.0, androidx.coordinatorlayout:coordinatorlayout:1.0.0, androidx.asynclayoutinflater:asynclayoutinflater:1.0.0, androidx.print:print:1.0.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8

UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-6.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"

Environment Variables:
USERDOMAIN = SERVERNBEAST
asl.log = Destination=file
ProgramFiles = C:\Program Files
TMP = C:\Users\chmuh\AppData\Local\Temp
PROCESSOR_ARCHITECTURE = AMD64
PROCESSOR_REVISION = 9705
OneDriveConsumer = C:\Users\chmuh\OneDrive
OS = Windows_NT
CHROME_CRASHPAD_PIPE_NAME = \\.\pipe\crashpad_6700_CVKHSUXRYWUAGZTV
PROCESSOR_IDENTIFIER = Intel64 Family 6 Model 151 Stepping 5, GenuineIntel
ProgramW6432 = C:\Program Files
USERPROFILE = C:\Users\chmuh
CommonProgramFiles = C:\Program Files\Common Files
DriverData = C:\Windows\System32\Drivers\DriverData
ComSpec = C:\WINDOWS\system32\cmd.exe
PSModulePath = C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules
PUBLIC = C:\Users\Public
USERNAME = chmuh
NUMBER_OF_PROCESSORS = 12
JAVA_TOOL_OPTIONS = -Dfile.encoding=UTF-8
FPS_BROWSER_APP_PROFILE_STRING = Internet Explorer
TEMP = C:\Users\chmuh\AppData\Local\Temp
Path = C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\dotnet\;C:\Program Files\Azure Data Studio\bin;C:\Users\chmuh\AppData\Local\Microsoft\WindowsApps;C:\Users\chmuh\AppData\Local\GitHubDesktop\bin;C:\Program Files\Azure Data Studio\bin
COMPUTERNAME = SERVERNBEAST
PATHEXT = .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
ALLUSERSPROFILE = C:\ProgramData
SystemDrive = C:
windir = C:\WINDOWS
FPS_BROWSER_USER_PROFILE_STRING = Default
HOMEPATH = \Users\chmuh
CommonProgramFiles(x86) = C:\Program Files (x86)\Common Files
APPDATA = C:\Users\chmuh\AppData\Roaming
OneDrive = C:\Users\chmuh\OneDrive
PROCESSOR_LEVEL = 6
CommonProgramW6432 = C:\Program Files\Common Files
ProgramFiles(x86) = C:\Program Files (x86)
SystemRoot = C:\WINDOWS
SESSIONNAME = Console
LOGONSERVER = \\SERVERNBEAST
LOCALAPPDATA = C:\Users\chmuh\AppData\Local
VBOX_MSI_INSTALL_PATH = C:\Program Files\Oracle\VirtualBox\
HOMEDRIVE = C:
USERDOMAIN_ROAMINGPROFILE = SERVERNBEAST
ProgramData = C:\ProgramData
ORIGINAL_XDG_CURRENT_DESKTOP = undefined

stderr[

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':launcher:lintVitalRelease'.
> This project uses AndroidX dependencies, but the 'android.useAndroidX' property is not enabled. Set this property to true in the gradle.properties file and retry.
  The following AndroidX dependencies are detected: androidx.lifecycle:lifecycle-runtime:2.5.1, androidx.core:core:1.6.0, androidx.room:room-runtime:2.2.5, androidx.fragment:fragment:1.0.0, androidx.slidingpanelayout:slidingpanelayout:1.0.0, androidx.versionedparcelable:versionedparcelable:1.1.1, androidx.customview:customview:1.0.0, androidx.swiperefreshlayout:swiperefreshlayout:1.0.0, androidx.lifecycle:lifecycle-common-java8:2.5.1, androidx.interpolator:interpolator:1.0.0, androidx.sqlite:sqlite:2.1.0, androidx.annotation:annotation-experimental:1.1.0, androidx.loader:loader:1.0.0, androidx.drawerlayout:drawerlayout:1.0.0, androidx.sqlite:sqlite-framework:2.1.0, androidx.collection:collection:1.1.0, androidx.viewpager:viewpager:1.0.0, androidx.work:work-runtime:2.7.0, androidx.localbroadcastmanager:localbroadcastmanager:1.0.0, androidx.arch.core:core-common:2.1.0, androidx.annotation:annotation:1.2.0, androidx.lifecycle:lifecycle-service:2.1.0, androidx.lifecycle:lifecycle-common:2.5.1, androidx.startup:startup-runtime:1.1.1, androidx.concurrent:concurrent-futures:1.0.0, androidx.room:room-common:2.2.5, androidx.lifecycle:lifecycle-livedata:2.1.0, androidx.tracing:tracing:1.0.0, androidx.legacy:legacy-support-core-ui:1.0.0, androidx.lifecycle:lifecycle-viewmodel:2.0.0, androidx.browser:browser:1.4.0, androidx.lifecycle:lifecycle-process:2.5.1, androidx.lifecycle:lifecycle-livedata-core:2.1.0, androidx.arch.core:core-runtime:2.1.0, androidx.legacy:legacy-support-core-utils:1.0.0, androidx.documentfile:documentfile:1.0.0, androidx.cursoradapter:cursoradapter:1.0.0, androidx.coordinatorlayout:coordinatorlayout:1.0.0, androidx.asynclayoutinflater:asynclayoutinflater:1.0.0, androidx.print:print:1.0.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
]
stdout[

> Configure project :launcher
WARNING: The option setting 'android.enableR8=false' is deprecated.
It will be removed in version 5.0 of the Android Gradle plugin.
You will no longer be able to disable R8
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\build-tools\30.0.2\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platform-tools\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platforms\android-29\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\tools\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\build-tools\30.0.2\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platform-tools\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\platforms\android-29\package.xml. Probably the SDK is read-only
Exception while marshalling C:\Program Files\Unity\Hub\Editor\2021.3.15f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\tools\package.xml. Probably the SDK is read-only
]
exit code: 1
UnityEditor.Android.Command.WaitForProgramToRun (UnityEditor.Utils.Program p, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.Android.Command.Run (System.String command, System.String args, System.String workingdir, UnityEditor.Android.Command+WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.Android.AndroidJavaTools.RunJava (System.String args, System.String workingdir, System.Action`1[T] progress, System.String error) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, Unity.Android.Gradle.AndroidGradle androidGradle, System.String workingdir, System.String task, System.Action`1[T] progress) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
Rethrow as GradleInvokationException: Gradle build failed
UnityEditor.Android.GradleWrapper.Run (UnityEditor.Android.AndroidJavaTools javaTools, Unity.Android.Gradle.AndroidGradle androidGradle, System.String workingdir, System.String task, System.Action`1[T] progress) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.Android.PostProcessor.Tasks.BuildGradleProject.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
Rethrow as BuildFailedException: Exception of type 'UnityEditor.Build.BuildFailedException' was thrown.
UnityEditor.Android.PostProcessor.CancelPostProcess.AbortBuild (System.String title, System.String message, System.Exception ex) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, AndroidPlayerBuildProgram.Data.AndroidPlayerBuildProgramOutput buildProgramOutput) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <bf5a7d3f06424428a0a228b33a117c52>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.Int32 subtarget, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <63965ae56af7489797f355b7c1211ab2>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

Build completed with a result of 'Failed' in 408 seconds (407644 ms)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

UnityEditor.BuildPlayerWindow+BuildMethodException: 5 errors
  at UnityEditor.BuildPlayerWindow+DefaultBuildMethods.BuildPlayer (UnityEditor.BuildPlayerOptions options) [0x002da] in <63965ae56af7489797f355b7c1211ab2>:0
  at UnityEditor.BuildPlayerWindow.CallBuildMethods (System.Boolean askForBuildLocation, UnityEditor.BuildOptions defaultBuildOptions) [0x00080] in <63965ae56af7489797f355b7c1211ab2>:0
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

Before adding the Ads plugin, the Andriod building was working fine.


text:
How can I record a demonstration to use with Proximal Policy Optimization?
I have a fuzzy logic controller for my race car that works fairly well. I want to use a recording of this as a demonstration for the PPO (Proximal Policy Optimization) algorithm from ML Agents for the same race car.
Do I set the fuzzy logic algorithm in the heuristic method of my Agent implementation?  The documentation is very vague.

The documentation seems to indicate that you implement the control logic in the Heuristic function and then use a DemonstrationRecorder to record the .demo file. How have you tried putting this into practice so far and where has the behaviour differed from what you need?

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How to prevent a `ViewportTexture` from extending beyond the dimensions of an imported mesh
I have a GLTF imprted from blender that contains a few simple meshes.
It is a screen with a bezel and some buttons. The display area of the screen is a plane that extends up to the bezel:

In this image, you can see the outline of the "display" area. You can also see that the label that says hello extends beyond the bounds of the "display" plane.
I tried creating a MeshInstance3D and setting it's material to the same ViewportTexture and it works fine.
It looks to me like the ViewportTexture is being stretched to the dimensions of the whole imported scene. That is, if the exterior of the bevel is 500mm and the display area is only 450mm, it seems that the texture is projected onto a surface of 500mm wide.
I am trying to achieve the following:

For this last image, I had to use a margin container and guess the margins approximately to set the text entirely within the display area.
I feel this is a bug as the material is not applied to the MeshInstance3D correctly.
Any thoughts?

It looks to me like an issue with the UVs on the mesh.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Put two images on table in the opposite corners
I want to put my two images on the opposite corners of my table: one on bottom left, the second on the bottom right. How to achieve that?
I have tried align() and left()/right(). None of these worked. Now they stick to each other on the bottom center.
public class BottomControlls {

    private Stage stage;
    private Viewport viewport;
    private Image imageLeftDrawerControll;
    private Image imageRightDrawerControll;

    public BottomControlls(SpriteBatch sb, Camera camera) {
        viewport = new FitViewport(7 * 32, 12 * 32, camera);
        stage = new Stage(viewport, sb);

        Table table = new Table();
        table.setSize(camera.viewportWidth, 32);

        Pixmap bgPixmap = new Pixmap(1,1, Pixmap.Format.RGBA8888);
        bgPixmap.setColor(Color.valueOf("00000080"));
        bgPixmap.fill();
        TextureRegionDrawable textureRegionDrawableBg = new TextureRegionDrawable(new TextureRegion(new Texture(bgPixmap)));
        table.setBackground(textureRegionDrawableBg);

        table.bottom();

        table.setDebug(true);

        imageLeftDrawerControll = new Image(new Texture("arrow_right.png"));
        imageRightDrawerControll = new Image(new Texture("arrow_left.png"));

        table.add(imageLeftDrawerControll).size(45, 32).align(Align.left);
        table.add(imageRightDrawerControll).size(45, 32).align(Align.right);

        stage.addActor(table);
    }
}


text:
AI or simulated approach for 4 player spades
I’ve read the strategies but would like to learn better moves.
Sometimes watching a simulated AI game with take backs allows me to learn how to eventually play better.
For 2 player it is fairly simple. 4 player card games such as spades, how would one go about this using modern AI? Does anything similar exist?

What strategies have you read? In what way do you want your new AI strategy to play "better"?


text:
Add a second texture to Sascha Willems' glftLoading app
I am working with Sascha Willems' Vulkan code:
https://github.com/SaschaWillems/Vulkan/tree/master/examples/gltfloading
https://github.com/SaschaWillems/Vulkan/blob/master/data/shaders/glsl/gltfloading/mesh.vert
https://github.com/SaschaWillems/Vulkan/blob/master/data/shaders/glsl/gltfloading/mesh.frag
I cannot figure out how to pass multiple textures into the fragment shader using C++. I know what to do in the GLSL code, because it's the same as in OpenGL 4.
Has anyone had any luck adding a second texture into this example code?
The glTF mesh that I am working with is at https://github.com/sjhalayka/pedestal_textures/raw/main/ped_tex.zip
Sorry for such a n00b question, but I'm totally stuck. Thanks for any help that you can provide.

What have you tried so far? Most of us aren't familiar with the example/tutorial you reference, so to help you, we'd need to go learn it, then guess how you're trying to reimplement it. You'll get a far better response if you include the relevant snippets in the question, including your own attempt(s).


text:
How many rays can one RT core calculate simultaneously?
I have noticed that all GeForce RTX cards, without exception, have an equal number of RT cores as they have streaming multiprocessors (SM). From this fact I assume that each RT core is associated with one SM. In other words, each SM has an RT core available for it to use.
But I am curious to know: How many rays can one RT core calculate simultaneously? Is it just one, or is it more than one?
Given that an SM has (typically) 128 cores, I wouldn't be surprised if an RT core can likewise calculate 128 rays simultaneously, so that each SM core can have its own ray. Maybe even a multiple of 128, so that each SM core can have several rays traced at once. However, I cannot find corroboration of this anywhere.


text:
How to render my volume rendered through raycasting into an imGui window
I've been trying a lot to modify my Code so I can pass my scene into an extra ImGui window but I just can't modify my code so it still works and uses an FBO to render into ImGui. Here's my starting point:
//OpenGL
#include <GL/glew.h>
#include <GL/freeglut.h>

//Base C++
#include <fstream>
#include <iostream>
#include <chrono>

//GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

//Shaderloader
#include "GLSLShader.h"

//Imgui
#include "imgui.h"
#include "imgui_impl_glut.h"
#include "imgui_impl_opengl2.h"

#define GL_CHECK_ERRORS assert(glGetError()== GL_NO_ERROR);

using namespace std;

//main screen resolution
const int WIDTH = 1280;
const int HEIGHT = 960;

//second screen resolution
const int WIDTH2 = 640;
const int HEIGHT2 = 480;
const int POS_X2 = 50;
const int POS_Y2 = 50;

//camera transform variables
int state = 0, oldX = 0, oldY = 0;
float rX = 4, rY = 50, dist = -2;

//modelview projection matrices
glm::mat4 MV, P;

//cube vertex array and vertex buffer object IDs
GLuint cubeVBOID;
GLuint cubeVAOID;
GLuint cubeIndicesID;

//ray casting shader
GLSLShader shader;

//background colour
glm::vec4 bg = glm::vec4(0.2, 0.2, 0.2, 1);

//volume dataset filename
const std::string volume_file = "Engine256.raw";

//volume dimensions
const int XDIM = 256;
const int YDIM = 256;
const int ZDIM = 256;

//fps tracker
static int fps = 0;
static int frameCount = 0;
static int currentTime = 0;
static int previousTime = 0;

//volume texture ID
GLuint textureID;

//transfer function (lookup table) texture id
GLuint tfTexID;

//transfer function (lookup table) colour values
const glm::vec4 jet_values[9] = { glm::vec4(0,0,0.5,0),
                                glm::vec4(0,0,1,0.1),
                                glm::vec4(0,0.5,1,0.3),
                                glm::vec4(0,1,1,0.5),
                                glm::vec4(0.5,1,0.5,0.75),
                                glm::vec4(1,1,0,0.8),
                                glm::vec4(1,0.5,0,0.6),
                                glm::vec4(1,0,0,0.5),
                                glm::vec4(0.5,0,0,0.0) };

//function that load a volume from the given raw data file and
//generates an OpenGL 3D texture from it
bool LoadVolume() {
    std::ifstream infile(volume_file.c_str(), std::ios_base::binary);

    if (infile.good()) {
        //read the volume data file
        GLubyte* pData = new GLubyte[XDIM * YDIM * ZDIM];
        infile.read(reinterpret_cast<char*>(pData), XDIM * YDIM * ZDIM * sizeof(GLubyte));
        infile.close();

        //generate OpenGL texture
        glGenTextures(1, &textureID);
        glBindTexture(GL_TEXTURE_3D, textureID);

        // set the texture parameters
        glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

        //set the mipmap levels (base and max)
        glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0);
        glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, 4);

        //allocate data with internal format and foramt as (GL_RED)
        glTexImage3D(GL_TEXTURE_3D, 0, GL_RED, XDIM, YDIM, ZDIM, 0, GL_RED, GL_UNSIGNED_BYTE, pData);
        GL_CHECK_ERRORS

        //generate mipmaps
        glGenerateMipmap(GL_TEXTURE_3D);

        //delete the volume data allocated on heap
        delete[] pData;

        return true;
    }
    else {
        return false;
    }
}

//function to generate interpolated colours from the set of colour values (jet_values)
//this function first calculates the amount of increments for each component and the
//index difference. Then it linearly interpolates the adjacent values to get the
//interpolated result.
void LoadTransferFunction() {
    float pData[256][4];
    int indices[9];

    //fill the colour values at the place where the colour should be after interpolation
    for (int i = 0; i < 9; i++) {
        int index = i * 28;
        pData[index][0] = jet_values[i].x;
        pData[index][1] = jet_values[i].y;
        pData[index][2] = jet_values[i].z;
        pData[index][3] = jet_values[i].w;
        indices[i] = index;
    }

    //for each adjacent pair of colours, find the difference in the rgba values and then interpolate
    for (int j = 0; j < 9 - 1; j++)
    {
        float dDataR = (pData[indices[j + 1]][0] - pData[indices[j]][0]);
        float dDataG = (pData[indices[j + 1]][1] - pData[indices[j]][1]);
        float dDataB = (pData[indices[j + 1]][2] - pData[indices[j]][2]);
        float dDataA = (pData[indices[j + 1]][3] - pData[indices[j]][3]);
        int dIndex = indices[j + 1] - indices[j];

        float dDataIncR = dDataR / float(dIndex);
        float dDataIncG = dDataG / float(dIndex);
        float dDataIncB = dDataB / float(dIndex);
        float dDataIncA = dDataA / float(dIndex);
        for (int i = indices[j] + 1; i < indices[j + 1]; i++)
        {
            pData[i][0] = (pData[i - 1][0] + dDataIncR);
            pData[i][1] = (pData[i - 1][1] + dDataIncG);
            pData[i][2] = (pData[i - 1][2] + dDataIncB);
            pData[i][3] = (pData[i - 1][3] + dDataIncA);
        }
    }

    //generate the OpenGL texture
    glGenTextures(1, &tfTexID);
    //bind this texture to texture unit 1
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_1D, tfTexID);

    // set the texture parameters
    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    //allocate the data to texture memory. Since pData is on stack, we donot delete it
    glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA, 256, 0, GL_RGBA, GL_FLOAT, pData);

    GL_CHECK_ERRORS
}

//mouse down event handler
void OnMouseDown(int button, int s, int x, int y)
{
    if (s == GLUT_DOWN)
    {
        oldX = x;
        oldY = y;
    }

    if (button == GLUT_MIDDLE_BUTTON)
        state = 0;
    else
        state = 1;
}

//mouse move event handler
void OnMouseMove(int x, int y)
{
    if (state == 0) {
        dist += (y - oldY) / 50.0f;
    }
    else {
        rX += (y - oldY) / 5.0f;
        rY += (x - oldX) / 5.0f;
    }
    oldX = x;
    oldY = y;

    glutPostRedisplay();
}

//scroll callback function
void OnMouseScroll(int wheel, int direction, int x, int y)
{
    if (direction == 1)
        dist += 0.1f;
    else if (direction == -1)
        dist -= 0.1f;

    glutPostRedisplay();
}

//OpenGL initialization
void OnInit() {

    auto start = std::chrono::steady_clock::now();

    GL_CHECK_ERRORS

    //Load the raycasting shader
    shader.LoadFromFile(GL_VERTEX_SHADER, "raycaster.vert");
    shader.LoadFromFile(GL_FRAGMENT_SHADER, "raycaster.frag");

    //compile and link the shader
    shader.CreateAndLinkProgram();
    shader.Use();
    //add attributes and uniforms
    shader.AddAttribute("vVertex");
    shader.AddUniform("MVP");
    shader.AddUniform("volume");
    shader.AddUniform("camPos");
    shader.AddUniform("step_size");
    shader.AddUniform("lut");

    //pass constant uniforms at initialization
    glUniform3f(shader("step_size"), 1.0f / XDIM, 1.0f / YDIM, 1.0f / ZDIM);
    glUniform1i(shader("volume"), 0);
    glUniform1i(shader("lut"), 1);
    shader.UnUse();

    //GL_CHECK_ERRORS

        //load volume data
        if (LoadVolume()) {
            std::cout << "Volume data loaded successfully." << std::endl;
        }
        else {
            std::cout << "Cannot load volume data." << std::endl;
            exit(EXIT_FAILURE);
        }

    //load the transfer function data and generate the trasnfer function (lookup table) texture
    LoadTransferFunction();

    //set background colour
    glClearColor(bg.r, bg.g, bg.b, bg.a);

    //setup unit cube vertex array and vertex buffer objects
    glGenVertexArrays(1, &cubeVAOID);
    glGenBuffers(1, &cubeVBOID);
    glGenBuffers(1, &cubeIndicesID);

    //unit cube vertices
    glm::vec3 vertices[8] = { glm::vec3(-0.5f,-0.5f,-0.5f),
                            glm::vec3(0.5f,-0.5f,-0.5f),
                            glm::vec3(0.5f, 0.5f,-0.5f),
                            glm::vec3(-0.5f, 0.5f,-0.5f),
                            glm::vec3(-0.5f,-0.5f, 0.5f),
                            glm::vec3(0.5f,-0.5f, 0.5f),
                            glm::vec3(0.5f, 0.5f, 0.5f),
                            glm::vec3(-0.5f, 0.5f, 0.5f) };

    //unit cube indices
    GLushort cubeIndices[36] = { 0,5,4,
                              5,0,1,
                              3,7,6,
                              3,6,2,
                              7,4,6,
                              6,4,5,
                              2,1,3,
                              3,1,0,
                              3,0,7,
                              7,0,4,
                              6,5,2,
                              2,5,1 };
    glBindVertexArray(cubeVAOID);
    glBindBuffer(GL_ARRAY_BUFFER, cubeVBOID);
    //pass cube vertices to buffer object memory
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &(vertices[0].x), GL_STATIC_DRAW);

    GL_CHECK_ERRORS
    //enable vertex attributre array for position
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    //pass indices to element array  buffer
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cubeIndicesID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cubeIndices), &cubeIndices[0], GL_STATIC_DRAW);

    glBindVertexArray(0);

    //enable depth test
    glEnable(GL_DEPTH_TEST);

    //set the over blending function
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    cout << "Initialization successfull" << endl;
    auto end = std::chrono::steady_clock::now();
    chrono::duration<double> elapsed_seconds = end - start;
    cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
}

//release all allocated resources
void OnShutdown() {
    shader.DeleteShaderProgram();

    glDeleteVertexArrays(1, &cubeVAOID);
    glDeleteBuffers(1, &cubeVBOID);
    glDeleteBuffers(1, &cubeIndicesID);
    glDeleteTextures(1, &textureID);

    cout << "Shutdown successfull" << endl;
}

//resize event handler
void OnResize(int w, int h) {
    //reset the viewport
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    //setup the projection matrix
    P = glm::perspective(60.0f, (float)w / h, 0.1f, 1000.0f);
}

//display callback function
void OnRender() {
    GL_CHECK_ERRORS

    //set the camera transform
    glm::mat4 Tr = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, dist));
    glm::mat4 Rx = glm::rotate(Tr, rX, glm::vec3(1.0f, 0.0f, 0.0f));
    glm::mat4 MV = glm::rotate(Rx, rY, glm::vec3(0.0f, 1.0f, 0.0f));

    //get the camera position
    glm::vec3 camPos = glm::vec3(glm::inverse(MV) * glm::vec4(0, 0, 0, 1));

    //clear colour and depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //get the combined modelview projection matrix
    glm::mat4 MVP = P * MV;

    //enable blending and bind the cube vertex array object
    glEnable(GL_BLEND);
    glBindVertexArray(cubeVAOID);
    //bind the raycasting shader
    shader.Use();
    //pass shader uniforms
    glUniformMatrix4fv(shader("MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
    glUniform3fv(shader("camPos"), 1, &(camPos.x));
    //render the cube
    glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0);
    //unbind the raycasting shader
    shader.UnUse();
    //disable blending
    glDisable(GL_BLEND);

    //swap front and back buffers to show the rendered result
    glutSwapBuffers();
}

int main(int argc, char** argv) {
    //freeglut initialization
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitContextVersion(3, 3);
    glutInitContextFlags(GLUT_CORE_PROFILE | GLUT_DEBUG);

    //main window
    glutInitWindowSize(WIDTH, HEIGHT);
    glutCreateWindow("Volume Rendering using GPU Ray Casting - OpenGL 3.3");

    //glew initialization
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        cerr << "Error: " << glewGetErrorString(err) << endl;
    }
    else {
        if (GLEW_VERSION_3_3)
        {
            cout << "Driver supports OpenGL 3.3\nDetails:" << endl;
        }
    }
    err = glGetError(); //this is to ignore INVALID ENUM error 1282
    GL_CHECK_ERRORS

    //output hardware information
    cout << "\tUsing GLEW " << glewGetString(GLEW_VERSION) << endl;
    cout << "\tVendor: " << glGetString(GL_VENDOR) << endl;
    cout << "\tRenderer: " << glGetString(GL_RENDERER) << endl;
    cout << "\tVersion: " << glGetString(GL_VERSION) << endl;
    cout << "\tGLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl;

    GL_CHECK_ERRORS

    //OpenGL initialization
    OnInit();

    //callback hooks
    glutCloseFunc(OnShutdown);
    glutDisplayFunc(OnRender);
    glutReshapeFunc(OnResize);
    glutMouseFunc(OnMouseDown);
    glutMotionFunc(OnMouseMove);
    glutMouseWheelFunc(OnMouseScroll);

    //main loop call
    glutMainLoop();

    return 0;
}


text:
Unity DXR Reflections Not Working Properly
When I use RTX powered reflections in Unity HDRP+DXR it reflects a limited distance of non emitting materials, It means if I add emission to the mesh in distance its emission gets reflected but still not default surface of it. Also the following issue only happens when using Point or Spot lights, Directional lights are fine, It seems unity ray-tracing does not include the light in distance.
Edit : This can be fixed by using Light Clusters I will answer this to my question in 24h, Still problem 2 exists.
I made a simple project which demonstrate the issue : https://github.com/CycloneRing/RTX-Issue
Problem Number 2 :
Also when meshes are close to the edges they are not visible in reflections as well.
Here's a picture of issue in the RTX-Issue project at repo :

Now when camera gets closer to the boxes we can see lights are reflected :

How can I fix it?


text:
How do I use shader to draw only outline of a cross section in unity?
How to draw a 2D cross-section of a 3D object?
I used the shader from the answer and it works great, but I am wondering how do I draw only the outline of the cross-section(as opposite to the whole plane)?
I am a beginner in shaders so I would really like some help. Can I first detect if the vertex is on the plane in vertex shader and then pass that info to pixel shader? How can I achieve that?


text:
How do you update a non-renderable texture in webgl2 if you cant bind it to a framebuffer?
This is a noob question but I am stumped. I have a texture that stores x and y velocities. These velocities can be positive or negative so I need a texture that can store negative values. I can make the texture fine:
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8_SNORM, height, width, 0, gl.RGBA, gl.BYTE, null);

The issue is that I want to be able to update the values in the texture but I don't think you can write to the texture using a framebuffer because per the webgl2 documentation textures with negative values are unrenderable.
const fbVelocity = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fbVelocity);
gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, velocityTexture, 0);

Webgl2 returns the error Framebuffer is incomplete: 36054. That makes sense as the texture type is unrenderable so of course trying to write to it with a frame buffer doesn't work!
My question is how are you supposed to update the texture if you cant use a frame buffer? I saw options of using it as a uniform in a shader that writes to another texture but wouldn't that new texture be unable to store negative values?


text:
Rotating Body Sprites of Snake depending on Direction Moving
Saw a thread with the same issue, but didn't seem like the question was answered: Snake Game body rotation
As shown in the above thread, I have a Snake game that I'm developing for a project. I have made two sprites: "SnakeBodyVertical.png" and "SnakeBodyHorizontal.png".
I wish to swap between these two sprites for each body sprite of the snake object depending on if the body part is moving in a horizontal direction, or vertical direction. But I'm unsure of how to do this.
My Current Snake Movement Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Snake : MonoBehaviour
{

    private Vector2 _direction = Vector2.right;
    private List<Transform> _segments = new List<Transform>();
    private KeyCode lastHitKey = KeyCode.D;

    public Transform segmentPrefab;
    public int initialSize = 3;

    public Sprite SnakeHeadUp;
    public Sprite SnakeHeadRight;
    public Sprite SnakeHeadLeft;
    public Sprite SnakeHeadDown;

    private void Start()
    {
        ResetState();
    }

    // Update: Updated Once Per Time (Edit -> Project Settings -> Time (0.09) to change difficulty!)
    // This function is controlling the direction our snake moves.
    void Update()
    {

        if(Input.GetKeyDown(KeyCode.W) && lastHitKey != KeyCode.S)
        {
            this.gameObject.GetComponent<SpriteRenderer>().sprite = SnakeHeadUp;
            lastHitKey = KeyCode.W;
            _direction = Vector2.up;

        } else if (Input.GetKeyDown(KeyCode.S) && lastHitKey != KeyCode.W)
        {
            this.gameObject.GetComponent<SpriteRenderer>().sprite = SnakeHeadDown;
            lastHitKey = KeyCode.S;
            _direction = Vector2.down;

        } else if (Input.GetKeyDown(KeyCode.A) && lastHitKey != KeyCode.D)
        {
            this.gameObject.GetComponent<SpriteRenderer>().sprite = SnakeHeadLeft;
            lastHitKey = KeyCode.A;
            _direction = Vector2.left;

        } else if(Input.GetKeyDown(KeyCode.D) && lastHitKey != KeyCode.A)
        {
            this.gameObject.GetComponent<SpriteRenderer>().sprite = SnakeHeadRight;
            lastHitKey = KeyCode.D;
            _direction = Vector2.right;
        }
    }

    //This transforms the position of our snake head, rounded to a whole number. This should force our snake to move in a grid.
    private void FixedUpdate()
    {
        for (int i = _segments.Count - 1; i > 0; i--){
            _segments[i].position = _segments[i - 1].position;
            _segments[i].rotation = _segments[i - 1].rotation;
            Debug.Log(_segments[i].rotation);
        }

        this.transform.position = new Vector3(
            Mathf.Round(this.transform.position.x) + _direction.x,
            Mathf.Round(this.transform.position.y) + _direction.y,
            0.0f
        );
    }

    //Function handles the logic of iterating in reverse from a list of prefabs of our snake segments, to create a new snake segment.
    private void Grow()
    {
        Transform segment = Instantiate(this.segmentPrefab);
        segment.position = _segments[_segments.Count - 1].position; //from the list of our segments, get the very last segment (-1)

        _segments.Add(segment);
    }

    //Function handles the logic of resetting the state of our game upon collision with objects other than food
    private void ResetState(){

        //emptying the snakelist
        for(int i = 1; i < _segments.Count; i++)
        {
            Destroy(_segments[i].gameObject);
        }

        _segments.Clear();
        _segments.Add(this.transform);

        //resetting our snake from 1 back to initialsize (3)
        for(int i = 1; i < this.initialSize; i++)
        {
            _segments.Add(Instantiate(this.segmentPrefab));
        }

        this.transform.position = Vector3.zero;
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if(other.tag == "Food"){
            Grow();
        } else if (other.tag == "Obstacle"){
            ResetState();
        }
    }
}

I would like any recommendations on where to find content to answer this question, and or advice on solving this issue. I'm relatively new to coding so be nice :)
Thank You!


text:
How to map south button on gamepad to behave like the left mouse button?
How would I tell Unity that the left mouse button is being pressed when I actually press the south button on a gamepad?

Which input handling are you using - the legacy Input Manager, or the new Input System Package? What outcome do you want this virtual mouse click to trigger? Some actions have shortcuts that make this very easy, but to show you that we need details of your use case, because the exact steps differ.


text:
IsTouchingLayers() does not detect collision
I'm making a tile-based player controller for a top-down game that first throws out a "move point" transform to see if its path is clear, then moves to it if the move point does not collide with anything. I would really like to do this with layers, because making a simple "walls" layer to place colliders on would make development really easy, but I can't make this code work.
(also I am extremely new to Unity, C#, and stack exchange, heads up)
The code is as follows (included in the update function):
// Collision detection
        if (transform.position != movePoint.transform.position)
        {
            if (movePoint.GetComponent<CircleCollider2D>().IsTouchingLayers((1 << 3)))
            {
                Debug.Log("Collision");
            }
            else
            {
                // Move player
                transform.position = movePoint.transform.position;
                Debug.Log("Move");
            }

            // Reset movePoint position
            movePoint.transform.position = transform.position;
        }

Even when I attempt to move directly into the wall, moving still works and I only get the "Move" debug message in the console. Can anybody help me understand why this doesn't work?

Have you considered dispensing with the second transform entirely and instead using Physics2D.OverlapCircle or Physics2D.CircleCast?


text:
How can I attach an UI Builder/ Toolkit based wrist UI/ virtual smart watch to the wrist in XR?
I have a Unity project based on https://developer.oculus.com/documentation/unity/ using Unity 2021.3.23f1 .
The OVRPlugin is set to OpenXR.
In XR Plugin-In Management Oculus is selected.
The Interaction SDK and Meta Avatar SDK is added per guidelines.
https://developer.oculus.com/documentation/unity/unity-isdk-create-ui/ describes how to set up an UI, but neither it is UI Toolkit/ Builder based, nor attached to the wrist.
Does someone know of an example how to attach an UI (or whatever else) to the wrist?
The examples I found where all based on the generic XR solutions of Unity, but not the SDKs of Meta.


text:
Better Alternative than Sprite Masks in Unity?

I am have blank sqaure sprite as a Fog of war and I am spawning multiple sprites masks when the player starts moving, through this I am to get this effect where only places where the player has travelled is revealed. But this causes too many Spritmasks to be spawned which significantly lowers the performance. Is there a better way for fog of war reveal other than sprite masks?

Presumably you've searched "how to make fog of war effect in Unity"? How have you tried implementing the guidance you've found so far?


text:
How do I load a scene in Unity for the current client, but not any other client?
I'm currently using NetworkManager.Singleton.SceneManager.LoadScene using the Netcode package, but it loads the new scene for both the current player and any other connected clients. I want it to only load for the current player, such that for the current player the other clients player prefabs are destroyed, but not the current player's and vice versa for the other clients. That way I can have multiple rooms, and when you enter the same room as someone else you can see them. How would I do this?
The code looks something like this and is placed on the player prefab
public class MultiplayerController : NetworkBehaviour
{
   void Update(){
      if (Input.GetButton("Jump")) //Transform
      {
            NetworkManager.Singleton.SceneManager.LoadScene(sceneNames[1], LoadSceneMode.Single);
      }
   }
}

I haven't used NetworkManager, but it sounds like you should disconnect from the players in the current room before entering a new room with new players.


text:
ReorderableList - Seemingly forced to get element's SerializedProperty in a weird way
I inherit from this and then make instances of the children:
public abstract class Connection : ScriptableObject
{
    public State nextState;
}

And then I hold those children in a list:
public class State : ScriptableObject
{
    public List<Connection> connections;
}

And am making it look pretty in the inspector:
[CustomEditor(typeof(State))]
// If you are wondering why this is of State
// it's because state has multiple lists of different types that I want to render in the same way
public class StateDrawer : Editor
{
    SerializedProperty connectionsProp;
    ReorderableList connectionList;

    private void OnEnable()
    {
        connectionsProp = serializedObject.FindProperty($"{nameof(State.connections)}");
        connectionList = DrawList<Connection>(connectionsName, connectionsProp);
    }

    private ReorderableList DrawList<T>(string name, SerializedProperty property)
    {
        ReorderableList list = new ReorderableList(serializedObject, property, true, true, true, true);

        list.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
        {
            SerializedProperty element = list.serializedProperty.GetArrayElementAtIndex(index);

            // this displays a Connection from the list on State
            EditorGUI.PropertyField(rect, element, GUIContent.none);

            // works great so far

            ...

// elsewhere

    public override void OnInspectorGUI()
    {
         serializedObject.Update();
         connectionList.DoLayoutList();
         serializedObject.ApplyModifiedProperties();
    }

I thought the following would have worked, but it did not:
// Note: still inside drawElementCallback

SerializedProperty nextState = element.FindPropertyRelative("nextState");
EditorGUI.PropertyField(rect, nextState);

// Output: nextState always null

Here is what actually worked:
// Note: still inside drawElementCallback

SerializedProperty thisConnectionProp = connectionsProp.GetArrayElementAtIndex(index);
Connection connectRealObj = thisConnectionProp.objectReferenceValue as Connection;
SerializedObject objRef = new SerializedObject(connectRealObj);

objRef.Update();

SerializedProperty testProp = objRef.FindProperty($"{nameof(Connection.nextState)}");

EditorGUI.PropertyField(rect,testProp);

objRef.ApplyModifiedProperties();

The reference in editor works fine, values update and save through the various linked ScriptableObjects.
Why did the first way not work? Is my solution in danger of breaking a value at some point?


text:
Why is this script not working when the tool is equipped?
So, I am trying to make it so when a tool (L1) is equipped, a proximity prompt appears, but my current script doesn't work. Here it is:
local Prompt = script.Parent
local Event = game.ReplicatedStorage:WaitForChild("Events"):WaitForChild("HeavyDoor"):WaitForChild("RemoteEvent")

local Player = game.Players.LocalPlayer

Prompt.Enabled = false

local function IfEquipped()
    Prompt.Enabled = true

    Event:FireServer()

   end

Player.Backpack.L1.Equipped:Connect(IfEquipped())

I'd appreciate help! Thanks

What happens when you try to use this script? Does nothing happen? Does something different from what you wanted happen? Do you see an error message in the log? The more details you can share, the faster users here can help narrow down the problem and suggest solutions.


text:
recording game object movement values for use in interpolation
I am looking for a way to record the position and velocity of each object in a game scene relative to the viewing camera and cross-reference that with direct extraction of the game's models, textures, and post-processing effects in order to automatically draw a new frame based on directly interpolating the object positions.
This is for a few games, all of which already exist and were made by other people
the list of games is as follows:
PC Building Simulator,
Scrap Mechanic,
BeamNG.drive,
Minecraft (modded)


text:
Unity SetActive(true) not working for panel
So I have a finishMenu that I'd like to activate when the player finishes the level. I have a UI container (canvas) that contains among other things, my finishMenu. When colliding with a finish pad, the player script executes EndLevel(). It executes a lot of stuff, but it also calls the Finish() function on my UI container:
public void Finish()
{
    Debug.Log("Finish Called!");
    finishMenu.SetActive(true);
    Debug.Log("self: " + finishMenu.activeSelf + " hierarchy: " + finishMenu.activeInHierarchy);
    Time.timeScale = 0f;
}

this is supposed to set it to active, and I'm not getting any errors. The second Debug.Log tells me that finishMenu is activeSelf but not activeInHierarchy, even though the parent gameObject (UI container) is active...

I have assigned finishMenu in the inspector, so I don't know what to do...
I have tried debugging with the Debug.Logs and breakpoints, and searching through my code to see if something is setting it to inactive, but I haven't found the answer yet. The finishMenu is supposed to activate, but it doesn't activate.

You've cropped this screenshot so tight that we can't see what's above or around it. Can you walk us through the steps needed to create a Minimal Complete Verifiable Example of the problem?


text:
Adding to view angles in unity?
I'm trying to make a save/load position script in unity. I have coded the position portion but how would I go about doing this for a camera?
//Grabbing mouse input
    rotX -= Input.GetAxisRaw("Mouse Y") * xMouseSensitivity * 0.02f;
    rotY += Input.GetAxisRaw("Mouse X") * yMouseSensitivity * 0.02f;

//Applying after clamp
    this.transform.rotation = Quaternion.Euler(0, rotY, 0); // Rotates the collider
    playerView.rotation     = Quaternion.Euler(rotX, rotY, 0); // Rotates the camera

So when I press my save button it saves the view angles, but how would I write to camera/collider?
Input.GetAxisRaw gets called every frame so when I add saved values to x & y then get overwritten the next frame, since it's just going off the mouse values.
How would I go about doing this? Thanks :)

It's not clear to me what problem you need help solving. Consider showing your current save/load code to remove any ambiguity about how you've implemented this so far.


text:
OBB Collision Response (Rotational Elastic Collision)
I’m making a 3D physics simulator with OBBs and Sphere Colliders. I have all the collision detection and separation working, but I’m struggling with OBB vs Sphere collision response. I have it working with a moving sphere (with rigidbody) and a fixed OBB (no rigidbody), so the sphere bounces off the cube, but how would I go about calculating the force to apply to a rigidbody OBB colliding with either a fixed sphere or rigidbody sphere?


text:
Unity URP Invert desaturated shader effect with
I wanted to have a shader that invert and desaturate the background scene color with a mask in URP using scene color.

I made a shader within shadergraph :

And it did not render as expected, I think it does not render transparent but I'm not quite sure, for instance the image below showcase both shader with a tmpro text behind.
I found this shader where the invert effect works but it doesn't have any mask properties. How can I apply a mask onto it ? Or is there a reason the shadergraph don't work with the scene color ?
Here are both rendering:

Working on Unity 2020.3.25f1 and URP 10.7
EDIT:
I managed to make this shaders implementation, it invert following the mask but doesn't give the desaturated look:
Shader "Unlit/invert_Mask"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent" }
        Cull off

        Blend SrcAlpha OneMinusSrcAlpha
        AlphaToMask On

        Blend OneMinusDstColor Zero
        AlphaToMask On

        Pass
        {
            CGPROGRAM

            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0 Alpha:Blend

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            bool invertMask;

            fixed4 _Color;
            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col;
                col.rgb = _Color;
                col.a = tex2D(_MainTex, i.uv);
                return col;

            }

            ENDCG

        }

    }
    FallBack "Diffuse"
}


text:
Realtime water UE5
I want to implement a small VR game where by pressing the LMB the character will create an invisible object that will push the water in front of him. With which plugin can this be implemented? We used Zebra Liquid Free, but no water was generated, although we did everything according to the guide.

We won't answer "which technology to use" questions like "which plugin to use" here. But we can help you troubleshoot what went wrong with your Zebra Liquid attempt if you edit your question to walk us through how you set it up, and what you expect want/to happen.


text:
How do pick up nearby items only?
I am trying to build an inventory system to pick up items depending on arrays. But the problem is when I pick up an item, all other items are picked up together.  I want to collect each item alone.
THE CODE IS BELOW:
public class EquipItem : MonoBehaviour
{
    public GameObject[] Items;
    public Transform []CollectedItems;
    public RawImage[] ItemImages;
    public string [] names;
    public GameObject PicUp_TXT, Drop_TXT;
    bool disabledItem = false;
    public bool ItemCllected;
    float Timer , MaxTimer = 9;
    int counter = 0;

    enum tool { Pilers, ScrewDriver, Wrench, Cutter };

    void Start()
    {
        foreach(GameObject Item in Items)
        {
            Item.GetComponent<Rigidbody>().isKinematic = true;
        }

        foreach(RawImage ItemImage in ItemImages)
        {
           ItemImage.enabled = false;
        }

        PicUp_TXT.SetActive(false);
        Drop_TXT.SetActive(false);
        ItemCllected = false;
        Timer = 0;
    }

    public void EquipedItem()
    {
        for (int i = 0 ; i < CollectedItems.Length; i++)
         {

                    Items[i].GetComponent<Rigidbody>().isKinematic = true;
                    Items[i].transform.position = CollectedItems[i].transform.position;
                    Items[i].transform.rotation = CollectedItems[i].transform.rotation;
                    Items[i].GetComponent<MeshCollider>().enabled = false;
                    Items[i].transform.SetParent(CollectedItems[i]);
                    ItemImages[i].enabled = true;
                }

        ItemCllected = true;
    }

    private void OnTriggerStay(Collider other)
    {
        //Picup Item
        if (other.gameObject.tag == "Tools")
        {
            //if (Item)
                PicUp_TXT.SetActive(true);
            if (Input.GetKey(KeyCode.E))
            {
                EquipedItem();

                //CollectedItem.gameObject.SetActive(false);

            }
            if (ItemCllected)
            {
                PicUp_TXT.SetActive(false);
                Drop_TXT.SetActive(true);
            }
        }

        //Drop Item
        Timer = Timer + Time.deltaTime;

        if (Timer >= MaxTimer)
        {
            Drop_TXT.SetActive(false);
        }

    }

    private void OnTriggerExit(Collider other)
    {
        PicUp_TXT.SetActive(false);
    }
}

Any suggestions, please?

Your OnTriggerStay is not using the element you select, instead it just calls the method of EquipedItem DropItem and from there you go over all the items you have. Instead you want to work with just the one that you triggered

You said you want to "drop and pick up each item separately", but you didn't tell us what behavior exactly you want when there are multiple items that could be picked up or dropped. How do you want the game to decide which one to drop or pick up?

@Zibelas I am a very beginner in unity and I don't know how to do that. Please if you can modify the code better do it.

@Philipp I should pick up an item when I become close to it. In my code when I go to an item and press E all items are picked up.

It seems like your question is about two different problems that seem related but are actually very different: picking up items and dropping items. Stack Exchange question should always be about one problem at a time. You seem to be more interested in picking up than in dropping, so I think we should focus on that.

I edited your question to focus on the picking up problem for now. Feel free to ask a separate question about the dropping problem.

@Philipp the problem is one because when I pick it up I also want to drop it.

No, it's not one problem, it's two different problems. Trust me with that. You will see when you see and understand the solutions to the two problems.

@Philipp thank you very much it works now. I asked about the drop items I hope you can answer me soon.

What you currently do, is that you check if the player is in any collider with the tag "Tools", and if so, you use a for loop to go through the whole array of possible tools and set each one to the picked up state.
What you need to do is:

find out which tool is represented by the collider the player is in
use that information to pick the right tool to pick up

So first, how can we find out which tool is represented by the collider? One solution would be to add a component that contains this information and add it to those objects. Let's call it ToolPickup. All this component does is hold the information which tool is controlled by this collider. And because you are using  arrays to address the tools, we can use the array index for that:
public class ToolPickup : MonoBehaviour {
    public int toolIndex;
}

Attach this component to each "tool" in the world and set the "Tool Index" in the inspector to the array index of the tool it represents.
Now, in your OnTriggerStay method, you can extract that information and pass it to the EquipedItem method:
if (other.gameObject.tag == "Tools")
{
    /*...*/
     if (Input.GetKey(KeyCode.E))
     {
         var toolPickup = other.GetComponent<ToolPickup>();
         if(toolPickup != null)
         {
             EquipedItem(toolPickup.toolIndex);
         }
     }

The EquipedItem method needs to be modified to take an array index as a parameter and then only change the state of the tool with that array index:
public void EquipedItem(int toolIndex)
{
     Items[toolIndex].GetComponent<Rigidbody>().isKinematic = true;
     Items[toolIndex].transform.position = CollectedItems[toolIndex].transform.position;
     Items[toolIndex].transform.rotation = CollectedItems[toolIndex].transform.rotation;
     Items[toolIndex].GetComponent<MeshCollider>().enabled = false;
     Items[toolIndex].transform.SetParent(CollectedItems[toolIndex]);
     ItemImages[toolIndex].enabled = true;

     ItemCllected = true;
 }


text:
How to mod position of camera when crouching in 7 Days To Die?
I am talking about the first person camera. It is not glued at the player's head position; it moves away a bit. It seems linked to the 3D model and not to the capsule collider that shrinks when we crouch.
SCore's "crouch thru 1 block" option still has the same problem I describe below, so it is not an option unless yours is working properly.
For example, in the file resources.assets, the variable PhysicsCrouchHeightModifier determines the crouch height. Anything below 0.50 will let you move through 1 block tunnels.
But the problem is that the camera will not follow that 0.50 or 0.40 crouch height. The camera will be positioned above and inside the block above the player. That is really bad because there is mesh backface culling so we can see through the back faces of blocks and even shoot through them. :(
If we could disable backface culling it could help already, so we would stop seeing behind walls, which breaks the game.
But the best thing would be to tweak the distance the camera is allowed to be placed away from the player head location.
To test what I mean, try to place an inverted ramp like this:
. \__
.@___

The player is the @.
When you crouch below the ramp, the camera may go as down enough to be able to look correctly through the 1 block tall tunnel.
But as soon you move a bit forward, the camera jumps up again, above the 1 block tall tunnel and inside the block above it :(
So, it seems that there is a max distance the camera is allowed to stay away from the player head location, it seems to be between 0.12f and 0.25f. But what I need to know is: what is the name of the variable that could control that?

Alternatively, a patch for SCore 1 block crouch, could do the trick:
https://github.com/SphereII/SphereII.Mods/blob/master/0-SCore/Harmony/PlayerFeatures/OneBlockCrouch.cs
There is a commented code there.
it is about getEyeHeight (so the camera would be properly repositioned).
i guess it was a test that did not work right? Otherwise that code would not be commented.
I got a hint to create a 2nd camera to use only when crouched, on that file. I guess such camera would be independent and not affected by other parts of the code, therefore it would probably be easier to make it work as intended.


text:
Minimal number of pairwise signals (mutexes) to follow a schedule
For a factory simulation, NPCs walk a path and stop in between to do things in work areas.
My task is to find the best work schedule. The NPCs can of course collide with each other on their way.
This must be prevented. For this, a collision area can be calculated beforehand (a simple box). There the NPCs "can" collide,
but they do not have to. Each waypoint of the NPCs has a predetermined time, but it can be longer (if the NPC is stopped by an obstacle).
The API of the simulation has the following limitations:

A collision box can only be calculated pairwise (NPC A <-> NPC B).
NPCs can only communticate pairwise (NPC A -> B or B -> A).
Communication happens with Enter(int id) (similiar to mutex[id]->aquire()) and Exit(int id) (similar to mutex[id]->release()) calls. I call them "signals".

First I created a simple graph where the waypoints with the times are inserted.
Then I create connections between the NPCs, if a path is in a collision area, to find a collision-free
topological sorting (without deadlock). This works well so far.
The graph looks like this (collision area is marked red, found ordering is first C then A then B).
Only the generation of signals is my problem.
I can't create a global "index" that indicates which NPC's turn it is. NPC A has no idea about the signals between NPC B and C.
Nevertheless, the sequence should be strictly followed, even if the path of an NPC should be delayed.
Also, the number of signals should be as minimal as possible (since there is only a limited number).
The problems in short:

How can I keep the order of a schedule if only pairwise communication between NPCs is possible?
What is the lowest number of "signals" (or mutexes) needed?

If there is already a name for this problem, I haven't found it yet and would be grateful for this information as well.


text:
How can I change the color of a BitMapFont that is already generated by FreeTypeFontGenerator in render
I'm trying to make a start loading screen with Fade In effect.
I've made a simple Animation generator and it works fine when I apply the alpha value for the sprite
,but when I try to apply the same alpha for a bitmapfont which is generated from a ttf file, the setColor won't affect the color of bitmap font. am I missing something or this is a bug/feature?
here is my code:
generating font:
parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.characters=generator.DEFAULT_CHARS;
parameter.color= new Color(70f/255f,40f/255f,190f/255f,1);
parameter.shadowColor=parameter.borderColor= new Color(0.5f,0.5f,0.5f,0.5f);
parameter.shadowOffsetX=6;
parameter.shadowOffsetY=6;
parameter.size=100;

generator= new FreeTypeFontGenerator(Gdx.files.internal("type_tahrir.ttf"));
font=generator.generateFont(parameter);
layout= new GlyphLayout(font,"Void Studio");

rendering font and sprite:
@Override
public void render()
{
    Gdx.gl.glClearColor(1,1,1,1);

    Gdx.gl.glClear(Gdx.gl20.GL_COLOR_BUFFER_BIT);
    deltaTime= Gdx.graphics.getDeltaTime();

    alpha=logoAnimation.update(deltaTime).alpha;

    camera.update();

    logoSprite.setAlpha(alpha);

    font.setColor(70f/255f,40f/255f,190f/255f,alpha);

    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    logoSprite.draw(batch);
    font.draw(batch,layout,1000-layout.width/2,300);
    batch.end();
}

TL;DR is it possible to change color of bitmap font after being generated via FreeType
Info: libgdx and gdx-freetype version 1.9.0


text:
Strange edge seams when subtracting a cylinder from other shapes
I'm just starting with UE 5.1 and I'm noticing weird behavior when I use cylinder to subtract from other shapes. I tried adding more sides to make it smoother but these weird artifacts still persist in both editor and in gameplay. Is there maybe some rendering setting I have to enable/disable or some other trick?


text:
How do phase conjugating mirrors look like in render?
This question might not fit this community standards, so it might be closed in the future. I am interested in physics and I recently learned about phase conjugating mirrors. These are very special, because they bounce back light in the direction it came from, instead of obeying the usual Snell's law. It looks something like this:

This is very interesting, because it can be used to "undo" distortion like this:

My question is if somebody who has ever written a ray tracer/path tracer could implement this in an object. I'm very interested to see the result, but I have never written one of these myself and it would be overkill to write one for this result.
Image source: http://slehar.com/wwwRel/PhaseConjugate/PhaseConjugate.html

This does not seem to be a question about how to develop a new game or game mod, which is what we answer here. Can you edit your question to frame it in terms of a game or game mod you are making, or take it elsewhere, like to the Physics or Computer Graphics StackExchange sites? (Be sure to check their on-topic guidelines first)


text:
List is keep adding the same items over again and how to make the textfield width to be fixed? and fix List adding the same items over again
This is the default window when opening it , it's showing gameobjects with scripts , each gameobject and the script attached to it.

now the problems:
when I'm typing in the search field for example guid and it's showing the gameobjects with any script that contains in the name guid attached to them the yellow Script label is not directly above the textfields of the script's names.
the problem in this case is when I filter for example typing guid the vertical bar on the right is gone and then the textfields width is getting longer and then the yellow "Script" label is not above the textfields directly:

the second problem is when I type guid and it's filtering. then when I'm opening the window again and typing guid again it will remember the old results from before when I typed guid and will display them too and each time I will open the window and type guid it will keep adding the last results with the new once:
in this example it's showing the same guid results 3 times:


text:
Sprite Asset Optimisation
I am writing a game for Android which combines open world questing and an RPG party development playstyle, and as such, I am finding it a very tight balancing act to get more content into that game that looks good, versus being limited with the amount of memory that an app can use without Android getting cranky about it.
I've been purchasing various assets to use for it, and have a good bunch of sprites to use, but when I wrote a calculator into my editor to instantly show me how much memory the bitmaps would consume when storing them I got some nasty shocks. So, I am looking to write some code into the editor first to at least optimise the size of each sprite frame in a model.
Some of the assets I have for example might have a spritesheet where the base sprite size is 300x300, even though the model itself is closer to 150 high. for example. I'm thinking of quickly parsing the spritesheet into the editor, checking to see if there are common areas of each sprite across the entire file that can be clipped - and then clip them out from every single sprite. That will leave me a sprite which has consistent sizing to the outer extremities of ANY of the sprites for that model. However, that means that individual sprites may still not be overly optimised.
In a well optimised engine, would each sprite be shrunk down to these minimal sizes and then rendered with offsets for each frame so that it appears centered - or would it be common practise to have each sprite in a single animation the same size, and just concede that there will be some animations that don't utilise the entire size of the bitmap and there will be sub-optimal memory usage for those?
An example would be a sprite where a character has both arms out, or both arms at their sides. In theory, when the arms are down, the width of the image could be narrower and rendered to account for that narrowing in that frame.

You tackle 2 issues here: 1 - it is generally worthless to ship game with assets that are bigger than they need to be, it's just a waste of space. You can easily "pre-process" all the assets into "correct" size on build. 2 - trimming sprites is an easy optimization, most of the games use it. thats why so many spritesheets are actually atlases (tightly packed).


text:
How to break out of nested loops?
Is there a way in Godot's GDScript to quickly/easily break out of nested loops?
For example:
# Check if the entire grid is filled.
filled = true
for x in grid:
    for y in grid[x]:
        if grid[x][y] == null:
            filled = false
            break # Break out of both loops?

PHP's break has an optional numeric argument that allows breaking out of nested loops: https://www.php.net/manual/en/control-structures.break.php
And Python has a for...else construct that can be used for this purpose: https://stackoverflow.com/a/3150107/4168619
Is there anything similar in GDScript?

Option1 Use an extra bool flag to break
extends Node2D

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = true
    for row in grid:
        var isBreak = false
        for data in row:
            if data == null:
                filled = false
                isBreak = true
                break
        if isBreak:
            break
    print(filled)

Option2 Use return
extends Node2D

func isFilled(array):
    for row in array:
        for data in row:
            if data == null:
                return false
    return true

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = isFilled(grid)
    print(filled)

Option3 flatten the array and use a single loop
(use append or append_array or +):
extends Node2D

func flatten1(array):
    var result =[]
    for row in array:
        for data in row:
            result.append(data)
    return result

func flatten2(array):
    var result =[]
    for row in array:
        result.append_array(row)
    return result

func flatten3(array):
    var result =[]
    for row in array:
        result+=row
    return result

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = true
    for element in flatten1(grid):
        if element==null:
            filled = false
            break
    print(filled)

(use reduce):
extends Node2D

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = true
    for element in grid.reduce(func(acc, x): return x+acc):
        if element==null:
            filled = false
            break
    print(filled)

Option4 Just check if the entire grid is filled
(use reduce and has)
extends Node2D

func _ready():
    var grid = [
        [1,2,3],
        [4,5,6],
        [7,null,9],
    ]
    var filled = !grid.reduce(func(acc, x): return x+acc).has(null)
    print(filled)

Related link: Godot Engine 4.0 documentation:Array

Some languages, such as C#, doesn't have such feature, but there are workarounds.
I'd prefer to put the code in a seperate function, and then use return; or return [value]; the moment you got the value you wanted.
Going through each loop with a boolean check (like if (filled == false) break;) is also possible in larger nested loops.

C# has such a feature, it's just not considered good coding style in many cases: goto will break out of any number of nested loops. As long as you only ever use forward gotos, (jumping to a label strictly later in the same function), you avoid the worst problems with them. But it's still usually a code smell and a sign that there's a better way to structure the algorithm so that you don't need it, like your return suggestion.

I've been strictly teached to never use goto in any scenario, for the reasons you mentioned. So even suggesting goto as an option would've been a bad habit for me. But yeah, technically it is an option.


text:
How can I modify a Unity Sprite Shader to create a black outline around the Sprite in addition to a flashing color effect?
I would like to be able to make a Unity Sprite flash 2 colors:

The entire sprite should flash Red (or whatever color is defined in the Sprite Color setting).
There should be a Black outline around the Sprite.

DMGregory wrote the following code which modified the default Sprite Shader to wonderfully achieve the first goal:
    Pass
    {
    CGPROGRAM
        #pragma vertex SpriteVert
        #pragma fragment ColorLerpFrag // Use our version instead of the default.
        #pragma target 2.0
        #pragma multi_compile_instancing
        #pragma multi_compile_local _ PIXELSNAP_ON
        #pragma multi_compile _ ETC1_EXTERNAL_ALPHA
        #include "UnitySprites.cginc"

        fixed4 ColorLerpFrag(v2f IN) : SV_Target
        {
            // Sample sprite texture.
            fixed4 c = SampleSpriteTexture (IN.texcoord);
            // Blend toward sprite component color depending on its alpha.
            c.rgb = lerp(IN.color.rgb, c.rgb, IN.color.a);
            // Pre-multiply alpha to work with the blending function.
            c.rgb *= c.a;
            return c;
        }
    ENDCG
    }

I have tried modifying the shader to also add a black outline around the Sprite, but can't get it to work.
Another possibility is to clone the GameObject with the Sprite Component, center the Sprite, turn it Black and then scale it up slightly.  But it would be much better if this effect could be achieved with a shader, as cloning would add to the memory footprint.
Is it possible to modify the shader further to also create a black outline around the Sprite?

It's cheaper to get high-quality outlines if you can sample a signed distance field — say stored in the sprite's alpha channel. If that's not practical, then you have to sample the sprite multiple times at nearby locations to detect how close you are to an edge, and that sampling gets more expensive the thicker the outline needs to be (or the higher fidelity you want at corners/fine features).


text:
So - Multi Draw Indirect, or batching?
I am not sure which one is better. Is Multi Draw Indirect just an easier, better, way than batching everything into one regular draw call, if you're using 4.3+? You can use VertexAttribDivisor with this, for example...
And you also don't have to setup a batching system yourself (it would require some work to get multi draw indirect to work, but it has some advantages which makes it seem easier to implement, and may be faster than a home-made batching system).
What are people's thoughts on this?

isn't multidrawindirect even better "batching"? You could multi-draw-indirect just one batch, or lots of batches at once


text:
3d camera control on XY plane controlled by mouse
I am creating a 3d game with a isometric view. I have a problem implementing camera controls. I can control angles of camera, but my view is scrollable only in the XY axis (camera is always up, Z axis). For now controlling camera works but it moves proportionally to the mouse movement. This makes the forward/backward movement much slower than left/right. I would like it to work in such a way that if I have an object under the mouse when I start scrolling, it will also be under the mouse when I finish scrolling the view. I'm guessing the solution to the problem will be a bit of maths and matrices. I've tried to search for some examples but failed. I'm attaching link to video to show how it's working now, if something is not clear I will try to explain more clearly. Please give me some advices how I can solve this.
https://www.youtube.com/watch?v=mPufuBV04M4


text:
Buy button not working
I'm working on a Roblox tycoon game. I don't know how to allow the player to buy things because just using: if tycoonPlayerMoney.Value >= 10  then. doesn't work.
Here's the script:
CurrencyName = "Money" --Name of the currency
StarterValue = 300   -- How much money You start with

--------------------------------Variables---------------------

v = script.Parent.Values.OwnerValue
m1 = game.ReplicatedStorage.Mosques.Mosque1 --- Building of the tycoon
b = script.Parent.b --- Purchase Buttons

PayOut = 2 -- Amount of pay
WaitBetweenPayout = 10 -- How long it will take for the next pay
--After touching tycoon door
script.Parent.Touched:Connect(function(Hit)
---Make owner
    if Hit.Parent:FindFirstChild("Humanoid") and v.Value == nil then

        local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)

        v.Value = Player

        script.Parent.Transparency = 1 -- Door transparent
        script.Parent.CanCollide = false -- Door CanCollide off
        script.Parent.SurfaceGui.TextLabel.Text = tostring(v.Value).."'s Mosque" --Change Door Text

        local Repeat = true  --Repeat giving currrency

        local fold = Instance.new("Folder", Player) ----Currency
        fold.Name = "leaderstats"
        tycoonPlayerMoney = Instance.new("IntValue", fold)
        tycoonPlayerMoney.Name = CurrencyName
        tycoonPlayerMoney.Value = StarterValue

        while true do ---Repeat paying every 10 seconds
            wait()
            if Repeat ==  true then
                wait(WaitBetweenPayout)
                tycoonPlayerMoney.Value = tycoonPlayerMoney.Value+PayOut
            end
        end
-----Purchase Buttons
        b.a.Touched:connect(function(Hit)
            if Hit.Parent:FindFirstChild("Humanoid") then
                local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                if v.Value == Player and tycoonPlayerMoney.Value >= 10 then -- How much cost
                    m1.Mosq.Decorations.Outside.Stairs:Clone()
                    m1.Mosq.Decorations.Outside.Stairs.Parent = workspace.Mosques.mosque1
                    b.a:Destroy()
                    tycoonPlayerMoney.Value = tycoonPlayerMoney.Value - 10
                    PayOut = PayOut + 2
                    b.b.CanCollide = true
                    b.b.CanTouch = true
                    b.b.Transparency = 0
                    b.b.BillboardGui.Enabled = true --Gui that shows the price and name
                end
            end
        end)

        b.b.Touched:connect(function(Hit)
            if Hit.Parent:FindFirstChild("Humanoid") then
                local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                if v.Value == Player and  tycoonPlayerMoney.Value >= 25 then
                    m1.Mosq.Decorations.Outside.Sign:Clone()
                    m1.Mosq.Decorations.Outside.Sign.Parent = workspace.Mosques.mosque1
                    b.b:Destroy()
                    tycoonPlayerMoney.Value = tycoonPlayerMoney.Value - 25
                    PayOut = PayOut + 4
                    b.c.CanCollide = true
                    b.c.CanTouch = true
                    b.c.Transparency = 0
                    b.c.BillboardGui.Enabled = true
                end
            end
        end)

        b.c.Touched:connect(function(Hit)
            if Hit.Parent:FindFirstChild("Humanoid") then
                local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                if v.Value == Player and tycoonPlayerMoney.Value >= 45 then
                    m1.Mosq.WallsEtc.Roofnfloor.FloorF:Clone()
                    m1.Mosq.WallsEtc.Roofnfloor.FloorF.Parent = workspace.Mosques.mosque1
                    b.c:Destroy()
                    tycoonPlayerMoney.Value = tycoonPlayerMoney.Value - 45
                    PayOut = PayOut + 4
                    b.d.CanCollide = true
                    b.d.CanTouch = true
                    b.d.Transparency = 0
                    b.d.BillboardGui.Enabled = true
                    b.d.Touched:connect(function(Hit)
        b.d.Touched:connect(function(Hit)
                if Hit.Parent:FindFirstChild("Humanoid") then
                        local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                        if v.Value == Player and tycoonPlayerMoney.Value >= 25 then
                            m1.Mosq.WallsEtc.WallParts.WallPart1:Clone()
                            m1.Mosq.WallsEtc.WallParts.WallPart1.Parent = workspace.Mosques.mosque1
                            b.d:Destroy()
                            tycoonPlayerMoney.Value = tycoonPlayerMoney.Value - 25
                            PayOut = PayOut + 2
                            b.e.CanCollide = true
                            b.e.CanTouch = true
                            b.e.Transparency = 0
                            b.e.BillboardGui.Enabled = true
                    end
                end
            end)
                    b.e.Touched:connect(function(Hit)
                        if Hit.Parent:FindFirstChild("Humanoid") then
                            local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                            if v.Value == Player and tycoonPlayerMoney.Value >= 25 then
                                m1.Mosq.WallsEtc.WallParts.WallPart2:Clone()
                                m1.Mosq.WallsEtc.WallParts.WallPart2.Parent = workspace.Mosques.mosque1
                                b.e:Destroy()
                                tycoonPlayerMoney.Value = tycoonPlayerMoney.Value - 25
                                PayOut = PayOut + 2
                                b.f.CanCollide = true
                                b.f.CanTouch = true
                                b.f.Transparency = 0
                                b.f.BillboardGui.Enabled = true
                            end
                        end
                    end)
                    b.f.Touched:connect(function(Hit)
                        if Hit.Parent:FindFirstChild("Humanoid") then
                            local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                            if v.Value == Player and tycoonPlayerMoney.Value >= 125 then
                                m1.Mosq.WallsEtc.Walls.EtcRoom.Wall1:Clone()
                                m1.Mosq.WallsEtc.Walls.EtcRoom.Wall1.Parent = workspace.Mosques.mosque1
                                b.f:Destroy()
                                tycoonPlayerMoney.Value = tycoonPlayerMoney.Value - 125
                                PayOut = PayOut + 6
                                b.g.CanCollide = true
                                b.g.CanTouch = true
                                b.g.Transparency = 0
                                b.g.BillboardGui.Enabled = true
                            end
                        end
                    end)
                    b.g.Touched:connect(function(Hit)
                        if Hit.Parent:FindFirstChild("Humanoid") then
                            local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
                            if v.Value == Player and tycoonPlayerMoney.Value >= 45 then
                                m1.Mosq.WallsEtc.Walls.EtcRoom.Wall2:Clone()
                                m1.Mosq.WallsEtc.Walls.EtcRoom.Wall2.Parent = workspace.Mosques.mosque1
                                b.g:Destroy()
                                tycoonPlayerMoney.Value = tycoonPlayerMoney.Value - 45
                                PayOut = PayOut + 4

                            end
                        end
                    end)
                    end)
                end
            end
        end)
    end
end)
```

If I would troubleshoot this problem, then there are four assumptions I would want to confirm are true. 1. The code in question actually gets executed, 2. v.Value is the correct player, 3. tycoonPlayerMoney.Value contains the amount of money I expect and 4. the flow of execution does not actually continues into the then-part of the if-statement. I would confirm that by setting a breakpoint in the debugger. Can you do that?


text:
Photon Fusion Object pooling
I would like to ask if anyone has some experience in object pooling through Fusion. To sum up things im migrating from Pun2 to Fusion and need to update my object pool. My issue apart from my lack of experience is that i cant really understand the documentation.
Object Pooling
My attempt to make it work was not successful and i think i would need to use the Acquire / Release instance methods that Photon provides but i cant really find a way to do so.
using Photon.Pun;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviourPun
{
    public GameObject objectToPool;
    public int amountToPool;
    private bool isInitialized = false;
    private List<GameObject> pooledObjects;
    public bool objectsStartHidden = true;

    private void Awake()
    {
        pooledObjects = new List<GameObject>();
    }

    private void Start()
    {
        if (PhotonNetwork.IsMasterClient)
        {
            SetupPool(objectsStartHidden);
        }
    }

    public void SetupPool(bool _hidden)
    {
        if (isInitialized) return;

        if (PhotonNetwork.IsMasterClient)
        {
            for (int i = 0; i < amountToPool; i++)
            {
                GameObject tmp = PhotonNetwork.Instantiate(objectToPool.name, Vector3.zero, Quaternion.identity);
                int viewID = tmp.GetPhotonView().ViewID;
                if (_hidden)
                    tmp.SetActive(false);

                pooledObjects.Add(tmp);
                photonView.RPC("AddToPoolRPC", RpcTarget.OthersBuffered, viewID);
            }
        }
        isInitialized = true;
    }

    public GameObject GetPooledObject()
    {
        for (int i = 0; i < amountToPool; i++)
        {
            if (!pooledObjects[i].activeInHierarchy)
            {
                return pooledObjects[i];
            }
        }
        return null;
    }

    public int GetPooledObjectIndex(GameObject obj)
    {
        return pooledObjects.IndexOf(obj);
    }

    public GameObject GetPooledObject(int index)
    {
        if (index >= 0 && index < pooledObjects.Count)
        {
            return pooledObjects[index];
        }
        return null;
    }

    [PunRPC]
    private void AddToPoolRPC(int viewID)
    {
        GameObject tmp = PhotonView.Find(viewID).gameObject;
        tmp.SetActive(false);
        pooledObjects.Add(tmp);
    }
}

This was my previous attempt which worked as expected :

Create a fix amount of objects
Get one when needed
Disable it and send it back

This is the behavior i would like to do with Fusion too and hopefully sync it across all clients as ideally only the master would spawn and all clients would take those game instances.
So to sum up i have 2 questions - requests!

Given the demos photon has (tanknarok/asteroids) i see that their way of implementing this is spawn through the network realtime and just keep it there to recycle. is this ok?? I mean its subjective and tied to the amount of items you create but yeah.
Should the above way be ok or the pre spawning if anyone has any idea and could help i would appreciate it!

Thank you for your time!


text:
Solving distortion with non-linear scaling in a shader
I am currently working on implementing an older paper in Unity to show the progression of some graphics technologies, and part of that involves sprites being able to cast shadows. A trivial implementation would be to simply use a sprite of the object we already use, change it's colour, and project it underneath whatever casts that shadow.

Because shadows don't spread out directly the shadow casting object if one were to use a spherical light source, it would be nice to be able to adjust the width of the shadow so that the "top" of the shadow can be wider than the "base" (similar to a trapezium).
My approach has been to use a shader that can modify the vertices with a transformation matrix, as seen in the relevant code snippet below.
v2f vert(appdata_t IN) {
v2f OUT;
OUT.texcoord = IN.texcoord;
OUT.color = IN.color;
float sX = _ScaleX;
float sY = _ScaleY;
float scaleX = sX * OUT.texcoord.y + 1.0;

float4x4 transformMatrix = float4x4 (
    scaleX,0,0,0,
    0,sY,0,0,
    0,0,1,0,
    0,0,0,1
);

float4 skewedVertex = mul(transformMatrix, IN.vertex);
OUT.vertex = UnityObjectToClipPos(skewedVertex);

#ifdef PIXELSNAP_ON
OUT.vertex = UnityPixelSnap (OUT.vertex);
#endif

return OUT;

This unfortunately produces these strange results, which I can't seem to figure out the cause of, but my suspicions are that the UV-coordinates having an origin in one corner of the sprite might have at least something to do with it. Changing the pivot of the sprite from bottom to bottom left doesn't solve it, and instead produces different distortions. The shape displayed in the preview panel of the inspector looks right as well, so I am quite confused.

Thanks to a reply from DMGregory the problem likely arises from applying a non-affine transformation. In order to remedy this, one could use projective coordinates. What I am reasonably certain I've done is add an extra dimension to the input texcoord. This doesn't change anything when I scale everything with a set constant (like 2.0 in this case, picked very arbitrarily) as one would expect, since we would just be multiplying and dividing by the same value, but how does one go from this to proper projected coordinates described in the answer to another question, also by DMGregory.
v2f vert(appdata_t IN) {
    v2f OUT;
    OUT.texcoord = float3(IN.texcoord.xy * 2.0, 2.0);
    OUT.color = IN.color;
    float sX = _ScaleX;
    float sY = _ScaleY;
    float scaleX = sX * OUT.texcoord.y/2.0 + 1.0;

    float4x4 transformMatrix = float4x4 (
        scaleX,0,0,0,
        0,sY,0,0,
        0,0,1,0,
        0,0,0,1
    );

    float4 skewedVertex = mul(transformMatrix, IN.vertex);
    OUT.vertex = UnityObjectToClipPos(skewedVertex);

    #ifdef PIXELSNAP_ON
    OUT.vertex = UnityPixelSnap (OUT.vertex);
    #endif

    return OUT;
}

fixed4 frag(v2f IN) : SV_Target {
    float2 uv = IN.texcoord.xy / IN.texcoord.z;
    fixed4 c = tex2D(_MainTex, uv) * IN.color;
    c.rgb *= c.a;
    return c;
}

This previous Q&A about fixing UV mapping artifacts on a tapering mesh may be helpful to you.

Interesting! I did not know that UV transformations had to be affine, I'll read further but that certainly provides some more insight.

If you need help adapting the answer there to solve the problem you've shown here, try editing your question to show where you're stuck.

You missed a step:

Given a scale factor at each point (say, equal to the breadth of your strip at that spot), you can construct the 3D projective uvw coordinate from your regular 2D uv coordinate this way:
Vector3 uv3 = ((Vector3)uv2) * scale;
uv3.z = scale;

In your case that's:
float scaleX = sX * IN.texcoord.y + 1.0;
OUT.texcoord = float3(IN.texcoord.xy, 1.0f) * scaleX;

The the texture coordinates need to know about scaleX if you want them to be able to adapt to the distortion it introduces.

Yup, that does it, thanks a lot for the help!


text:
Opening JSON UI screens from entities/blocks
I'm making a Bedrock Edition mod with JSON, and I want to be able to specifically open a JSON UI screen within events of a behavior pack or in a script.
"minecraft:on_interact": {
    ...
    "event": "open_gui_screen(ui/screens/screen1.json)"
}

I've looked through all of the documentation and the Bedrock wiki, but it doesn't show much about opening a JSON UI menu through events on an entity or from the JavaScript code.