#archived-code-general

1 messages · Page 244 of 1

hard viper
#

I want to eventually cap to 30, but I want to know (as I work on project) if I do/add something that suddenly costs a lot of time

heady iris
#

isn't your texture 300x300

#

that's 90,000

hard viper
#

and I spam so many Debug tools that profiler is normally not super accurate in editor mode

rigid island
heady iris
#

don't you want unique colors?

#

make a HashSet out of it

hard viper
#

ty I'll look into profiler

rigid island
solemn bridge
# hard viper ty I'll look into profiler

You can just profile in editor, the same processes will still be present in the build, so if you see a lag spike due to some code or loading etc that should still be there in build, so if you fix the issue in editor mode that should fix it in the build

#

Also I'm not sure how the "scene" camera works as far as profiler, you'd think that the profiler would be only giving you info based on the Camera in game but i believe that in some cases the scene camera acts as a second camera

#

check if there is an impact on performance by closing the scene panel

#

I knwo this is the case for some functions like "IsInView" or whatever it is for renderers.

#

I'm not sure if its a bug or intended

rigid island
# heady iris make a HashSet out of it

does this look correct

 public static HashSet<Color> ReadPixelColors(this Texture2D texture)
 {
     Color[] cs = texture.GetPixels();
     for (int i = 0; i < cs.Length; i++)
     {
         cs[i].r = cs[i].a;
         cs[i].g = cs[i].a;
         cs[i].b = cs[i].a;
         cs[i].a = 1.0f;
     }
     return cs.ToHashSet();
 }```
#
  var hash = colorTexture.ReadPixelColors();
  foreach(var h in hash)
  {
      hashedColors.Add(h);
  }``` still white just not 90000 colors

now I remember also why I used GetPixelData 😔 
> Each pixel is a Color struct. GetPixels might be slower than some other texture methods because it converts the format the texture uses into Color. GetPixels also needs to decompress compressed textures, and use memory to store the decompressed area. To get pixel data more quickly, use GetPixelData instead.
> 
> A single call to GetPixels is usually faster than multiple calls to GetPixel, especially for large textures.
> 
> If GetPixels fails, Unity throws an exception. GetPixels might fail if the array contains too much data. Use GetPixelData or GetRawTextureData instead for very large textures.
https://docs.unity3d.com/ScriptReference/Texture2D.GetPixels.html
hard viper
#

sometimes super inaccurate

haughty echo
#

Can someone explain why this code produces this log:

private void _Release(Vector3 position = default, Quaternion rotation = default)
{
    Debug.Log($"{rotation} {rotation == default} {rotation == Quaternion.identity} {rotation == new Quaternion()}");
}

(0.00000, 0.00000, 0.00000, 0.00000) False False False

mellow sigil
#

Because you've passed an invalid quaternion as the parameter

#

Quaternion.identity (and default etc) is (0, 0, 0, 1)

knotty sun
#

no, default is 0,0,0,0 and is invalid and should never be used

hard viper
#

try showing what default is

velvet talon
#

hello i have problem. how to move smoothly objects and not on lines in unity scene?

hard viper
#

i expect default to be all 0

#

but if rotation is default, you might be getting false because == with floats is suck. just a thought

knotty sun
#

no it is false because it must pass a validation test, which it fails

hard viper
#

is that just part of the == for quaternions?

knotty sun
#

for any operation on a Quaternion

hard viper
#

because 0,0,0,0 should be an invalid quaternion

mellow sigil
#

Yes, and two invalid things are not equal to each other

hard viper
#

that’s strange tbh

#

because I would expect it to be i==i&&j==j…

haughty echo
#

Default quaternion and new quaternion struct are both all 0s

hard viper
#

yeah, then it’s the overloaded == operator

#

you can check it btw

#

just check source code for == under quaternion. hopefully it isn’t injected

haughty echo
#

I checked it, I think something else is going on, it's just a comparison of the 4 component floats

knotty sun
#

it's not, the code is very clear, only valid Qaternions allowed for operators

haughty echo
thin hollow
#

I know that you use Unity Events by += subscribing and -= unsubscribing functions to them. But, it seems I cannot find a function to unsubscribe everything from the Event?
I'm making a modal window for my UI, I want to set it up so that it hands in my main UI object, and various situations that require an y\n reaction from the player will activate that UI object and subscribe to one of it's Events. I then want to ensure that at no time no matter what no more than a single subscriber for that event exists and the past subs wouldn't linger, so in the function that gets called when a button in the modal window is pressed I want to call Invoke on the appropriate event, and then unsubscribe all subscribers from it:

        public event Action PressedOk;
        public event Action PressedCancel;

        public void CallbackOk()
        {
            PressedOk?.Invoke();
            PressedOk?.UnsubscribeAll(); // This one is missing
            this.gameObject.SetActive(false);
        }

        public void CallbackCancel()
        {
            PressedCancel?.Invoke();
            PressedCancel?.UnsubscribeAll(); // This one is missing
            this.gameObject.SetActive(false);
        }

I suspect if that function is missing, my idea for how modal popup should work isn't exactly a correct one?

knotty sun
rigid island
thin hollow
# sage latch `RemoveAllListeners`

No such function I can find, however I found a similarly sounding one, would that be correct? Not sure why it requires two arguments though, based on the description at the Microsoft docs, I think I should pass the same into both anyway.
Action.RemoveAll(PressedOk, PressedOk);

sage latch
#

for a normal event just set it to null

somber nacelle
thin hollow
#

Oh, got it, thanks!

sage haven
#

does anyone know what this line of code is doing? (the whitemask and blackmask are also integers)

const int colourMask = whiteMask | blackMask;
#

I'm not too sure what the | symbol is doing

leaden ice
#

e.g.

0b00010000 | 0b00000010

Gets you cs 0b00010010

#

In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operations and directly supported by the processor. Most bitwise operations are presented as two-operand inst...

sage haven
#

tysm

hexed pecan
hexed pecan
rigid island
rigid island
#

I want to use for other stuff too but mainly to see if what the RT camera is looking at is lit up by lights

hexed pecan
#

Because that would make it all white if it has full alpha

rigid island
#

do i need that loop at all?

rigid island
#

thanks for making me notice stupid mistake..

rigid island
#

I think the color format has something to do with it but idk how ton change it

#

here are the differences in format

hexed pecan
#

This looks like it would match RGB8

rigid island
hexed pecan
#

I can't find info about RGB8 but I guess it's 8 bits per channel

deft spear
#

Im trying to block clicks under gui button using if (EventSystem.current.IsPointerOverGameObject()) return;, but this also blocks clicks on terrain, I think because my canvas covers the entire screen?

hexed pecan
#

Or maybe it is 3+3+2.. Idk

delicate olive
rigid island
#

I tried this manual copy didn't work

#
 public static Texture2D ChangeFormat(this Texture2D oldTexture, TextureFormat newFormat, out Color32[] color)
 {
     Texture2D newTex = new Texture2D(oldTexture.width, oldTexture.height, newFormat, false);
     Color32[] cs = oldTexture.GetPixels32();
     color = cs;
     newTex.SetPixels32(cs);
     newTex.Apply();
     return newTex;
 }```
#

ir just copies it black

deft spear
#

@delicate oliveWill this check not stop me from clicking on my buildings etc. too?

delicate olive
hexed pecan
#

I would try something that has 8 bits per channel

deft spear
#

@delicate oliveYea

hexed pecan
#

Maybe R8B8G8A8_UNORM?

delicate olive
rigid island
delicate olive
rigid island
#

if you recall I had this yesterday ```cs
yield return new WaitForEndOfFrame();

newTex = new Texture2D(
renderTexture.width,
renderTexture.height,
TextureFormat.RGBAFloat,
0, false);

Graphics.CopyTexture(renderTexture, newTex);

met.mainTexture = newTex;
yield return new WaitForEndOfFrame();``` @hexed pecan

deft spear
#
        if (Input.GetMouseButtonDown(0)) {
            if (EventSystem.current.IsPointerOverGameObject()) return;

Makes me unable to click on anything else but UI

#

My buildings and units are in 3d

hexed pecan
#

Logically it should work, both have 8 bits per channel and 4 channels

hexed pecan
deft spear
deft spear
rigid island
# hexed pecan <@968604165150507078> See my edit

its not black but now im having the same color than when I did ReadPixelData with original format on new texture```cs

       //pixelData32 = newTex.GetPixelData<Color32>(0);

       // for (int i = 0; i < pixelData32.Length; i++)
       // {
       //     if (!colorsNewTexture.Contains(pixelData32[i]))
       //     {
       //         colorsNewTexture.Add(pixelData32[i]);
       //     }
       // }```
delicate olive
# deft spear

To find the UI blocking the view, you could do something like this:

    public GameObject GetGameObjectOverPointer()
    {
        var lastPointer = GetLastPointerEventData(-1);

        if (lastPointer != null)
        {
            return lastPointer.pointerCurrentRaycast.gameObject;
        }

        return null;
    }

    // Debug the logic using log statements to for example print out the name of the gameobject if it isn't null

Slight correction; to use the protected GetLastPointerEventData() function, the class needs to derive from StandaloneInputModule

deft spear
#

How is this not managed by Unity by default

delicate olive
lean sail
#

you can see what UI is blocking with the event system panel already

delicate olive
lean sail
#

pointerEnter

deft spear
#

if (Input.GetMouseButtonDown(0)) {
if (EventSystem.current.IsPointerOverGameObject()) Debug.Log("Clicked on GUI");

This fires on EVERYWHERE I click

delicate olive
delicate olive
#

Always looked at the "First Selected" field on the EventSystem component and it was always null so

deft spear
#

What panel?

lean sail
delicate olive
lean sail
#

also you have to be in play mode

deft spear
#

Looks empty to me

lean sail
#

🤔 not really sure why you dont see anything tbh

delicate olive
#

It should also show the object in the inspector when it is in Debug mode

deft spear
delicate olive
#

Where's your standalone input module? I have it here

deft spear
#

I dont have one

delicate olive
#

Oh you must be using the new input system then

deft spear
#

Its converted

delicate olive
#

So it must be detecting somethign

deft spear
#

Ya it detects my gui buttons

delicate olive
#

But does "selected" mean "hovering" or does it mean you've clicked the button?

deft spear
#

This option also clears the selection when clicking on terrain

#

It always says Selected:

delicate olive
#

What if you just try disabling the canvas and see if you can click the 3D objects

deft spear
#

I can not

delicate olive
#

Then if you can, work down the canvas hierarchy object by object until you find the culprit

#

So it's not the canvas

#

Did it register input b4?

deft spear
#

Ya, if I remove the eventsystem check I can run my raycast

#
void Update()
{
    
    if (Input.GetMouseButtonDown(0)) {
        // if (EventSystem.current.IsPointerOverGameObject()) Debug.Log("Clicked on GUI");
        Destroy(_placedMouseCursor);
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask)) { 
            Debug.DrawLine(transform.position, hit.point, Color.red);
            _placedMouseCursor = Instantiate(mouseCursor, hit.point, Quaternion.identity);
            MoveAgent(agent);
        }

    }
}
delicate olive
#

Is the EventSystem a part of the new input system? Because you're using the new system and if it's not then you shouldn't even be doing the check with the old system

#

I haven't used the new system so I dunno

deft spear
#

No idea

#

Maybe its not

delicate olive
#

ChatGPT says it is part of the old system

#

and that there is no equivalent in the new system

deft spear
#

Or well, the input system module is converted under Event System

delicate olive
deft spear
#

Im on 2023

#

I have not configured anything in the input system gui tho

delicate olive
#

I guess we're at a dead end (at least on my part) because I have never used the new input system; maybe people in #🖱️┃input-system are more knowledgeable with this

real ivy
#

hi!

#

i want to have a list of scritps to be add on the object when it is instantiated, how can i do that?

delicate olive
real ivy
#

it makes sense, but what i don't know is the type i should declare the list

delicate olive
#

MonoBehaviour..?

knotty sun
#

List<System.Type>

real ivy
#

let me try

lean sail
real ivy
delicate olive
knotty sun
#

no, but it's your list so you control what goes in it

delicate olive
#

Yeah but he wanted to use the list in a function that adds components to an object

knotty sun
#

yeah, so?

delicate olive
#

Using System.Type in the list would not allow for that functionality..

knotty sun
#

of course it would

lean sail
#

you can cast

delicate olive
#

Yeah, but why cast when you can just directly declare it as a list of MonoBehaviours/Components?

knotty sun
#

no need to cast Addcomponent has a Type override

delicate olive
knotty sun
#

no

lean sail
#

oh it does have an override

real ivy
#

i can't add the script to the list on the inspector

#

(using the system.type)

knotty sun
#

no, System.Type is not serializable, but then you never mentioned that

delicate olive
delicate olive
#

Also, do you really need to use AddComponent? You could consider methods like prefabs

real ivy
delicate olive
real ivy
#

how do you sugest me to do?

#

the addcomponent was my first idea

lean sail
#

this does sound weird to be adding a list of components, but if you do continue like this then you probably do want to use Component instead, or else you wont be able to add rigidbody or similar stuff

delicate olive
#

Then I would use a prefab 100%

real ivy
#

i have a bullet and want to add modifiers to it

#

this is a prototype btw so i can test all the ideas

knotty sun
delicate olive
# real ivy i have a bullet and want to add modifiers to it

Idk, this may be a great way for that as it uses composition (which is good for modularity), but another approach would be to just have one class like BulletModifiers attached to the bullet and access that when you want to add effects to it

real ivy
#

give me a minute

lean sail
# real ivy i have a bullet and want to add modifiers to it

If you need this to be 100% modular, like the user can fully customize what a bullet can do then I'd just store the modifiers in one class and maybe have the functionality on a scriptable object.
If it's a difference of selecting between 5 possible bullets, just make prefabs

hexed pecan
delicate olive
lean sail
#

It's definitely not the best way, just a quick way to test

delicate olive
#

And when refactoring for example, file name changes are pretty common so

real ivy
#

yeah it gives me compile error for being obsolete

#

but i think it is possible to convert from string to type

knotty sun
#

yes, using Reflection

lean sail
#

Is that really a compile error? I thought itd just be a warning

hexed pecan
#

It does show up as a compile error in VSCode though

real ivy
lean sail
real ivy
#

now i just need to do it for the list

#

do this have any significant performance impact?

hexed pecan
#

You could also make a dictionary that maps an enum value to a type

real ivy
#

that's cool

#

i liked the string aproach

real ivy
lean sail
real ivy
#

i think i can do something

#

i can just have the list of types ifself

#

but now it works, thank you all

hollow gazelle
#

Is it possible to use the netcdf library in C# to play simulations in Unity or does anyone know how to do this in Unity =) ? Hey guys I currently have a C++ project where I simulate tsunami waves 2 dimensionally. To save the values of the waves I use the netcdf,zlib , hdf5 library. The calculated values are then saved in this .nc file and I can then display the values in a program "Paraview", i.e. play the time steps and then see a simulation. My goal now is to bring everything into Unity and play my simulations directly in Unity.

mighty wave
#

hello, why camera 02 is not turning on using UnityEngine;

public class LevelLoader : MonoBehaviour
{
public float targetY = 5.14f; // Docelowa wysokość Y, po której obiekt przechodzi na kolejny poziom.
public Transform Player; // Referencja do obiektu gracza (Square).
public Camera camera0;
public Camera camera1;
public Camera camera01;
public Camera camera02; // Nowa kamera

private bool isTransitioning = false;

private void Update()
{
    float playerY = Player.position.y;

    if (!isTransitioning && playerY >= -5.39f && playerY <= targetY)
    {
        SwitchCamera(camera0, camera1, camera01, null); // Zmień na kamerę 0
        isTransitioning = true; // Ustaw flagę przejścia na true
    }
    else if (isTransitioning && playerY > targetY)
    {
        SwitchCamera(camera1, camera0, null, null); // Zmień na kamerę 1
        isTransitioning = false; // Resetuj flagę przejścia, gdy gracz wraca poniżej 5.14
    }
    else if (isTransitioning && playerY < -5.39f && playerY >= -10.78f)
    {
        SwitchCamera(null, camera0, camera01, null); // Zmień na kamerę 01
        isTransitioning = false; // Resetuj flagę przejścia
    }
    else if (isTransitioning && playerY < -10.78f)
    {
        SwitchCamera(null, camera0, null, camera02); // Zmień na kamerę 02
        isTransitioning = false; // Resetuj flagę przejścia
    }
}

private void SwitchCamera(Camera enabledCamera, Camera disabledCamera1, Camera disabledCamera2, Camera disabledCamera3)
{
    if (disabledCamera1 != null)
        disabledCamera1.enabled = false;

    if (disabledCamera2 != null)
        disabledCamera2.enabled = false;

    if (disabledCamera3 != null)
        disabledCamera3.enabled = false;

    if (enabledCamera != null)
        enabledCamera.enabled = true;
}

}

somber nacelle
tawny elkBOT
mighty wave
#

and when it comes to cinemachine, now that I look at it, it is probably used to track the player, the idea of the view in my game is a bit different

somber nacelle
#

you don't have to track the player with cinemachine. it's meant to control your camera

#

but you still haven't answered what debugging steps you've taken to ensure that your conditions are being met

mighty wave
#

what do you mean by debugging steps, I'm seriously a beginner?

somber nacelle
long saffron
#

My object isnt moving

hexed pecan
long saffron
#

testing it

hexed pecan
#

That will practically only move it once, 2 units right of the starting position

long saffron
#

but it stays in place, not sure if its jittering

hexed pecan
#

Then gameMode is probably not 1

#

Or you have something else changing its transform, like an animator with root motion

long saffron
#

its just a sphere and i put a debug statement there and its being called

#

I instantiated it but I call starting position after that

#

It says that it moved once and then stalls there

hexed pecan
long saffron
#

im testing it so yes for now

hexed pecan
#

You are setting the pos to startingPosition + offset, neither of those values are changing so it will stay in place

#

You can do transform.position + offset if you want it to constantly move

long saffron
#

but its in the update

hexed pecan
#

That will move it 2 units every frame though, so you want to multiply it with deltaTime to make it correctly scale to framerate

hexed pecan
long saffron
#

i put += and then it worked

#

thanks

upper aspen
#

I am having an error when trying to instantiate a gameobject. Anyone have an idea how to squash this one? The script is accessing a public gameobject which I have asigned in the editor. When I play the cene the object can be seen assigned in the editor. Why is my script saying it is null?

main coral
#

Why is my wheel collider so big ?

somber nacelle
somber nacelle
main coral
#

Ok which is the correct channel for this ?

somber nacelle
upper aspen
hard viper
#

if I have an object of type Type, is there a way to check if that type implements a given interface without instantiating it?

quartz folio
hard viper
#

ty vertx. is that performant, out of curiosity?

#

I just need to ask because sometimes, I get these functions that are a perfect fit, but surprise: giant lag

#

huh, VS can't find IsAssignableTo

quartz folio
#

In Unity's version it used to be IsAssignableFrom, just reverse the arguments

#

much more confusing way of doing it, so they flipped it thank god

hard viper
#

I see that. but I see IsAssignableTo in the source. I just can't access it for some reason. it says no such method found in System.Type

quartz folio
#

Yes, it doesn't exist in this version of .NET

hard viper
#

god damnit unity lol

#

ty vertx

#

maybe I'll just make it an extension method.

hard viper
gaunt wren
#

Looking into Additive Scenes currently, It doesn't look like you can simply load an additive scene in and place it at a specific position natively from what I can tell.. I have some ideas of how to position the additive scenes in the active scene but it's a hacky solution.

How do others work with them generally?

spring creek
gaunt wren
#

right, that makes sense. So you have build these scenes with specific coordinates in mind to ensure scenes don't overlap each other.

spring creek
gaunt wren
#

in my case, it is for level chunks. Probably see if Prefabs are just as viable

hoary mason
#

my collider isn't disabling when I do this

#
    {
        ChangeAction(ActionState.hit);
        Rigidbody.velocity = Vector2.zero;
        Hurtbox.enabled=false;
        ChangeEffect(EffectState.hit);
        animator.SetInteger("Effect",(int)effect);
        //Parent.Animator.SetInteger("State", (int)ActionState.hit);
        Controllable = false;
        gameObject.layer = 9;
        Debug.Log("Hurtbox: " + Hurtbox.enabled);

    }```
#

or well

#

the debug returns false, but it's still enabled on the inspector, and when I check it here it returns true

void endInvincibility()
 {
     Debug.Log("Hurtbox: " + Hurtbox.enabled);
     Hurtbox.enabled = true;
     ChangeEffect(EffectState.normal);
     animator.SetInteger("Effect", (int)effect);
     gameObject.layer = 0;
     //Parent.Animator.SetInteger("State", (int)ActionState.idle);
 }```
#

no other part of the game even references the hurtbox

leaden ice
hoary mason
#

i'm not, clicked on "hurtbox" on the inspector and it's the right one

leaden ice
#

then it's getting re-enabled elsewhere

hoary mason
#

yeah but no idea how

#

literally nothing else references it

hoary mason
#

the current animation, for example

hoary mason
#

ooh

#

thanks

cyan musk
#

I have a general question not necessarily help with code but I’m trying to generate an enemy base in 2d that consist of walls turrets buildings ect I’d obviously assume I have to instantiate some prefabs and what not but what would the logic be like behind that for randomly generating a base

#

how would I get the walls to spawn in an orderly fashion for example

thin hollow
#

I've extracted a function in one of my scripts as an extension abstract generic method, because I needed to do same thing in another script, and it for some reason doesn't work like that - even in the initial object I plucked it from. What might be the problem?

       public static T FindInParents<T>(this Transform p, int hierarchyDepth=5) where T : class
        {
            Transform currentParent = p;
            T obj = null;
            for (int i = 0; i < hierarchyDepth; i++)
            {
                if (obj == null && currentParent != null)
                    obj = currentParent.GetComponent<T>();

                if (obj == null)
                    currentParent = currentParent.parent;
                else break;
            }

            if (obj == null)
            {
                DevLog.LogError("No parent has "+typeof(T).FullName+" component");
            }

            return obj;
        }
lean sail
thin hollow
lean sail
thin hollow
#

Isn't using the Log function a debug?

lean sail
thin hollow
#

I use Rider, and while it activates the debug mode in unity, it is completely empty:

lean sail
#

not really sure how rider debugger works tbh

thin hollow
#

Oh, I needed to add a red dot to the line of the code...

spring creek
thin hollow
#

Ok, I can see what's happening now, it seems like the problem is that the for Loop runs only for two iterations no matter what. Even if I just hardcode 5 iterations, for (int i = 0; i < 5; i++), it checks the current transform, the parent of that transform, and then seemingly stops - next breakpoint happens for script on another object.

spring creek
#

@thin hollow So, I am only just coming in to this, but I see you have two conditions that check if the object is null, and else it breaks.
Could the object simply NOT be null? The first if statement sets it to something currentParent is not null

for (int i = 0; i < hierarchyDepth; i++)
{
    if (obj == null && currentParent != null)
      obj = currentParent.GetComponent<T>();

    if (obj == null)
        currentParent = currentParent.parent;
    else break;
}
#

Were one of those if statements supposed to say if obj != null?

#

I would use the debugger to on the obj = currentParent line

thin hollow
rigid sleet
#

am I missing something? Whats the i variable here for?


for (int i = 0; i < hierarchyDepth; i++)
            {
                if (obj == null && currentParent != null)
                    obj = currentParent.GetComponent<T>();

                if (obj == null)
                    currentParent = currentParent.parent;
                else break;
            }

#

I dont see you using it anywhere

#

you arent iterating over the transform hierarchy anywhere

thin hollow
rigid sleet
#

okay so what are you exactly iterating over here

spring creek
rigid sleet
#

just i times over the direct parent?

#

just trying to understand the goal here

#

okay I got it, 1 sec

spring creek
#

I read it as a deep hierarchy. Many levels of children, grandchildren, etc.
It iteratively checks up the chain for a given generic component

rigid sleet
#

yep yep got it, I was confused due to how this was written, a lot of the checks seem a bit redundant

thin hollow
# rigid sleet just i times over the direct parent?

The way it supposed to iterate is "try to get component from the current transform, if it returns null, set current transform to the current transform's parent, repeat until component is found or loop ran out"

rigid sleet
#

hmm yeah it seems very sane, let me plop this on an empty project and see if I can get it working

#

you dont need to check if the object you are passing is null, if its null then it means you got into a null parent aka top hierarchy object so you can do something like this instead


            Transform currentParent = p;
            T obj = null;
            i = 0;
            for (int i = 0; i < hierarchyDepth; i++)
                obj = currentParent.GetComponent<T>();
                if (obj == null){
                    currentParent = currentParent.parent;
                    if (currentParent == null) break; //If the parent is null then we stop traversing the hierarchy
                }
            }

#

but yeah doesnt fundamentally change the code, gimme a minute to get unity running

thin hollow
#

Huh, weirder, I commented out else break;, and now it completes the loop. Upside - it works, downside - I think this way it doesn't stop and runs out the remaining loops even after object was found. A little, but waste of resources. Not ideal, but I don't think I will have hierarchies deeper than 5 or 6, so...
Still, why it does this?

rigid sleet
#

oh, okay i see an issue

#

yeah your code will always return itself

thin hollow
#

what do you mean?

rigid sleet
#

I just called your code and it worked on my end

#

but it returned itself

#

if for some reason the class you are running this from also has the component you are looking for it will return itself

thin hollow
#

I call it in this way:
ICollisionTriggerReceiver parentInterface = transform.FindInParents<ICollisionTriggerReceiver>(5);

#

And, no, the class I run this from doesn't have ICollisionTriggerReceiver interface inheritance, it's only on the parent.

rigid sleet
#

hmm yup your code doesnt find the object on my end

thin hollow
#

I thought maybe the issue is due to ambiguity of ifs with those missing parenthises, but with both

            for (int i = 0; i < 5; i++)
            {
                if (obj == null)
                {
                    obj = currentParent?.GetComponent<T>();

                    if (obj == null)
                        currentParent = currentParent.parent;
                    else break;
                }
            }

and

            for (int i = 0; i < 5; i++)
            {
                if (obj == null)
                {
                    obj = currentParent?.GetComponent<T>();
                }

                if (obj == null)
                {
                    currentParent = currentParent.parent;
                }
               else break;
            }

it breaks again. =\

rigid sleet
#

there is something really weird going on

#

for (int i = 0; i < hierarchyDepth; i++)
        {
            Debug.Log($"Checking for Component on: {currentParent.name}");
            obj = currentParent.GetComponent<T>();
            Debug.Log($"Obj is null?: {obj == null}");
            if (obj == null)
            {
                currentParent = currentParent.parent;
                if (currentParent == null) break;
            }
        }

#

ohhhh nvm

#

this works for me


public static T FindInParents<T>(this Transform p, int hierarchyDepth = 5) where T : class
    {
        Debug.Log($"Running");
        Transform currentParent = p;
        T obj = null;
        for (int i = 0; i < hierarchyDepth; i++)
        {
            Debug.Log($"Checking for Component on: {currentParent.name}");
            obj = currentParent.GetComponent<T>();
            Debug.Log($"Obj is null?: {obj == null}");
            if (obj == null)
            {
                currentParent = currentParent.parent;
                if (currentParent == null) break;
            }
        }

        if (obj == null)
        {
            Debug.LogError("No parent has " + typeof(T).FullName + " component");
        }
        return obj;
    }

thin hollow
#

Hmm, you think its because of the daddy parent issues?
I think your code will not find anything if the desired component is from the first child of the object, instead of the object itself. I think this code trying to find the first encountered component instead of trying to grab one from the topmost parent has more potential usage in the future .

rigid sleet
#

yeah this grab the first one

#

from bottom to top

#

from the parents

thin hollow
#

Hm, yeah, your version seems to work even with the "break" that, well, breaked it before. Weird >_<

            for (int i = 0; i < 5; i++)
            {
                obj = currentParent?.GetComponent<T>();

                if (obj == null)
                {
                    currentParent = currentParent.parent;
                    if (currentParent == null) break;
                }
                else break;
            }
rigid sleet
#

just to make sure, you want a version of this script that returns the last ocurrence of the class right?

thin hollow
#

no, the first it gets. For the last I think I can always crawl to the topmost parent with iteration and call "findComponentInChildren()" from there.

rigid sleet
#

gotcha gotcha

#

then yeah that should work for you then, let me do a double check with another class just to be sure

#

I think I am finding a unity bug here

#

If I check for a rigid body class

#

it breaks

#

for some reason the returned obj is not null

#

but its null when checked

#

bizarre

#

it only happens when looking for a rigidbody haha

#

Yeah i think this is some bizarre unity issue, this doesnt work for any UnityEngine class

#

oh

#

obj == null

#

yeah this is wrong

#

you cannot do that for Generic types

somber pulsar
#

Does anyone wanna be a playtester for a unity project?

rigid sleet
#

@thin hollow okay this is the fixed version

#

public static T FindInParents<T>(this Transform p, int hierarchyDepth = 5) where T : class
    {
        Transform currentParent = p;
        T obj = null;
        for (int i = 0; i < hierarchyDepth; i++)
        {
            obj = currentParent.GetComponent<T>();
            if (obj == null || obj.Equals(null))
            {
                currentParent = currentParent.parent;
                if (currentParent == null) break;
            }
        }

        if (obj == null || obj.Equals(null))
        {
            Debug.LogError("No parent has " + typeof(T).FullName + " component");
        }
        return obj;
    }

#

it was indeed some unity fuckery

#

You cannot directly check for obj == null

#

because it is not a Unity type

#

this checks both cases, as a system object and as a unity object

lean sail
thin hollow
plucky anchor
#

Hello, I have run into the error :
ArgumentException: GetComponent requires that the requested component 'Image' derives from MonoBehaviour or Component or is an interface.
This confuses me as I believe that an Image is a component, contrary to what the error states.

thin hollow
lean sail
plucky anchor
lean sail
rigid sleet
#

It’s the generic

#

You can absolutely use == null in Unity stuff

#

But the code using a Generic null check was the issue, that’s just not a thing in general

lean sail
rigid sleet
#

Oh you meant the operators lol

#

But yeah the issue was exactly what was described here

#

Obj = null was being reported as false even when the object was indeed null lol

lean sail
plucky anchor
thin hollow
spring creek
lean sail
lean sail
plucky anchor
rigid sleet
#

The whole idea of finding a component in a parent to me is very bizarre too

#

If you have a sane architecture you almost never wanna do that

plucky anchor
#

so because I couldn't reference the thing I wanted dirrectly, I tried to workaround it and failed

rigid sleet
#

Talking about the other code not yours hehe

thin hollow
# rigid sleet The whole idea of finding a component in a parent to me is very bizarre too

My first case for which I initially thought it up: I needed to have several trigger colliders on one prefab and to also discern between the triggering of different colliders (It's an object that does different things based on from which direction player have come from, basically, and directions aren't aligned with the coordinate grid). So I implemented interface for the prefab object that receives typical OnTriggerEnter function analogs, but with additional references to what child they were triggered from. I didn't want to hardcode in parent-child structure (what if I'll want to reuse this in another prefab with a different amount of children?), so I made this code so that child objects would seek the interface in parent on their own.

lean sail
lean sail
plucky anchor
lean sail
#

yea but not really sure why your ide doesnt show it tbh

plucky anchor
#

It might be a Visual Studio Code Editor issue, I will look into that. Thank you for the help either way 👍

rigid sleet
#

If you want a pro tip about interfaces in Unity @thin hollow

#

If you are gonna have any kind of serialization and prefabs you should try not using them lol

#

You are gonna have a lot of headaches

#

Nowadays I use virtual methods and avoid the issues down the road

thin hollow
#

I have my entire level design philosophy built around basic "triggerInterface" with which different classes can activate any other object you reference to them in the Inspector....

rigid sleet
#

Nested serialization (prefabs and prefabs of prefabs) really mess the references up

#

Food for thought it might not be something that happens to you hehe

thin hollow
#

All of my references are set once in the editor and won't change during gameplay, so they aren't being serialized.
Though, for NPCs, that's not true, so that's an important warning to look forward to, thanks again!

#

Would probably need to serialize GUIDs instead of direct references, and on loading search for objects with that GUID to reassign the references...

rigid sleet
#

Btw setting stuff in the editor is serialization

#

In fact that’s a really easy way to break interface serialization, nested prefabs completely break interface references and you have to assign them at the top level prefab

thin hollow
#

Wait, but if it's nested serialization that messes references up, how not using interfaces will help to avoid this?

rigid sleet
#

That doesn’t happen to normal references

#

How are you referencing interfaces in the editor btw?

thin hollow
rigid sleet
#

You can’t really do that by default yeah which is a big downside

#

Using something like Odin Inspector you can reference them directly and that’s when things break

thin hollow
#

Ah, well, that's easy then, I can't use Odin cuz I can't pay for it. XD

spark flower
#

how do you shuffle a list

lyric moon
#

hey im working on a game, and when built, it crashes. i was wondering if yall know what can commonly cause a unity game to crash (besides hardware issues). programming-issues wise i mean. null references dont really cause crashes they just stop running code for that script so what actually warrants a crash crash, like full application close

royal wedge
# spark flower how do you shuffle a list
public static List<T> Shuffle<T>(List<T> _list)
    {
        for (int i = 0; i < _list.Count; i++)
        {
            T temp = _list[i];
            int randomIndex = Random.Range(i, _list.Count);
            _list[i] = _list[randomIndex];
            _list[randomIndex] = temp;
        }

        return _list;
    }
fervent furnace
#

NRE can crash your game since there is no any guard stopping you making write/read violation

delicate olive
#

Does Player.log log crash messages?

lyric moon
#

ios game so i cant do that sadly - cant build for pc either

fringe ridge
#

why on other projects it worked with just SceneManager.LoadScene("Game 1");, but now i need to do SceneManager.LoadScene("Project Data/Game/Scenes/Game 1"); Also in this case if i were to check for scene name, should i check for the full path or just Game 1?

craggy veldt
craggy veldt
fringe ridge
#

ah, so the index would be the one in build settings right? 0,1,2...

craggy veldt
#

yes

fringe ridge
#

Thanks

#

also, maybe someone already tested this so i dont have to. When player tries to load the game for the first time with Google play games services, does it return an empty by array with success, or is there an error?

stoic ledge
#

For people new to async/await approach,
Let's say we have a method:

public async Task RenameUser(string userId, string newName) {
throw new NotRegisteredException();
}

What will the return type look like and how can the method caller handle this exception?

craggy veldt
#

you'd want Task<T> to return something

async Task<bool> AsyncFoo()
{
  try
  {
    await Task.Delay(TimeSpan.FromSeconds(5), myTokenSource.Token);
  }
  catch(OperationCancelledException)
  {
      //Do your thing when token was cancelled
  }
  return true;
}
drifting crest
#

In the Unity build how can I make it detect display 1 and display 2 ?

craggy veldt
stoic ledge
stoic ledge
craggy veldt
#

here from the docs

stoic ledge
#

yep, exactly

#

By return type I mean will Exception be thrown upwards the stack or will it be "Task" with IsFaulted == true.
But I got it clear already, thank you.

craggy veldt
#

you can always check them via Task.Result

#

if you're wrapping your logic around the tokensource cancellation then just check the token instead

#

also, it is a good practice to throw in async/await when cancelling sources

cosmic rain
#

Unless you await it I guess🤔

#

Always confusing business with the async throws

merry stream
#

so I'm watching a tutorial on an inventory system using script able objects. is it always bad to change script able objects at runtime or is it fine to use in an inventory? would making an onapplicaitonQuit function to clear the inventory work?

leaden ice
merry stream
#

I understand that changes to them persist but could you elaborate? i'm just trying to learn best practices for unity dev and overall coding architecture. I feel that many tutorials overlook this to simplify everything like making everything public.

leaden ice
#

Under all other circumstances, changes will not persist

merry stream
#

so why have I heard that they should only be used to store data that won't be changed? Is it acceptable to use it for an inventory?

leaden ice
#

It's acceptable to use for an inventory if you understand the nuances and the behavior that will come from how you are using it

#

Obviously the difference of serialized vs non serialized data also comes into play

merry stream
#

how so?

leaden ice
#

How not so?

#

Serialization is central to that whole persistence issue

#

Since only serialized data can possibly be persisted by the engine

#

A lot of people use SOs as a convenient referencable object in the editor.

You could do that and have a non serialized inventory on it and there's no risk of persistent changes

#

So it really just depends on exactly the details of your usage

latent latch
#

SOs can be used many ways, but the only reason I don't write to them is because plain c# objects satisfy my requirements already.

#

it's actually fine if you want to dupe data to write to

merry stream
#

so you would instead make a inventory singleton?

merry stream
leaden ice
latent latch
#

I usually just make them as a plain c# object, but if you've a one player game where you've a single inventory I could see some use.

leaden ice
#

ScriptableObjects are just one type of asset

merry stream
#

so what does adding serializable do?

proud fossil
#

Does anyone know how the "tick" system works in Unity?

leaden ice
main shuttle
merry stream
proud fossil
merry stream
#

does it just allow it to be shown in editor

proud fossil
#

arent there physics ticks

#

logic ticks

leaden ice
#

Showing in the inspector is just ONE of the things I mentioned

main shuttle
# proud fossil logic ticks

Sure, but there are a bunch of ticks you could think of, i.e. network ticks, fixedupdate ticks and the ones you already said.
So I'm not sure which one you want to know about.

proud fossil
#

oh yeah, fixedupdate and update ones

latent latch
#

you can set the tick in project settings

proud fossil
#

thx guys

leaden ice
#

With nice diagrams and everything

proud fossil
#

but could you explain me what a is a tick?

#

like its definition

leaden ice
#

Think of a clock ticking

#

That's it

#

Just a thing that happens repeatedly at a constant interval

proud fossil
#

ok thanks

#

its Update called every frame or as much as possibel depending on your CPU?

leaden ice
#

Both. It's called every frame. Frames happen as much as possible unless you use vSync or other artificial limits

proud fossil
#

oh, ok, dumb question I guess

fair dew
#

Hello, I'm following Jerry Tessendorf paper on simulating water. I'm a bit confused with complex vectors ("I hope that's how they called"). Anyways, I have formula for normal maps (attached picture). The issue is that I don't understand how to express i*k (the first part) , where k is vector with both real parts. Any, help would be helpful!!!!

leaden ice
#

You'd have to create a data type to represent complex numbers

#

You could make a ComplexVector3 type to represent complex vectors

#

It may consist of 3 complex numbers

fair dew
#

I know that when u express real number in complex plain you get vector2, first part real and the second imaginary. So, now I would need vector 3 where 2 first numbers are real and last one is imaginary? Or do Ineed vector4?

#

K is vector2

leaden ice
#

Vector2 is a cop out

#

Make an actual ComplexNumber type

#

You could use Vector2 inside but you need to define the interactions properly because you can't just do operations on Vector2 like normal.

fair dew
#

Cop out?

leaden ice
#

It's lazy

#

It just happens to be a struct that holds two numbers

#

So it CAN represent a complex number

#

But it's not going to solve any problems for you

fervent furnace
#

you have to define the multiplication operator for imaginary number
you can use three vector2 btw, but you cant overload the operators of vector2

leaden ice
#

I think it would be much clearer and cleaner to make a custom Complex struct

#

And define all your operations/functions/operators etc as necessary

fair dew
#

I'm a bit more confused with the mathimatical part, the programming part is clear. So if I have real number: 3, I can express it as 3 + 0i. How would it work with complex vector?

fervent furnace
#

and you need to make you own Pow of complex number (e^(real part))*eular formula iirc

proud fossil
#

what executes first FixedUpdate or Update

proud fossil
#

thx

mental rover
fair dew
#

Oh you ment for vector

mental rover
#

to stop things getting very messy I'd go with PraetorBlue's suggestion of implementing that complex type yourself and ensuring all elementary operations are what you want

fair dew
#

But how we go from vector2 with both real parts to 2x vector3 in complex plain?

mental rover
#

a complex number is just a number

#

you can think of it as a vector of two parts, but conceptually it's just a number

fair dew
#

So, if we have 2 real numbers how we end up with 3 real numbers?

proud fossil
#

and i still dont understand the tick thing

fair dew
fervent furnace
#

you can have a custom struct

public struct A{
  public static operator XXXXX.....
}
```then you can have a Vector of A
```cs
public struct Vector2A{
  public A x,y;
}
mental rover
fervent furnace
#

(just like what unity names its Vector2Int...)

#

they replace the float to int

fair dew
#

Anyways, I will try calculating this part twice first I will calculate for k.xi... and then for k.yi... As this will give me tangent and bitangent. @mental rover

mental rover
#

if it works it works right

fair dew
turbid surge
#

I'm making a simple game where you bartend and talk to people. I was wondering how I should manage sequence of events like when you finish making a drink or once you talked to NPC 1 then NPC2 comes over and starts talking to NPC 1.

#

State machine? Like stay in that state until conditions are met then move on to the next state and repeat?

#

Or maybe an event system, like when something is done, tell some manager class and set something to true. Or a mix of both?

#

What would anyone recommend?

mental rover
#

trimmed of a lot of boilerplate to the point it's just an iterator, since likely it just needs to be in the form A -> B -> C -> D

turbid surge
#

Story narrative yep, and okay yes that feels right. Coroutine state machine that waits until conditions are met to move on. Then when it moves on the next state it runs all the stuff it needs (timeline cutscenes, other stuff,etc.) then awaits to move on til the next conditions are met (served X drinks, talked to NPC about X).

narrow nebula
#

In my game players and enemies have a script to handle status effects. Status effects have indicators under the character to show the amount and all status effects have a sprite. What would be the best way to store the list of sprites? ChatGPT suggested a gameobject that isnt destroyed on load to store a list of the sprites.

turbid surge
#

Sorry thinking out loud - thank you

rigid island
#

GPT as useful as a sack of wet mice

narrow nebula
mental rover
rigid island
#

any enemy or object that reference that SO has accesss to the sprites

#

no DDOL needed

cerulean mist
#
        // Calculate acceleration force
        Vector3 velocityChange = wishVel - rb.velocity;
        Vector3 accel = velocityChange * accelMultiplier;
        accel = Vector3.ClampMagnitude(accel, maxGroundAccel);

        // Accelerate towards desired velocity
        rb.AddForce(accel, ForceMode.Acceleration);

Just a quick question -- do I need to account for Time.fixedDeltaTime for adding acceleration force?

leaden ice
cerulean mist
#

Alright cool just making sure 👍 thanks

fair dew
#

@mental rover Although my communication was poor. It helped me to talk to somebody to understand few things that were missing.
Here is the normals generated.

mental rover
fair dew
ocean river
#

So it seems to be impossible to get Cinemachine to work in unity 5.6, is there a good alternative that works?

rigid island
#

why are you using 5.6 anyway

ocean river
#

There are specific builds for N3DS, which are not supported anymore

#

but its the only way to unity for n3ds

#

anyways,
cinemachine for 5.6 or alternatives?

rigid island
#

Not sure I came into unity when cinemachine was already bought off, so never had to use anything else :\

spring creek
# ocean river anyways, cinemachine for 5.6 or alternatives?

Cinemachine was added in version 2018.1 it looks like (from the manual)

There isn't really an alternative afaik. Maybe you can see if early versions of the standalone cinemachine (pre-unity purchase) works

Might be something really old from the asset store, but I have no idea

ocean river
#

playables

#

it uses playables back in 1.0, i just checked

#

there isnt a way to exactly use playables in five like in 2017 right

knotty sun
#

you can use 2017 for 3DS development

ocean river
#

yeah but

#

its buggy as hell

#

afaik the lastest ever released n3ds was on five.six.six

#

sorry five and six keys are broken

knotty sun
#

2017.2.5

#

but you are right 5.6 was more stable

ocean river
#

some smart guy: it's better to keep on 5.6, 2017 is unstable because they haven't finish it, there is a lot of unknown issue and memory leak + the very last version of unity for 3ds released was on 5.6

#

i have a version from 2020 which is five.six so hes right

rigid island
#

just word of mouth

ocean river
#

hes some guy called ynox working on that sonic unleashed for 3ds, not sure if i should

rigid island
#

I also love the whole "trustmebro" on the internet

ocean river
#

i could try it though

rigid island
#

just try it and test?

knotty sun
#

I can tell you he is wrong, I could screenshot the developers download page showing the SDK version but I won't (NDA)

ocean river
#

aaaaaa i wish i had such an 3ds account

#

they dont allow nda 3ds anymore

#

so much stuff 'd be easier

#

just asking, but,

#

where can i even get this 2017

#

i only have 5.6.5 and 5.6.6

knotty sun
ocean river
#

its not a public version

#

it was distributed on nintendo dev

#

but yeah its not downloadable anymore

knotty sun
#

you wont get that if you're not a reg. developer

ocean river
#

mmmmmhmm

#

sad

#

thanks for the advice though

round violet
#

weird question:
is it possible to write on the same line a <summary> of a var/function/... ?
something like c# /* <summary> is player on the ground </summary>*/ private bool _isGrounded = true;

#

i prefer in one line rather than above

same logic as

[Tooltip("Zipline")] [SerializeField] private LayerMask _ziplineLayerMask;
west hamlet
#

Hello, I´m having somme issues with the tilemap, when the player press a wall, it stick to it

jaunty sleet
#

Does anyone know how to fix the "collab service is depricated" error happening constantly? I just opened a new project and it is so annoying

west hamlet
#

I have been able to fix the fact that pressing a wall would let you climb , but still happens that the player get stuck

west hamlet
knotty sun
rigid island
#

also you need player to be nofriction material then

#

or checkbox infront of you to see if its movable by the amount you pressed

rigid island
jaunty sleet
jaunty sleet
west hamlet
west hamlet
rigid island
swift falcon
#

Hello, I am trying to set the variable "questionItem" in line 47, but for some reason it gives me an error that basically says that questionObj is not set to an Instance of an Object (my guess is that it doesnt have a value). Can anyone help me fix this?
https://paste.ofcode.org/xuDAeTpdZutKm9fH2jgHsH

rigid island
#

its not VC package the problem

rigid island
#

put it on the collider

#

had to be 2D physics material

west hamlet
swift falcon
jaunty sleet
#

but I didn't check collaboration when I made the project

rigid island
jaunty sleet
#

I am using 2021.3.15 but I haven't had this issue before, idk

swift falcon
#

update

#

all

#

editor + project

rigid island
west hamlet
rigid island
swift falcon
rigid island
#

show the full stack error

swift falcon
rigid island
#

also calm down and be patient

swift falcon
swift falcon
rigid island
#

well no reason to spam the channel for you personal problems

west hamlet
west hamlet
#

Now its working fine

rigid island
#

it hasn't been long..

#

give people time to read

#

and process the info..

swift falcon
#

alr alr

rigid island
swift falcon
#

okay

rigid island
#

Debug.Log($"questionObj : {questionObj}");
Debug.Log($"Answerobj : {Answer.Instance}");

knotty sun
#

Answer.Instance.questionItem = questionObj.gameObject;
3 options
Answer is null
Answer.Instance is null
questionObj is null
Debug which one or more it is

rigid island
#

after 46 before 47

swift falcon
#

answerobj is null

rigid island
#

AnswerObject is null then

#

show how you assign it

swift falcon
#

alr

#

one sec

rigid island
#

also never use GameObject.Find

swift falcon
#

why

rigid island
#

cause its painfully slow , awful and error prone

swift falcon
#

it works fine?

rigid island
#

ok use then ifc

#

you seem to know better UnityChanLOL

swift falcon
#

how can I access a child of an obj then

rigid island
#

did you look it up should be first result

swift falcon
#

alr

rigid island
#

though you would want to use Components direclty with GetComponentInChildren

swift falcon
#

but theres still a problem, AnswerObj doesnt exist

rigid island
swift falcon
#

another script

#

Answer.cs

rigid island
#

and is it attached on an object yes?

swift falcon
#

its value is that script

rigid island
#

wat?

swift falcon
#

and yes the script is attached to an obj

rigid island
#

and is the object Enabled ?

swift falcon
swift falcon
rigid island
swift falcon
#

gimme a sec

rigid island
#

cause thats prob why its null

swift falcon
#

funny thing is that this error occurs when theres no answer, so I think yes

swift falcon
#

error

#

i meant

rigid island
#

make sure no other copeis are there

swift falcon
rigid island
swift falcon
#

its disabled at the beginning, i click a button and i create an answer (4 max)

#

but this error appears when i dont create an answer and i switch to the next question

#

so i cant put it on an object and dont disable it at all, would be even more messy

#

but i can check if that variable is not NULL, right?

#

it works

rigid island
swift falcon
#

i fixed it

swift falcon
rigid island
#

why would it be messy putting Answers.cs on a gameobject that doesn't disable ?

swift falcon
#

its answer.cs, trust me it makes more sense because it runs on every answer

rigid island
swift falcon
#

runs on multiple objects

rigid island
#

the whole system is brittle

#

why are you even using Update() instead of events..

swift falcon
#

when you are making a quiz in kahoot dont you want your question to have multiple answers, correct or incorrect that you can choose from

rigid island
#

also GetComponent in Update is mega cringe and inefficient

swift falcon
rigid island
#

but doing things Event based in probably smarter.

#

Learn about events

#

you're already using them for buttons, no reason to do all this in update

swift falcon
rigid island
swift falcon
#

alr, but it works! it doesnt need to be entirely bug-free, its a school project after all

swift falcon
#

basically its just not setting a "parent" question for nonexistent answers

rigid island
swift falcon
fluid lily
#

Anyone familiar with orthogonal projection? I have the fallowing code, and it isn't giving the values I would assume.

        public static Vector2 ProjectOntoLine(this Vector2 v, Vector2 lineDirection) {
            // Normalize the line direction
            Vector2 normalizedLineDirection = lineDirection.normalized;

            // Calculate the scalar projection
            float scalarProjection = Vector2.Dot(v, normalizedLineDirection);

            // Calculate the projection onto the line
            Vector2 projection = scalarProjection * normalizedLineDirection;

            return projection;
        }
fluid lily
#

Ah it was fine, I just wanted the component orthoganal to it(or aka the vector to get from v to the projected value.

main coral
#

Hey when I have a question for the new inputsystem where do i have to ask ?

fluid lily
#

3 channels down

hollow hound
#

How can I prevent default scrolling behaviour of ScrollRect? I don't want mouse scroll input to move content of the scroll rect.

fluid lily
# fluid lily Anyone familiar with orthogonal projection? I have the fallowing code, and it is...

Okay I am confused on how that is working. I have this version which is what all the math places show how to do it, but my normalized value one works the same as far as I can tell and I was supper tired when I made it. Does anyone know if there will be any issues with it vs.

        public static Vector2 ProjectOntoLine(this Vector2 y, Vector2 v) {

            float top = Vector2.Dot(y, v);

            float bottom = Vector2.Dot(v, v);

            return top / bottom * v;
        }
#

Ah normalized ends up doing the same calculations. interesting.

rigid island
#

also not a code question

hollow hound
rigid island
hollow hound
#

Ok, will ask there next time, thanks

jaunty sleet
#

Does anyone know how I can convert a vector3 containing the velocity of an object into a quaternion that will rotate the object to face the direction it is moving in?

strange gust
#

how do i make my character fall fasterwith rigidbodys built in gravity

maiden junco
strange gust
#

tried that

#

doesnt work

maiden junco
#

try to decrease drag

delicate olive
#

Do you want only the character to fall faster, or all rigisbodies?

#

If so you could adjust the global physics factor in Player settings

strange gust
smoky salmon
#

I want to move my player as realistically as possible by using physics, because I want to be able to accumulate momentum by wall jumping, hitting an enemy etc. but I don’t know what the right way to do that is? I tried using AddForce() but that makes the player very slippery, and I still want the game to feel snappy

#

Anyone know how to help?

delicate olive
smoky salmon
delicate olive
#

But doesn't changing the velocity push them anyways?

smoky salmon
delicate olive
smoky salmon
#
currentSpeed * Time. fixedDeltaTime * (transform.right * horizontalMovement + transform.forward * verticalMovement).normalized + new Vector3(0, playerRB.velocity.y, O);```
#

Sorry I’m not sure how to put it in a code block

smoky salmon
delicate olive
#

Use three of these symbols " ` " at the start and three again at the end of the code block

#

And at the start add '''cs

#

(only the cs part, not the ' symbols)

#

!code

tawny elkBOT
delicate olive
#

They need to be like these `, not '. See the difference?

#

`` ''

smoky salmon
#

Ohh I see

#

Lmao I’m using my phone rn and this is quite frustrating

delicate olive
#

Lmaoo you can't find the correct symbol lol

smoky salmon
#

Nope

#

#

Or ‘

delicate olive
#

It should be in the extra symbols tab on youe phone keyboard

smoky salmon
#

` this?

delicate olive
#

Yess that exactly

smoky salmon
#

Alright finally done

delicate olive
smoky salmon
#

Yeah

delicate olive
smoky salmon
#

Oh I’m sorry typo

#

I meant recorrect

delicate olive
#

So when that runs again in the update, the force you added is basically removed completely

#

And not taken into account

smoky salmon
#

Yes exactly

#

And I’m not really sure what to do then

delicate olive
#

If I were to use AddForces on a player controller, I would convert the entire movement logic to just be AddForce

#

That's the only solution I can think of

#

And then clamp the max velocity to whatever you want

smoky salmon
#

Hm okay

#

Sort of specific question

delicate olive
#

But then you'd somehow have to manage not clamping the high wall jump velocity you just added so Idk

smoky salmon
#

Yeah exactly

#

That was the question

#

Oh well I’ll try to find a way

#

Thanks for helping

delicate olive
#

Okay good luck mate

#

One more thing; you could also just disable the movement entirely for some duration after wall hopping for example, or you could have a seperate Vector3 that you add any extra velocities you want and use that in the movement calculations

#

The latter actually seems pretty reasonable to me

#

Then lerp it in Update towards 0 so it dissipates as time goes on

#

@smoky salmon

smoky salmon
#

Ooh I see

#

That’s actually not a bad idea

#

Thanks!

junior salmon
#

Is it possible to change the saturation of a volume in post processing in a script

soft shard
# junior salmon Is it possible to change the saturation of a volume in post processing in a scri...

The volume itself does not have "saturation", it has a "weight" you can adjust which lowers the visibility of all effects on it, but if you just want to modify a specific effect, you would have to get a reference to that effect, for example "Bloom", then you could modify the values of "Bloom" by script, or whichever effect(s) your trying to change, this link may help: https://forum.unity.com/threads/how-to-modify-post-processing-profiles-in-script.758375/#post-5622541

pulsar holly
#

My rotation issue never got fixed.

fallen lotus
#
public class GameParameters
{
    public static float fallingCubesJumpForce = 6f;
    
    async Task InitializeRemoteConfigAsync() {
        fallingCubesJumpForce = RemoteConfigService.Instance.appConfig.GetFloat("fallingCubesJumpForce", fallingCubesJumpForce);
    }
}

can someone tell me if putting fallingCubesJumpForce inside the default parameter fallback when grabbing data will grab the 6f that was declared when the variable is declared?

cosmic rain
#

If you want it to use the value from when the method was called, cache it in a local variable and use that.

fallen lotus
#

ohh so if there isnt a present value, it wont just take whatever that value would haev been beforehand?

cosmic rain
#

Not entirely sure we're on the same page. The value used would be the current value of fallingCubesJumpForce.

fallen lotus
#

ohhh so thats what i want

#

i see

cosmic rain
#

Okay.

fallen lotus
#

so bassically that declaration is correctly using whatever value is declared at the top as the default value?

cosmic rain
#

Syntactically, yeah. Otherwise, not sure... Depends on the intention here.

fallen lotus
fluid lily
#

Uhm.

Log.Info("result.x = {0}", result.x);
Log.Info("result.x = {0}", result.x == float.NaN);
.
.
.
result.x = NaN
result.x = false
lean sail
cosmic rain
#

What type is x?

fluid lily
#

result is a vector2

fluid lily
cosmic rain
#

Ideally, you shouldn't be getting to NaN in the first place.

lean sail
#

Yea not really sure how u get that in the first place tbh

cosmic rain
#

You probably divide by 0 somewhere or something.

fluid lily
#

"
In C#, comparing a floating-point value directly to float.NaN using the equality operator (==) will not work as expected. This is because NaN (Not a Number) is a special value, and comparing it directly with the equality operator is always false. This is due to the nature of floating-point arithmetic and the fact that NaN is not equal to any other value, including itself."

fluid lily
#

I just need to check for it and set it to vector2.Zero

cosmic rain
#

Maybe fix the cause instead?

lean sail
#

Not equal to itself is a funny way of writing something

fluid lily
# cosmic rain Why?

There is always someone like you, who thinks they know better. Not waisting mine or your time. This has solved my problem

cosmic rain
#

We're usually trying to provide an optimal solution here, which is why we might sound picky at times. But suit yourself.

tacit swan
#

how can i make it so rigidbody2d.addforce acts like modifying the velocity, as in, there's no acceleration time or deacceleration time, the moment you press and let go of the arrow keys you reach max speed and slow down immediately

#

mainly trying to use addforce for movement instead of just modifying the velocity directly because later i want to add knockback with addforce

#

but if i modify the velocity directly its going to be a pain later

west hamlet
#

hello, I´m using the Cinemachine2D camera to follow the player, but it keeps doing laggy glitch things with the sprites

#

Thats the both cameras config

karmic brook
#

had a similar issue

west hamlet
karmic brook
#

are the bullets moving with force or are you adjusting the position in update?

karmic brook
#

try setting the rigidbody to interpolate if its not set already

karmic brook
#

and the player movement is inside the update function?

#

the glitch might be because your player movement is in update but your camera updates in fixedupdate

west hamlet
karmic brook
#

not sure what it is then do you maybe have a pixel perfect camera attached?

west hamlet
#

Never used this camera before

karmic brook
#

it looks like this

west hamlet
karmic brook
#

camera settings are annoying it could be anything

chrome trail
#

Is there a way to get information on an animation state that isn't the current or next one?

west hamlet
#

Meh , it fixes the bug when you increase the projectile speed , so might use that

karmic brook
chrome trail
west hamlet
#

wait that isnt

karmic brook
#

with AddForce()

west hamlet
#

I dont use AddForce

karmic brook
#

can you send the bullet scritp

#

shouldnt be the code that moves the bullet inside the bullet script?

quartz folio
#

!code

tawny elkBOT
west hamlet
#

ops , didnt knew that

west hamlet
karmic brook
west hamlet
#

The bullet itself gets the direction when you create it , dunno how to explain it

cosmic rain
#

*if you can't explain it, share the relevant code.

livid grail
#

Probably a dumb question;

I want to make a game that's like a super simple top down 2D shooter (like Vampire Survivor but even simpler).

I want the enemy that kills you to activate certain events (like a cutscene)/be reported in the end (killed by X) and have the enemies have variety in whether they can shoot bullets/not, how fast they can move (or no movement which I assume would just be a variable = 0) and if they can be dodged through.

Would I use scriptable objects to make the various enemies here? I've honestly always had trouble figuring out what's the best way to handle different enemy types that share very similar codes/things.

spring creek
livid grail
#

Honestly even stuff like enemy spawn and accounting for each enemy with simple AI and health is kind of new for me. I'm coming back to unity after like 3~4 years and the last thing I worked on was 1 VS 1 lol.

drifting crest
#

Anyone here tried builiding an Application for UWP from Unity?/

rigid island
drifting crest
dull glade
#

Does someone know how to fix this error, it comes up when removing items from a list and have that game object with the list selected in the inspector.
ObjectDisposedException: SerializedProperty Stock.Array.data[7] has disappeared!
UnityEditor.SerializedProperty.Verify (UnityEditor.SerializedProperty+VerifyFlags verifyFlags) (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <46e1bf9196684231bfdf718689da7102>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <1b5a54bf0ae04c9abb7f7c64341a4384>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <1b5a54bf0ae04c9abb7f7c64341a4384>:0)

mellow sigil
#

Show how you remove the items

tawny elkBOT
dusk haven
#

Hi, i am kind of struggling with positioning my Gameobjects correctly, i am not sure why it will not respect the z position. i instantiate a car gameobject using this script.

public GameObject GetRandomCardFromCardSafe()
   {
       int randomIndex = UnityEngine.Random.Range(0, cardSafeCards.Count());
       // Return a random card from playerDeck
       GameObject randomCard = Instantiate(cardSafeCards[randomIndex], Vector3.zero, Quaternion.identity);
       Debug.Log("Random Card From Card Safe: "+ randomCard.name);
       return randomCard;

   }```
#

and i further modify them for this specific scene cs instantiatedCard = deck.GetRandomCardFromCardSafe(); Debug.Log(instantiatedCard.name); instantiatedCard.SetActive(true); instantiatedCard.transform.SetParent(transform); instantiatedCard.GetComponent<CardMovementHandler>().enabled = false; instantiatedCard.AddComponent<Drag>(); instantiatedCard.GetComponent<RectTransform>().position = new Vector3(0,0,0);
but every object i instantiate this way ends up with z -935.3074 while i would love it to be 0. i have tried everything i could think of and google thought of.

#

these are the components of each card gameobject if it is any help

mellow sigil
#

The Z position shown in the RectTransform component is anchoredPosition, not position

dusk haven
#

i did try using that and it didnt work either, sadly

mellow sigil
#

if you just don't touch any of the position properties in the prefab it gets instantiated in the same position as in the prefab

dusk haven
dusk haven
#

hey! that works! ❤️

#

been struggling with that for days

dusk haven
#

oh now that this stupid scene is working, i had another issue with Layout groups, i am using them to position my objects in a nice grid regardless of how many i want to present, but i have been struggling to get one to update when i add new objects, it will update only once a second object has been added. My google results usually brought me to deprecated docs.
i simply set the parent of the object i am moving to the new sorting group.

delicate olive
drifting crest
#

anyone here have any idea about how to configure multiple display for UWP build

delicate olive
#

Are thos scroll rects? If they are I highly recommend you to add those to your layouts

#

Then when a card is changed/added/removed use the static LayoutRebuilder class that Unity provides

#

Use a method like MarkLayoutForRebuild() with the layout root's rect transform as the parameter

#

ForceLayoutRebuildImmediate() also works but it is more expensive so use it only when you have a lot of nested groups

dusk haven
#

normal recttransforms, we have sized the content to fit the cards

#

i though ForceLayoutRebuildImmediate() was not in the current unity version anymore? 🤔

delicate olive
#

From the video it seems it should scale dynamically

dusk haven
#

wait, the card object or the layout groups?

delicate olive
#

Or did you reply to the other question

dusk haven
delicate olive
#

No, the cards' sizes should stay constant, only the layout groups' "content" objects should be scaling

#

So if you want them to scale, add the contentsizefitter to the Contents and config the appropriate fields

dusk haven
#

the text should remain readable so i am planning on making the group scrollable

delicate olive
#

This would also be more appropriate discussion in #📲┃ui-ux than in here I believe, but whatever

dense swan
#

~~ Hello, does testing steam achievement can be done directly from Unity? I already called Steamworks.SteamUserStats.SetAchievement(apiName) and Steamworks.SteamUserStats.StoreStats() but my account doesn't receive the achievement.~~

~~I also already added Achievement in steam works and publish the change. (they are hidden though) ~~
nvm it works. I need to restart steam first though.

dusk haven
delicate olive
west hamlet
#
using UnityEngine;
using System.Collections;
using UnityEngine.UIElements;

public class Bullet : MonoBehaviour 
{   

    public Vector3 mousePos;
    private Camera mainCam;
    private Rigidbody2D rb;
    public float force;

    void Start()
    {
        mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
        rb = GetComponent<Rigidbody2D>();
        mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition); 
        Vector3 direction = mousePos- transform.position;


        //Rotate
        Vector3 rotation = transform.position-mousePos;
        rb.velocity = new Vector2(direction.x,direction.y).normalized *force;
        float rot = Mathf.Atan2(rotation.y, rotation.x) *Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0,0,rot+90);
    }
      private void OnCollisionEnter2D(Collision2D other)  
    {
        if(other.gameObject.CompareTag ("Player"))
        {

        }
        else        
        {
            Destroy(this.gameObject);
        }
    }
}


cosmic rain
west hamlet
#

but the direction is the same once the player shoot

cosmic rain
west hamlet
cosmic rain
#

Try enabling it then

west hamlet
#

It now works

#

What does Interpolate do ?

cosmic rain
#

Physics updates the position of your rb every fixed update, however the game is rendered in the regular update which can happen more often. That's why objects moved by physics look jittery - they're not moving continuously. Interpolation fills the gaps by moving the rb in between fixed updates as well(interpolates between the current fixed frame and next fixed frame position in the regular update).

versed light
#

public class PlayerMovement : MonoBehaviour
{
    private float horizontal;
    private float speed = 8f;
    private float jumpingPower = 16f;
    private bool isFacingRight = true;

    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask groundLayer;

    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
        }

        if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
        }

        Flip();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }

    private bool IsGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

    private void Flip()
    {
        if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
        {
            isFacingRight = !isFacingRight;
            Vector3 localScale = transform.localScale;
            localScale.x *= -1f;
            transform.localScale = localScale;
        }
    }
}

For some reason my jump is not working, is there anything I need to add or remove? Just to let you know I also added the Rigidbody to the Rb

dusky pelican
#

Is using a lot of properties good or bad habit?

delicate olive
dusky pelican
delicate olive
# dusky pelican Yep, it's manager.

Not related to properties but what stands out to me are the factory machine part class names. I don't think it's common practice to use Prefix_ClassName, people often use namespaces to group classes instead

#

Like "namespace <game name>.Factories" at the top of the class

dusky pelican
#

You're right! I will make it like that. Thanks for advice. So there's nothing wrong about using that much properties right?

delicate olive
#

Is that for holding prefab instances for other scripts to instantiate?

delicate olive
dusky pelican
#

It's kinda like, i have machines in production setup. Each Production Setup contains five machine. So for creating multiple production setups, i use that way.

delicate olive
#

But that's like the only way in my case so

dusky pelican
jolly plank
#

Hi, so I've got a mod for a unity game, and the error:

[Warning: Unity Log] The referenced script (UnityEngine.XR.Interaction.Toolkit.UI.TrackedDeviceGraphicRaycaster) on this Behaviour is missing!

occurs when trying to run the modded game, I don't get any errors building

UnityEngine.XR.Interaction.Toolkit is in the project references too, could I get some pointers in the right direction to look?

delicate olive
#

Because they group them to the production step, which is quite necessary

knotty sun
dusky pelican
jolly plank
primal wind
#

I'm having issues initializing a jagged array

knotty sun
primal wind
#

chunks is declared elsewere but i added it here to not confuse

Chunk[][][] chunks = new Chunk[RealmSizeInChunks][][];
Debug.Log(chunks.Length);
for(int i = 0; i < chunks.Length; i++)
{
    chunks[i] = new Chunk[RealmHeightInChunks][];
    for(int j = 0; j < chunks[i].Length; j++)
    {
        chunks[i][j] = new Chunk[RealmSizeInChunks];
    }
}
knotty sun
#

and Chunks is initialized?

#

cos that looks ok

primal wind
#

I mean, i did the same thing before i added a new array on top of it for 3D

#

And it worked

#

Maybe i broke something without noticing

knotty sun
#

what error are you getting?

primal wind
#

IndexOutOfRangeException anytime i try doing anything with it

knotty sun
#

is Chunk a class or a struct?

primal wind
#

it looks like that when i use a breakpoint

primal wind
#

Tried making it a struct but caused issues i didn't want to have yet

knotty sun
#

you are using both Height and Size, is this correct?

primal wind
#

yes

knotty sun
#

Debug both RealmHeightInChunks and RealmSizeInChunks

primal wind
#

Oh its 0 somehow

versed light
primal wind
#

I even set the values manually and it works

knotty sun
#

public variables?

primal wind
#

private