#archived-code-general

1 messages · Page 70 of 1

buoyant crane
#
public YourScript yourScript;

void OnTriggerEnter(Collider other)
{
     yourScript.Triggered(other);
}

// inside YourScript
public void Triggered(Collider other)
{
     Debug.Log(other.name);
}```
stray stratus
#

My VR game keeps freezing every 4 seconds then unfreezing after a half second and I can't figure out why it is happening. I am using Unity URP and just put in an XR Origin (VR). It seems to have started when I put an XR Origin in the project.

#

By the way this is running on a Meta Quest 2

#

(Actually Oculus Quest 2 but I don't think it matters)

leaden ice
stray stratus
#

I am sending the apk

#

so it doesnt have a profiler

steady moat
stray stratus
#

I just heard of the profiler yesterday, so I don't really know anything about it

stray stratus
#

yeah I know that, but I haven't had time to look over it.

keen warren
#

Little headache here, I want to store a reference to an object (that is serialized), but I want it to be assigned null by default. I found that I can use [SerializeReference] which seems to do the trick, unless the property is not null and the script was reimported. Ideally, I'd like that to reset back to null. In this scenario, I don't need to serialize the property, it's just elsewhere the object does need to be serialized. Any ideas how I can reliably default it to null?

steady moat
keen warren
#

Yes, but when it isn't null, and a reimport occurs, it appears to lose the reference and it becomes an empty object rather than null. I dunno.

leaden ice
steady moat
spring basin
#

Hello, I have a 1 MB text file and would like to load it and parse it to a serialized class. The text file is a JSON string.
https://hatebin.com/wikazkpgye
The following code only prints a very small portion of the file content.
How do I retrieve, save and parse the entire JSON data?

spring basin
#

Even that returns the same portion

leaden ice
#

then that is the entirety of your file contents.

spring basin
#

hmm, maybe some quote got added while saving the json

#

will check

#

thank you

#

@leaden ice I just checked, the file loads fully on my editor but doesnt on my android device

#

using File.ReadAllText

leaden ice
#

how did you check

spring basin
#

i copied pasted the txt file from my android phone to my pc

#

and loaded the file

#

it printed the entire text in my console

#

but when i try to load it in my editor and try to check it in adb logs it doesnt print everything

#

any idea why? @leaden ice

leaden ice
spring basin
#

ahhhhhh

#

hahaha

#

thank you

#

will check if the json loaded properly

#

with the serialized class

#

ty again

gusty osprey
#

alternative to EditorUtility.OpenFilePanel for player builds?

spring basin
#

@leaden ice lmao, thanks alot man, turns out the log wasnt getting printed but the data exists

#

was stuck on it for an hour haha

#

ty again

void basalt
#

Trying to access Unity's update loop inside of a static class. I don't want to use a monobehaviour entry point.

        updateFunc = TestUpdateLoop;``` 

This doesn't give me any callbacks so I'm assuming I'm using it wrong, I just can't find any examples on the internet
steady moat
void basalt
#

I've practically never used delegates before

summer oyster
#

Can someone help me with a bug? The camera is messed up

soft shard
# gusty osprey alternative to EditorUtility.OpenFilePanel for player builds?

AFAIK, there is no built-in way of doing that in a build, youd have to create your own, though its not overly difficult if you largely use the System.IO namespace, specifically System.IO.Directory, System.IO.File, System.IO.FileInfo and System.IO.Path, maybe System.IO.DirectoryInfo if you may want to show extra info about the folder as well, it would be easier to simply display a list and generate a prefab to throw the data of the folder into, a bit harder to show thumbnails or calculate something like file size, as the larger the folder, the longer it will take to do those calculations - alternatively, there are likely several assets on the store that have already done the majority of the work for you

steady moat
#

You could also try to see if you can use directly the application of your target platform like: Process.Start("explorer.exe" , @"C:\Users");

lusty seal
#

A little help please I am trying to use addressable for my project and wanted to know do I have to use unity cdn or it doesn’t matter and I want to know if I have two different projects how would I go about have user b create a project with all its assets and creat addressable and have user a load that cause I have my team working on different part of the game. Just want to know what would be the best way to handle this

steady moat
#

For the sharing of Data/Source between multiple project, it should be done with the help of Package or Version Control. Addressable are not made for such use case same if they could work.

lusty seal
soft shard
lost sand
#

im having trouble implementing a gun that shoots two lazers at one press ive got one to shoot but the other wont. i have two firing points with the same script attached to it. im my head this should work fine.
\

ashen wing
#

I'm pretty new to Unity, and semi-new when it comes to c#.

I have been trying to figure this out for about six hours, and I'm not having any luck, even after typing the problem out and talking to my rubber duck. I scoured the internet as best as I could.

My goal is to set an unused number between 0,9 to an instantiated object (button), use that number to pull the rest of the variables from that object when I click on it, and then populate some text boxes with those values. These objects will be destroyed and leave gaps to be filled occasionally.

But, my problem is that I don't know how to set the number to a prefab from outside of it, let alone make a function check that the index number is free before assigning it. And after that, I don't understand how to use the number to tell me what instantiated object (button) I have clicked on. I feel like it might be a simple problem, or maybe not, but my mind just can't get around the issues at the moment.

If someone can help, I'd appreciate it.

void basalt
#

Like when you click a button in the editor?

ashen wing
#

The values are being set when it's instantiated while the game is running-via code.

#

When I click the button while the game is running.

void basalt
#

Get the gameobjects, get a reference to their class instance, set the variables.

#

I don't understand what you're struggling on.

#

For the buttons, you'll need to get their references, and subscribe to the onClick event

#

If you don't understand how to get a gameobject's reference, then you should be in the beginner section.

#

If you don't know how to make a function, then you should probably start learning C# instead of asking people to write code for you

lost sand
swift falcon
#

Both firing points are probably set to the same one

#

Can you show me your hierarchy and what you referenced in your script

ashen wing
void basalt
ashen wing
ashen wing
void basalt
#

You should set the values from a singular source, for this problem. That would be the easiest

winged mortar
#

Do you have 10 prefabs at the time you want to assign them values?

#

And does it have to be a unique number within 0-9

void basalt
#

You can either use a static class with the RuntimeInitializeOnLoadMethod attribute, or you can create a mono class and put it on a singular empty gameobject, which then instantiates and assigns values to the objects

#

Or have a static class only containing an integer, and have each of your objects assign themselves a value from that static class, while iterating the static value.

ashen wing
winged mortar
#

And you need keys to store somewhere else rgiht?

#

Just use guids then

void basalt
#

no

#

you do not need GUIDs for this

marsh hawk
#

For some reason line 25 doesn't work, I'm not getting any errors and I think everything is attached correctly

winged mortar
#

And add a seperate check if you already have more than 10

void basalt
#

or you know, just don't use GUIDs in the first place

winged mortar
#

Why are you against Guids?

void basalt
#

Because they have no purpose for this problem

ashen wing
winged mortar
#

The way I see it he wants to give every object an ID

void basalt
#

I'm aware

winged mortar
#

Sounds like guids

void basalt
#

no

#

unsigned integers are the best IDs

#

iterate up

winged mortar
#

Becomes hard to guarantee the uniqueness of ints when you start using multiple threads ;)

void basalt
#

Why would you ever need multiple threads for this

void basalt
winged mortar
#

Even unity themselves consider them a valid option for giving IDs to objects, as they use it in their samples

void basalt
#

lmao

#

There is absolutely zero reason to use GUIDs for this.

#

Want to assign each gameobject's ID to an array slot? Not going to happen with GUIDs.

winged mortar
#

Not going to work if you use the same system for unsigned ints either

#

But you could just use a hashmap for this anyway

void basalt
#

Again, absolutely zero reason

#

you are creating more problems than it's worth.

winged mortar
#

I think the problems of using unsigned integers are worse than the GUID problems

prime hound
#

what arguments going on here

winged mortar
#

GUIDs vs unsigned integers for object IDs

prime hound
#

i see

void basalt
#

I am the author of a rollback netcode engine in development for Unity. It does not work without properly baking IDs into gameobjects.

#

I think I know what I'm talking about.

#

Again, you are creating problems when using GUIDs for this.

#

You also are not going to compress a GUID in any sensible manner

#

I have written my own encoder for my data compression

winged mortar
void basalt
#

ok

#

this conversation is done

prime hound
#

this was an amazing chain of events

winged mortar
#

not my problem that you reply with lmao

#

once someone comes out with a proper argument

void basalt
#

What's your argument again?

#

I missed it

winged mortar
#

See if you maybe read my messages, like I just read your message about the compression of ints, then maybe you'd understand

#

But as you said

void basalt
#

Oh right, generating a random massive number that you can't compress or assign to a buffer index is better than iterating up

winged mortar
#

argument is over.

void basalt
#

we're done here

thin aurora
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

thin aurora
#

Regular integers that iterate up with each object works too, but requires more code to set up to get the next number, especially when persisting data. Guid is as simple as calling guid.NewGuid(), not to mention it's not predictable. I doubt any of that matters, but it's definitely better when it comes to setting an id.

#

Also this conversation is stupid

#

Give your own solution but and don't bash eachother

thin aurora
ashen wing
keen warren
# leaden ice If you don't need it serialized why are you using SerializeReference?

That was to try give it a null value, which in my understanding isn't easily achievable in non UnityObjects.

What I want to do is I have a ScriptableObject that contains a list of Connector. In the EditorWindow, I want to keep a reference of a Connector, but it should default to null but instead it defaults to an instance of Connector. Hence the SerializeReference. Let me know if this isn't ideal.

void basalt
# thin aurora Guids would have been the best solution for this

Sorry, complete disagree. Absolutely no point not to use a direct ID mapped to an array index. You can reuse the IDs and keep it limited to a pretty small binary range. Dude literally said earlier that he wanted the IDs mapped to the GameObjects. This is a direct lookup. No point teaching pointless behavior while he's learning. These things are 128 bits each. I doubt anyone here will go over the UInt16 or UInt32 range on a single machine for entity IDs.

leaden ice
#

So again I'll ask why you're serializing it if you don't need it serialized

keen warren
#

As my ScriptableObject contains a list of Connector, wouldn't I have to serialize the Connector class in order for it to be saved with the ScriptableObject? That's why it's serialized, and in my editor window, I want a nullable Connector property that can have one of those connectors from the list.

winged mortar
#

@thin aurora he knows as he made his own encoder is and a famous author of a netcode rollback engine

winged mortar
#

(I am just playing around, there are reasons why you'd use an int over guids like the one you provided)

undone jay
#

Hey I am using unity's input system and I am wondering how I make so that as long as the jump key is pressed it will keep calling the function Jump

vast bear
# undone jay

You can change the jump input from trigger behavior press to hold or you can switch a "jump" bool on when you press down and switch it off whenever you release the jump button.

undone jay
#

i have Debug.Log("Jump Pressed");
inside the jump function just to make sure it's being called

vast bear
#

You can make a new input called something like jump on release and use the bool option

#

it might be easier with the delegate route youve taken. I usually use events with the new input system.

undone jay
#

will try that thanks

#

thanks did this and it worked

elder flax
#

oh this is getting annoying tbh

#

i have a script to iterate through my items to change something

#

i have a lot of them so im not doing it manually

#

it changes the scripts on the prefab

#

but the changes arent registering for some reason

#

i call PrefabUtility.RecordPrefabInstancePropertyModifications(item.gameObject);

#

that should record all changes right?

#

i also tried recording changes for the component that I changed but that didnt work either

#

the funny thing is it does work but when i reload unity it undoes it

#

instantiating before reload has changes applied

#

but selecting the prefab either shows changes applied or not depending on if I double clicked

#

and the thing is, i did the smae thing to mass add LODs and it worked fine

undone jay
#

how would i have these visible inside the unity inspector but not editable

[Header("Movement")]
private float forwardSpeed;
private float backwardSpeed;
private float sidewaySpeed;
thin aurora
#

There's a library that has more attributes for the editor (I forgot the name), maybe that one has a solution

#

Either way, exposing them makes them mutable

somber ether
#

No one can, at least yet. But in the case you ask a real question, maybe.

lost axle
#

can someone teach me how to implement bobbing for my fps character?

keen warren
# leaden ice So again I'll ask why you're serializing it if you don't need it serialized

I explained, not sure if you caught the message as it wasn't a ping, but I think I found a solution. Inside my editor window I changed [SerializedReference] to [NonSerialized] which seems to work, even though the Connector class is serialized for use with a ScriptableObject. It now starts off as null, and also goes back to null when the scripts are reimported. Not 100% sure why it goes back to null, I'd rather it remember the same Connector but this is better than broken so I'll take it. 🙂

bronze crystal
#

i have this in my uiController

#
    {
        ghostAmount = amount;

        // Update the ghost text
        ghostText.text = ghostAmount.ToString();
        Debug.Log("Ghost Amount: " + ghostAmount);
    }

    public void SetTime(float seconds)
    {
        time = seconds;

        // Update the time text
        timeText.text = time.ToString("0.00");
        Debug.Log("Time: " + time);
    }```
#

but it isn't updating my ui

#

i have a simple if for testing purpose to make sure everything connected right

#
        {
            uiController.SetTime(-1f);
        }
        if (Input.GetKeyDown(KeyCode.G))
        {
            uiController.SetGhostAmount(-1);
        }```
#

but ui not updated

vagrant blade
#

Your UI controller is a monobehaviour. You cannot define it with as a new object, it has to be a component on a GameObject you reference.

bronze crystal
#

yes i changed that

#

    void Start()
    {
        uiController = FindObjectOfType<UIController>();```
leaden ice
keen warren
#

I thought you were referring to the class itself, not the property in all honesty. I also didn't know you could use [NonSerialized] on a [Serialized] class catshrug

copper shoal
#

I'm having some issues with raycast and tag exclusion. Here's my code:

[SerializeField] private float LaserRange = 8;
[SerializeField] private string[] ExcludedTags;
private GameObject circleInstance;
public GameObject circlePrefab;
public LayerMask blockingLayers;

private void FixedUpdate()
    {            
      RaycastHit2D hit = Physics2D.Raycast(transform.GetChild(0).transform.position, transform.right, LaserRange, ~blockingLayers);
       Debug.DrawRay(transform.GetChild(0).transform.position, transform.right * LaserRange);

            if (hit.collider != null)
            {
                //Check every tag
                for (int i = 0; i < ExcludedTags.Length; i++)
                {
                    if (!hit.collider.CompareTag(ExcludedTags[i]))
                    {
                        Debug.Log("Is not excluded!");

                        // If the circle instance doesn't exist yet, create it
                        if (circleInstance == null)
                        {
                            circleInstance = Instantiate(circlePrefab);
                        }

                        if (!Input.GetKey(KeyCode.Mouse1))
                        {
                            // Update the position of the circle instance to match the point of contact
                            circleInstance.transform.position = hit.point;
                        }
                    }
                }
            }
            else
            {
                // If the raycast doesn't hit anything, destroy the circle instance
                if (circleInstance != null && !Input.GetKey(KeyCode.Mouse1))
                {
                    DestroyLaser();
                }
            }
    }

I added ExcludedTags strings in the Editor and checked if I've not misspelled any of them. When the raycast touches a GameObject with excluded tag, the circlePrefab is still being instanciated. Any ideas?

glossy wadi
#

I'm currently trying to make a basic 2d spaceship, and so far(with the help of unity answers), i've managed to make this:

    // Update is called once per frame
    void Update()
    {
        Vector2 horizontal = Input.GetAxisRaw("Horizontal") * transform.right;
        Vector2 vertical = Input.GetAxisRaw("Vertical") * transform.up;
        float rotation = Input.GetAxisRaw("Rotation");
        Vector2 inputVector = horizontal+vertical;
        FireThrusters(inputVector, rotation);
        
    }
    
    public void FireThrusters(Vector2 movementDirection, float rotation)
    {
        Vector2 finalThrust = Vector2.zero;
        //Apply Movement
        foreach(var thruster in thrusters)
        {
            //Movement
            float dot = Vector2.Dot(thruster.transform.right,movementDirection);
            if(dot >= fireThreshold)
            {
                thruster.GetComponent<SpriteRenderer>().color = debugColorActive;
                float participation = dot/fireThreshold;
                Vector2 thrust = thruster.transform.right*participation*maxThrustForce;
                finalThrust += thrust;
            }
            else
            {
                thruster.GetComponent<SpriteRenderer>().color = debugColorInactive;
            }

        }

        rb.AddForce(finalThrust);
        rb.velocity = Vector2.ClampMagnitude(rb.velocity,accelerationlimit);
    }
    
    }```
This works really well, however, It does not account for rotation. How can I check which thrusters should "Fire" to get my desired rotation, and then rotate using addtorque, ideally in a similar mannar to the code above? I used this: https://answers.unity.com/questions/923915/determining-thruster-activation-on-3d-spaceship.html link for what I have so far.
leaden ice
copper shoal
#

but there's the (!hit.collider.CompareTag(ExcludedTags[i]))

#

don't instantiate if the tag doesn't match

bronze crystal
#

still no clue why my uicontrollerdoesnt update the ui while showing the value of the variables

knotty sun
copper shoal
#

ohhhhh

#

now I get it

#

how can I fix it?

knotty sun
#

check all of the tags first, then do the rest of the logic of NO tags were found. A bool is your friend for this

merry fog
#

does anyone have a 3d vr no clip script that uses trigger to use

bronze crystal
#

on my canvas i have the uicontroller, but my gamecontroller reference cant find it ``` private UIController uiController;

void Start()
{
    uiController = FindObjectOfType<UIController>();```
sacred dove
#

Hi! I want to create a sync method that allows to get data from a local server. This code does work, but I can't it why is it so slow. For simple curl command the response is instant, but using my code the response takes a few seconds. How do I make it faster?

        private string MakeCustomRequest(string endpoint, string type)
        {
            var task = MakeCustomRequestAsync(endpoint, type);
            return task.GetAwaiter().GetResult();
        }

        private async Task<string> MakeCustomRequestAsync(string endpoint, string type)
        {
            using var request = new HttpRequestMessage(new HttpMethod(type), addrBegin + endpoint);
            var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(config.User + ":" + config.Password));
            request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
            var response = await httpClient.SendAsync(request).ConfigureAwait(false);
            var toString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            Debug.Log(type + "  " + addrBegin + endpoint + ": \n" + toString);
            return toString;
        }
bronze crystal
#

i dont get it

#

object in scene with script

#

the right tag

#

uiController = GameObject.FindWithTag("UIController").GetComponent<UIController>();

#

NullReferenceException: Object reference not set to an instance of an object

vagrant blade
#

You haven't shown that you're using the right tag.

bronze crystal
#

its probably something common and stupid, cant figure it out.

rocky jackal
#

How do i use the NetworObject.TrySetParent funktion corectly when i use it it gives me an error saying that its a group Methode and it cant be set

idle flax
#

Hey all. How do I loop through every int in a float, then loop through every decimal in the same float? Couldn't find anything on this on Google.

leaden ice
#

Likewise for "every decimal in a float"

stable osprey
#

duh

idle flax
#

Every whole number in a float, every decimal in a float.

leaden ice
#

???

#

Are you saying you want to loop over the digits?

stable osprey
#

duh

#

(sry early April affected me)

idle flax
#

Nevermind, I think I figured it out.

swift falcon
#

Int in float maybe like this:

5.15
7 <--
1.9
6 <--
9 <--
leaden ice
#

But that's not a float that's 5 different values

#

Maybe an array of floats?

swift falcon
#

Yeah but maybe thats what he means

runic skiff
#

https://hastebin.com/share/omolekivig.csharp
Why might I be getting SendMessage cannot be called during Awake, ChechConsistency, or OnValidate (Brock: OnSpriteTilingPropertyChange)?

stable osprey
#

-- delete 'OnValidate' first, and if it persists, this means it's because of the 'Awake' method

nocturne meadow
#

Hi all may i ask a question?

stable osprey
#

hmm..

#

ok

nocturne meadow
#

I have a textfile that gets updated by a python script.
Unity reads the text file, however Unity also locks it which prevents python from updating it since it cant append to the text file

#

anyway around this?

stable osprey
#

ah. that sucks

nocturne meadow
#

it does

ocean river
#

I have a question too.
I cant get skeleton to work from a fbx, that i exported from maya 2022.
everytime i boot the game on my 3ds, it crashes after the logo.
only when i have the skeleton model loaded.

leaden ice
ocean river
#

i mean, model with a skeleton.

leaden ice
#

This is not a Unity issue it's your code issue

ocean river
#

but its unity for 3ds...

nocturne meadow
#

its not my code issue

#

lmao

#

the code works fine

stable osprey
nocturne meadow
#

unity locks the file, i cant even manually update it since the resource is busy

leaden ice
stable osprey
#

except -- what are you wanna use that file for?

leaden ice
#

What's the context here

stable osprey
ocean river
#

yep.

#

theres that nintendo 3ds sdk

#

and unity for n3ds thing

nocturne meadow
# leaden ice Are we talking about gameplay? The editor? What?

its very simple, i have a textfile. lets say test.txt and it contains text 1234
I ready the file (on Update) as follows: (works fine)

public void ReadString()
{
    string path = "C:/Users/ZZZ/My Code/ZZZ/data/collections/ZZZFinal.txt";
    StreamReader reader = new StreamReader(path); 
    //Read the text from directly from the test.txt file
    coins.text = reader.ReadToEnd();
    reader.Close();
}

however if i open my text file i cant make a change since resource is busy, which makes sense, but unity never "releases it'.
do i make a coroutine or something , maybe unity releases the lock?

leaden ice
stable rivet
nocturne meadow
stable rivet
#

🕵️

nocturne meadow
#

its not a game btw

leaden ice
#

And it's no wonder unity always has a file lock on it

nocturne meadow
#

the text file updates every second XD

stable rivet
#

you’re reading the file every frame and wondering why the resource is busy

nocturne meadow
#

yea i knw

leaden ice
#

Or

nocturne meadow
#

im asking whats the best way to unlock, since it does work at times

leaden ice
#

Better yet

#

Use IP

#

TCP

#

Not a file

stable osprey
#

yup!

nocturne meadow
#

makes sense i guess ill look into it thanks

runic skiff
nocturne meadow
# leaden ice This ^

Thanks mate got it working, this is a way better solution now need to spend time to flesh it out..

rocky jackal
#

the bright blue box is a child of the dark blue box. the dark blue boc is connected to the orange box with a fixed joint. when the orange box(its gonna be a car) moves they should all move but the light blue box also has physics(because its the player) should still be able to move by itself and rotate wich would create a offset but right now the light blue box does not move at all when the dark blue box moves.

#

how could i solve this ?

ancient sail
#

Does anyone know how to fix this blur in camera?

golden vessel
#

Hey, how does WaitForSeconds works with very short times (close to time per frame)? I want to write each letter one at a time without it being frame dependant

lucid valley
#

it's never going to happen on the exact time (or just extremely unlikely)

golden vessel
#

Alright that explains a lot. Cos I was playing a sound according to that but the sound wasn't consistent

lavish mist
#

Hi everyone, i have a question. Im making a top down game where, to attack, the player
has 4 triggers 1 above, 1 below, 1 on the right and 1 on the left, and i want that when an enemy
gets inside of one of them (im using OnTriggerStay in the enemy's gameObject), and the key in the respective
direction gets pressed (im using GetKeyDown) a boolean called invincibility turns false
(which when its true, makes thefunction of recibing damage inside of the enemy
(called in update) not execute) once, for 1 frame, and the enemy's health gets reduced
by 5 (they have 20 health)

golden vessel
#

Should PlayScheduled in advance

lavish mist
#

what happens is that sometimes it works well, but sometimes it doesnt gets called

What is or are the reason this is happening? and how to solve it?

elfin tree
#

Can you get an int from an enum even though there are none defined?

swift falcon
#

i lost my temper
im trying to use physics2D.raycast to check for the enemy(which has a box collider2D before you ask)
and it wont detect it

potent sleet
#

oh?

potent sleet
#

you could just cast it

#

int myNumber = (int)myEnum

plush sparrow
#

Is there anyway to store game data in application memory instead of file memory

#

Like the file memory stored using json
It can be accessed by the user and modified
I don't want that

#

Is there any other proper way to store data?

potent sleet
#

just store the file remotely..

tepid river
#

i have a UI thing on my cameras canvas that tracks a scene object.
i do "myCamera.worldToScreen(myObj.position)" which works generally.
but when i move the camera, the UI object jumps/is wobbly while trying to stay at the correct position.
cant wrap my head around why that would happen. anyone else had a similar problem?

the camera-object ray is marked red in the scene, so thats not where the jumping comes from.

https://imgur.com/Fcoq8vh

#

positioning happens in Update(), i tried lateUpdate and FixedUpdate too but all have a similar problem

swift falcon
#

Tried everything but it still persist.

#

I also tried someone elses code and it had the same issue

hearty perch
#

can someone tell me how to get child of a game object with script?

hearty perch
#

alr mb

buoyant shuttle
#

Hey guys, can someone help me with a basic formula... I have 2 vars, lets say MaxX= 1000 and Maxy= 100. (x,y). I have to other vars x and y both = 0. In the update I have the x/y both increasing. I need them to both reach their max at the same time. How do I determine the amount I increase them both by?

#

This is easy stuff.. But I have been building websites for awhile and been away from game coding and math for awhile lol.

leaden ice
#

time being the amount of time the animation should take in seconds

potent sleet
#

I think..

inner yarrow
#

I'm not sure if this is code, but I want to be able to decide which scenes are the levels, and the order that they are in. I was going to do this by having a SerializeField Scene array on my player, so that I can just drag them in, but it says that the type Scene is not supported. I also tried an array of SceneAssets which does let me drag them in, but I can't figure out how to load the Scene given a Scene Asset. Does anyone know of a different way to do this?

potent sleet
inner yarrow
# potent sleet explain further wdym which scenes are levels

I mean that I have a lot of scenes in this project, but I don't want the player to play through every scene becayse some of them aren't levels, some of them are levels to play through, but others are things like test scenes where I just try to get something to work.

potent sleet
#

don't u want a specific scene?

#

why do you need to "go through all of them"

bronze crystal
#

i dont understand i made static instane variable still cant acces my class

#

    [SerializeField] private TextMeshProUGUI ghostText;
    [SerializeField] private TextMeshProUGUI timeText;

    private int ghostAmount = 0;
    private float time = 0f;

    private void Awake()
    {
        ghostAmount = 3;
        time = 1f;

        if (instance != null && instance != this)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
    }```
#

private UIController uiController = UIController.instance;

inner yarrow
buoyant shuttle
somber nacelle
inner yarrow
#

oh I see

bronze crystal
#

i also have my script attached to a object

#

but when trying to acces it i get error again

potent sleet
#

on GameController

bronze crystal
#
        {
            uiController.DecreaseTime(1f);
        }
        if (Input.GetKeyDown(KeyCode.G))
        {
            uiController.DecreaseGhostAmount(1);
        }```
#

increase and decrease time

potent sleet
#

uiController is null

somber nacelle
#

show where you've assigned uiController

bronze crystal
#

    void Start()
    {
        // Set the initial game state
        GameManager.State = GameState.MainMenu;
        Debug.Log("Game controller update ruunning: " + "Update() method running");
    }

    void Update()
    {
        CheckGameState();
        TriggerPause();
        CheckGhostAmount();
        CheckTimeAmount();
        if (Input.GetKeyDown(KeyCode.T))
        {
            uiController.DecreaseTime(1f);
        }
        if (Input.GetKeyDown(KeyCode.G))
        {
            uiController.DecreaseGhostAmount(1);
        }
    }
potent sleet
#

uh

somber nacelle
#

you shouldn't assign it in the field initializer, if both objects exist in the scene at edit time then the field initializer will likely run before Awake has been called to set up the singleton

potent sleet
#

shouldn't this error

somber nacelle
#

the instance variable is static so no, it's just null at that point

potent sleet
#

oh tru

bronze crystal
#

how is it null tell me

somber nacelle
#

literally just explained why

potent sleet
#

if instance is static why not just use that , or is it there benefit to cache to private var

lucid valley
#

or just make it a property

#

private UIController uiController => UIController.instance;

somber nacelle
#

or get a proper reference to the instance instead of making everything into a singleton

bronze crystal
#

pff, what a headache connecting two classes

bronze crystal
lucid valley
potent sleet
#

ya more of a general question, is there a benefit(besides less typing I guess) over doing this instead ^

lucid valley
#
void Update()
    {
        CheckGameState();
        TriggerPause();
        CheckGhostAmount();
        CheckTimeAmount();
        if (Input.GetKeyDown(KeyCode.T))
        {
            UIController.instance.DecreaseTime(1f);
        }
        if (Input.GetKeyDown(KeyCode.G))
        {
            UIController.instance.DecreaseGhostAmount(1);
        }
    }
potent sleet
#

hmm I guess I answered my own, reading on this it

"every time you access the static instance CLR has to lookup the reference to static instance in memory"

lucid valley
#

yeah, reference to a reference?

potent sleet
#

wonder if this is true

Caching the static instance into a variable might make sense in certain cases where you need to access the static member multiple times within a method or across multiple methods, and you want to avoid the overhead of repeatedly accessing the static member from the class's metadata. However, this is typically a micro-optimization, and should only be done after profiling has shown that it's necessary.

somber nacelle
#

it absolutely is a micro-optimization, the performance difference is negligible at best. gimme a few moments and i'll throw together a benchmark to prove that

lucid valley
#

i'd say it'd be very quick since it should still be in the cache

potent sleet
#

on this. so true right here as well

In general, it's usually better to write clear and maintainable code, rather than trying to optimize performance prematurely.

#

eg instead of using a bunch of static to rely on?

bronze crystal
#

when i store it into a variable suddenly it doesn'work

somber nacelle
#

are you still storing it in a variable in the field initializer? or are you doing so in Start like you should be when doing that?

bronze crystal
#

i made the varialbe and then in start

somber nacelle
#

do you assign to the Instance variable in the UIController's Awake or Start method?

bronze crystal
#

start

somber nacelle
#

there you go, that's why. it's Start may not have run before another object's Start

bronze crystal
#

    private void Awake()
    {
        uiController = UIController.instance;
    }```
somber nacelle
bronze crystal
#

why when i use it directly it works, but when stored in variable it doesn't

somber nacelle
#

do this part in Start and assign to the Instance variable in UIController's Awake

bronze crystal
#

what this part?

bronze crystal
#

there is just variable and assign

potent sleet
potent sleet
#

the order matters

solar current
#

hello

#

hello

#

i need help

#

NOOOOOOOOOOOWWWWWW!!!!!!!

somber nacelle
solar current
#

please i want to create android game

#

and i am too Noob on coding nothing i know it about coding

somber nacelle
#

please click that link and read it

bronze crystal
#

this is weird now direct reference als crashes

solar current
#

hi give me a moving player script

somber nacelle
#

there are plenty of tutorials for making that yourself, go find one

bronze crystal
solar current
#

I know it

#

i use chatgpt

#

but he has ploblems at coding

bronze crystal
#

its just a tool

solar current
#

anyone know coding

warm wren
#

yes

solar current
#

so help me

somber nacelle
#

this isn't a place for people to do the work for you

bronze crystal
#

but if i might ask developers out here, what best practices are you using to connect classes?

somber nacelle
fiery jackal
#

Hey everyone, I'm having an issue on my new project that I didn't have before and I have no idea what is going on. After I configured the joystick in the new Unity Input System, when I have a joystick connected I can't use the keyboard keys anymore, just the joystick ones. If I disconnect the joystick, then the keyboard keys start to work again. Any clue if I'm missing any configuration to enable both?

bronze crystal
#

why my time rapidly decrease, thought i fixed that with coroutines

#
    {
        while (true)
        {
            yield return new WaitForSeconds(1f);
            DecreaseTime(1f);
        }
    }```
somber nacelle
#

you're probably starting a whole bunch of instances of the coroutine, of course you haven't provided enough context to know if that is actually the case or not

bronze crystal
#

this is the function i call ```public void DecreaseTime(float seconds)
{
time -= seconds;

    // Update the time text
    timeText.text = time.ToString("0.00");
    Debug.Log("Time: " + time);
}```
#

here is where i start it: case GameState.InGame: // Handle the in-game state // Go to the start game scene Debug.Log("Your gamestate is: " + GameManager.State); StartCoroutine(UIController.Instance.DecreaseTimeByOne());

#

in my game controller sscript

somber nacelle
#

i'm just going to assume you are starting it in Update because you're still not providing enough context

bronze crystal
#

i have nothing in update

royal sable
#

I don't recall but is it not possible to use the [field: SerializeField] on List<T> properties?

somber nacelle
#

should be possible

somber nacelle
royal sable
bronze crystal
inner yarrow
#

Is there a built in function to invert a layermask?

#

If not I'll make my own, I'm just curious, and I can't find out if there's a built in function.

golden vessel
#

Is there a way to schedule an animation? So that it's not frame dependant.

bronze crystal
#

@somber nacelle nvm fixed it.

somber nacelle
#

that's good because you didn't bother sharing where you had started the coroutine yet 😉

mystic spade
#

2D controller basic script:

hollow hound
#

Architecture help

I have a stun mechanic.
I have the MoveToPlayer script.
MoveToPlayer is used both by stunnable entities (such as enemies) and non-stunnable enteties (such as auto-aiming projectiles).
Behavior of the MoveToPlayer changes from stun condition.
Is the best solution is to inherit from MoveToPlayer something like StunnableMoveToPlayer to implement stun logic there? That way all the movement logic will be there and I would be able to override parts that are affected by stun.

tepid river
#

either that or you use composition.
add an optional object that can be asked "can the player move" and in that have stun logic

#

for starters, inheritance is usually fine, just personally not a fan of it because it gets messy to fast

oblique spoke
#

Trying to represent complex objects through a tree of inheritance is the classic recipe for problems.

tepid river
#

10 years into your project, you notice that you would like to dock an asteroid to a ship for transportation.
tough luck, asteroids and ships are only 2nd cousins in the inheritance tree

#

happened to a game i used to mod

keen echo
#

I test my code, but I do not test them by writing interfaces because I forgot what they are for. Why should I test my code with an interface?

potent sleet
#

wdym test with an interface ?

#

are you talking about the type interface or something else

tepid river
#

well interfaces exist if you have multiple classes doing similar things and want to hide that.
easier testing is just a nice side effect

#

imo its pointless to hide a single class behind an interface, no matter if for testing or not

potent sleet
potent sleet
#

wdym more productive, it has it's own usecase

#

esp if you dont want to use inheritance

tepid river
#

it makes swapping out classes a lot easier, so yes it leads to improved productivity in the long run. but you have to figure out a smart interface first which is less productive in the short run

keen echo
tepid river
#

usually you create the interface if you already have these almost-similar-classes-doing-similar-things
not before you have it

potent sleet
#

I use them often when i make things like services etc

hollow hound
# tepid river either that or you use composition. add an optional object that can be asked "ca...

I would like to use composition, but I can't find the right mechanism.
I don't fully understand what you mean by optional object.
For context, my MoveToPlayer has Update() {move(); }. Do I need some StunnableMovementController, that will call in its update move() if it's not stunned? That way, MoveToPlayer won't be Monobehevior, just a c# class?
MoveToPlayer also has OnCollision logic (to stop trying to move if it's already colliding) and I don't want to duplicate this logic in different MovementControllers.

#

I don't thins that call OnCollisionEnter { moveModule.OnCollision(); } in MovementController is a good option.

strong cloud
# keen echo is it more productive?

Productivity is relative. Interfaces are ways to "interface" with something. In the context of programming, it's basically a description that says "hey here's how you can use this thing". In the context of testing, you basically start by defining your interfaces so that you can write tests that make sense, and then you write the rest of your code to align with those interfaces so that the tests can do their thing

tepid river
#

if you use composition, you dont need a childclass.
you just give your MoveToPlayer a field that takes an object of type "StunManager".
it queries its stun manager if its stunned, but can also handle stunManager being null.
that way its optional to use it

OR you actually use StunnableMovementController which shares an interface with NormalMovementController so the characters can take whatever of the two, without caring which one it is

strong cloud
#

for example, if I want to be able to ask my book object who its author is, it would be nice if I could just do book.getAuthor(), so I might have a WrittenMaterial interface that says things implementing it need to have a getAuthor method

bronze crystal
#

i'm checking to only decrease time when iam ingame, so for example if i shift to state of game pause this would not decrease, but it is. public IEnumerator DecreaseTimeByOne() { if (GameManager.State == GameState.InGame) { while (true) { yield return new WaitForSeconds(0.01f); DecreaseTime(0.01f); timeText.text = FormatTime(time); } } }

tepid river
#

if statement goes inside the while look

#

otherwise it gets started and starts ignoring the state

oblique spoke
#

You can also define features of a controller class by adding interfaces like IStunnable to it, while querying for them with GetComponent as separate features, if separating into different classes is awkward.

bronze crystal
bronze crystal
tepid river
#

heh
well you have to handle what the while loop does if the player is not in the game

candid trench
#

So i took a look at the profiler to try and figure out where my bidirectional pathfinding algorithm is spending most of its time.
Turns out its when i sort the open lists!

So heres my question. Rather than sorting the entire lists each iteration in the while loop.
How do i implement an insertion sort? whats the best container to do so on given what im trying to achive?

https://pastebin.com/rCUTQFXu

tepid river
#
public IEnumerator DecreaseTimeByOne()
    {
       

            while (true)
            {
                yield return new WaitForSeconds(0.01f);
                if (GameManager.State == GameState.InGame) {
                  DecreaseTime(0.01f);
                  timeText.text = FormatTime(time);
                }
            }

    }
#

something like this probably

#

right, also you dont have an exit condition...

bronze crystal
#

no i use toggle

potent sleet
#

you can just break the loop on gamepause state

bronze crystal
#
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (GameManager.State == GameState.InGame)
            {
                GameManager.State = GameState.Paused;
            }
            else if (GameManager.State == GameState.Paused)
            {
                GameManager.State = GameState.InGame;
            }
        }
    }```
#

so basaicallyit would only run when ingame state

potent sleet
#
while (true)
            {
                yield return new WaitForSeconds(0.01f);
               
                  DecreaseTime(0.01f);
                  timeText.text = FormatTime(time);
                   if (GameManager.State == GameState.Paused) break;
                }
            }```
dark ice
#

How can I control an alembic track through code? As in control when it plays.

keen echo
strong cloud
winged mortar
strong cloud
candid trench
candid trench
winged mortar
#

Hoping that fixes your issue :)

#

Also I think for bidirectional a star you need to keep a lot more lists right? Maybe the overhead is not worth the gain in performance that you get

#

Might be worth to profile

candid trench
hollow hound
# tepid river if you use composition, you dont need a childclass. you just give your MoveToPla...

Oh, In my example I mean that StunnableMovementController is not an child class, just a Monobehaviour.
I don't completely understand how stunManager would inject in the behaviour of MoveToPlayer.
The only way I see, is MoveToPlayer is checks something like StunManager.stunned and changes its behaviour. But that way I will have stun logic in components that don't know anything about stun and don't use it. And there can be more statuses like that, it seems strange to check for all statuses in script that don't actually uses that logic and just moves to player.

The problem with different controllers is that MoveToPlayer have some OnCollision logic that changes state of the component, so I can't
use usual functions from simple c# class there.

candid trench
winged mortar
#

Not the memory, but you need to sort more lists

candid trench
#

well yea, but with priority queue that becomes a non issue no?

#

by just using the distance as the priority

hollow hound
tepid river
winged mortar
candid trench
#

just distance to the other ends head

#

--source-> distance <-target--

winged mortar
#

Also you are right, wouldn't make much of a difference with priority queues

candid trench
#

yea, but im unable to make a priority queue x) cant seem to find the correct namespace

winged mortar
#

Isn't the priority of a path determined by the current path length + the heuristic?

#

Oh no

#

This is since .net 6

candid trench
#

wdym?

winged mortar
#

PriorityQueue datastructure doesn't exist in unity's version of .NET

#

You can't find the namespace because it doesn't exist

candid trench
#

what version is unity using?

winged mortar
#

I think it's 4.7 or 4.8

#

.NET framework

candid trench
#

oh christ

winged mortar
#

Since 4.5 ms started working on .NET core 1/2/3, which was later renamed to just .NET

#

They've still been updating .NET Framework though

#

The priority queue is .NET 6, so it doesn't exist in the version unity is running

candid trench
winged mortar
#

Check your .csproj file to be sure

#

It should be in there

#

I haven't checked in a hot minute

candid trench
#

youve lostme

#

do i check the .dll ??

winged mortar
#

No, there should be a .csproj in in your project, it details the information about the scripts n stuff, I think one of the properties recorded in it is the .net version

#

But I could be mistaken

#

Filename is something like assembly csharp.csproj

#

It's just an XML file you can open in any text editor (preferably your IDE)

candid trench
#

ah its an actually file, hang on then

winged mortar
#

Also, double check your priority calculation

#

I am pretty sure that just using the distance between the source and target as a priority leads to it being a greedy search

#

Which will lead to poor performance when there's a lot of obstacles

gilded estuary
#

Hey, so I just wanted some advice, would it be wise to have a debug menu all set up in a different scene so that it can be used either in the scene it’s in directly, or load the scene while in another one and simply load the canvas and pause the game, etc.? Or would it be better if it was all done in script so the script can just be added into a game object in the scene and trigged somehow that way and save space maybe?

lusty seal
#

when i build my addressables and i'm not using cdn where are they saved ?

swift falcon
#

So i want to have a delay beetween each animation i make such as if i press "1" it plays animation1 and if he presses button 1 again he has to wait 2 second t o do the attack again> anyone have any idea on how to do this ?

winged mortar
#

Loading a scene additively also works though if you have a lot of scenes

candid trench
#

something like this

hollow hound
# tepid river then use two different types of MovementController, one for the stunnable type a...

The problem with different controllers is that now MoveToPlayer has its own state that changes from onCollisionEvents.
So with different classes I will need to basically duplicate this state and it's logic.

More abstract solution could be creation of State field of type MovementState. Then, all methods will pass state to MoveToModule (such as move.OnCollision(state). That way all of the base move logic will be handled by this MoveToModule class (just c#, not mb).
Do you think this is the right solution?

candid trench
tepid river
#

well sounds like collision and stunning should be separate logic objects

candid trench
winged mortar
winged mortar
hollow hound
winged mortar
#

If you'd only use the distance, it will always pick the node which would result in a lower (probably Euclidian) distance, which is essentially a greedy search

gilded estuary
candid trench
winged mortar
candid trench
# winged mortar Be sure to measure, I'm curious to what degree your solution will speed up!

seems like im failing to implement "f" in the G = F + H calculation 😛

//Sort the queue by distance to the other queues head
            if (i % 2 == 0)
            {
                float f = 0;
                KeyValuePair<Tile, Tile> tempCurrent = current;
                while (tempCurrent.Value != null)
                {
                    float distance = (tempCurrent.Key.position - tempCurrent.Value.position).magnitude;
                    f += distance;
                    visitedFromSourceTile.TryGetValue(current.Value, out Tile parent);
                    tempCurrent = KeyValuePair.Create(current.Value, parent);
                }

                queueFromSourceTile.Sort((x, y) => ((x.Key.position - queueFromTargetTile.First().Key.position).magnitude + f).CompareTo((y.Key.position - queueFromTargetTile.First().Key.position).magnitude + f));
            }
            else
            {
                float f = 0;
                KeyValuePair<Tile, Tile> tempCurrent = current;
                while (tempCurrent.Value != null)
                {
                    float distance = (tempCurrent.Key.position - tempCurrent.Value.position).magnitude;
                    f += distance;
                    visitedFromTargetTile.TryGetValue(current.Value, out Tile parent);
                    tempCurrent = KeyValuePair.Create(current.Value, parent);
                }
                queueFromTargetTile.Sort((x, y) => ((x.Key.position - queueFromSourceTile.First().Key.position).magnitude + f).CompareTo((y.Key.position - queueFromSourceTile.First().Key.position).magnitude + f));
            }
#

Unity crashes 😛

winged mortar
#

I don't have the time to check right now, can take a look at it tomorrow though, in the meantime someone else could try to help you

candid trench
#

Aye sorry! didnt mean to be bothersome. Ill fix it :>

#

i always do

winged mortar
#

Is really no problem, just a little late for me so going to bed in a little bit, let me know if you figured it out or not and I'll take a look if you didn't!

dusty talon
#

hey anyone know why SetCategoryAndLabel wouldnt work? I have a sprite library and sprite sesolver and renderer. But calling that with a category and label doesn't have any effect at start

winged birch
#

Hello! I'm working on an achievement system, but am not sure what I'd need to code to have the game register each scene's collectibles as 'unique' to that scene (specifically so I can have achievements for all coins in a level / all collectibles from all levels, where each level is its own scene). Any help much appreciated!

Item collector script - https://hastebin.com/share/moluxatade.csharp
Datamanager script for saving & loading - https://hastebin.com/share/jexifawiko.csharp

swift falcon
#

yo squid just have a bool for each scene ? like bool AllCoinsCollectedInScene1

#

U might have to make a singleton or some sort of static class to implement that but thats my first guess

hollow hound
#

Is it possible to create type of scriptableobject that implements interface?
Or the only way is to create abstract class ( : SctiptableObject, IMyInterface) and then inherit all classes from it?

winged birch
#

🤔 It's an option, I just wonder how I'd tell the DoNotDestroy object thing I have what scene it's currently in

swift falcon
#

Ahhh i see ur data manager class seems big as is but u might have to add to it

#

U could mark each coin with a tag for each level Squid

#

That way u dont really care about what scene ur currently in just what coins belong to which scene

#

@winged birch

soft shard
winged birch
#

True - I'm thinking of adding a 'using Unity.SceneManagement' to my ItemCollector script and having it read the name of the current scene it's in

#

It'd be a bit messy but then I could just have if statements for each level telling it which one this collectible belong to

swift falcon
#

That should work as well both are going to require a bit of spaghetti code but itll get the job done

winged birch
#

ha, expect to see me back in a day or two when something gets buried in the spaghetti. thanks for your help

shell scarab
hollow hound
soft shard
swift falcon
#

my tag idea ^^

#

I think giving the coins some sort of id is the best route personally

lyric wadi
#

yea

shell scarab
#

if you need every coin to have a unique ID that you don't assign in the inspector that's persistent you could store it in a file

winged birch
#

Mm, I've not dabbled in dictionaries but could give it a go

swift falcon
#

Not really each specific coin more so coins in a specific scene

#

I believe thats what he wanted i shouldnt speak for him

#

if its each specific coin thats a different can of worms

soft shard
swift falcon
#

I dont think i understand his question

#

Just make a reference to the S0's

#

Do interfaces prevent them from being referenced ?

soft shard
swift falcon
#

OOOOHHH

#

he cant call the interfaces functions

#

because theres no GetComponent

#

i getcha

hollow hound
swift falcon
#

List<>

#

Thats what i thought u meant honestly U just want a container for the SO's right ?

winged birch
#

I'm not 100% sure how I want it to work at the minute, so this might be a bit confusing, but bear with me - this is the idea

  1. Each level has 10 silver coins, 5 gold coins, and 1 red / blue / green gem
  2. Their collection is sort-of tracked through this script - https://hastebin.com/share/moluxatade.csharp
  3. I'm working on achievements that persist between scenes, from 'collect all silver coins in level 1' to 'collect all gold coins in the entire game'
  4. When the player dies / restarts a level, all coins and gems are 'uncollected', which may cause issues?
  5. Achievements, when unlocked, should never be re-locked
  6. player data is saved via a DoNotDestroy object that has this script - https://hastebin.com/share/jexifawiko.csharp
#

the solutions y'all were offering should still be valid, I'll give dictionaries a go, but hopefully that clarifies a bit

swift falcon
#

The player dying isnt a issue

#

Just set all coins to zero upon death

winged birch
#

it does reset the scene on player death, though, which makes me worry

swift falcon
#

why ?

#

Just have achievements always set to true once unlocked ?

winged birch
#

Partially to be annoying -- this is for my dissertation on achievements affecting player engagement, so it's to see how badly players want 'em (if they'll keep going for all coins after dying and losing their progress in that level)

#

I can look into just a proper respawn mechanic if that's at odds with reality though

soft shard
# hollow hound I need something like this ```cs public class SomeSO1 : ScriptableObject, IInte...

Ohh yeah, Vee has a good point, you could make a List<ScriptableObject> and assign SO1,2,3 in it, and if you know they all have that interface, you can then try the cast on some index of the list, or create a base type that uses the interface and make each inherit from that, for example:

public class SomeSO : Scriptable, IInterface {}
public class SomethingSpecific : SomeSO {}
public class AnotherSpecific : SomeSO {}

public class SomeClass : Mono
{
public List<SomeSO> ...
}
swift falcon
#

Squid homie ur overthinking it lol

#

Just make a method that handles the player death OnDeath() { coins = 0 )

hollow hound
winged birch
#

🫡 I'll do some tinkering and report back. thank you gamer

swift falcon
#

Ok so my first thought was...and this a shitty thought mind u

#

Just make SO's that implement that interface and make SO's that dont

#

And if those SO's are on a gameobject check the gameobjects and not the SO's

hollow hound
soft shard
swift falcon
#

the scripts i meant sorry dibbie

hollow hound
#

Thanks, I'll try it

soft shard
# hollow hound But I want to this variable to has this interface methods, that so's implement

If you want to access them directly, you could extend that example with virtual functions, for example:

public interface IInterface
{
public void Something();
}

public class SomeSO : ScriptableObject, IInterface
{
public virtual void IInterface.Something() {}
}

public class SomethingSpecific : SomeSO
{
public override void Something() {Debug.Log("do something cool");}
}

Then you should be able to call it with something like

public class SomeClass : Mono
{
public List<SomeSO> data

data[someIndex].Something();
}

If someIndex happens to be 2, and your list of data happens to be 3 or more elements, and in this example, lets say index 2 of your data happens to be SomethingSpecific, then that class can decide what "something" interface does, in this case, log to the console

swift falcon
#

This is my sign to learn about virtual functions

#

arent they just methods that overwrite the parents definition of the base method or am i mistaken?

hollow hound
soft shard
# swift falcon This is my sign to learn about virtual functions

It can be useful for inheritance, like if you have a base "Weapon" class that uses a virtual "Attack", a bow and a sword could override that, in Unity you might find yourself with a lot of those "modification of existing thing", but if you want a hybrid weapon tthat is both a bow AND a sword, then inheritance may not work well - or you can but youll end up with 3 or 4 classes to make the hybrid work

toxic notch
#

Hi, I'm trying to learn how to convert my hand movement in local space so that it results in the same movement around a robot. Right now I'm just getting the difference in hand position between each frame and scaling it then applying it to the robot target but that could move it in a bunch of directions not based on where I'm looking. Any ideas?

swift falcon
#

OOP is great they say

#

So a....abstract classes abstract methods....

steady moat
#

OPP is a paradigm.

swift falcon
#

its OOP*

#

i was trying to say that an absract classes abstract methods sound the same as virtual methods

#

sorry if that wasnt clear i was just trying to get a better understanding i prolly just worded it badly my apoligies

#

and c# is very much OOP

#

Maybe not as much as python and javascript

soft shard
swift falcon
#

^^^ now i get it

#

Thank u Dibbie

steady moat
#

C# is way more OPP than python or javascript.

#

They are not even compiled nor typed. You need to go out of your way to make OPP with Python or Javscript.

swift falcon
#

its O O P i dont mean to pick on u i promise

steady moat
#

Object Oriented Programming ?

swift falcon
#

ur writing OPP

steady moat
#

You are not... OOP is a paradigm that you follow.

#

There is Data Oriented Programming

#

Procedural

#

Functionnal

swift falcon
#

Ok so whats opp

steady moat
#

A paradigm

swift falcon
#

whats the acronym

steady moat
#

It is not an acronym

swift falcon
#

lets move on

spiral crest
#

Im working on an app where the user takes a photo or selects a previous photo and text is extracted from the image. I am hung up on how to extract the text from the image

cold parrot
spiral crest
cold parrot
spiral crest
cold parrot
#

most of the simple ones are nowhere near as capable as recent AI hype would make you expect

spiral crest
#

I couldnt find tesseract for untiy

cold parrot
#

its a c library with bindings in many languages

spiral crest
#

oh

#

ill look into it

#

thanks

cold parrot
#

the repo i linked is the c# variation

spiral crest
cold parrot
spiral crest
#

it says commercial is allowed but then it says something about a notice

cold parrot
#

you generally have to include a notice about which libraries you use in any software you make that uses them

#

only stuff like MIT license is really transparent to the end-user

spiral crest
#

So just a little "this app uses tesseract" thing at startup?

cold parrot
#

usually you'd have a button somewhere that shows a list of them all

spiral crest
#

i could put it in the about then

#

thanks :)

cold parrot
#

for example in most apps you have something like this in the "about" panel

candid trench
#

Why am i getting this error?

public class PathFinder
{
    public List<Node> QueueFromSourceTile { get; private set; } = new List<Node>(new NodeComparer());

    public class Node
    {
        public Node(float _f, float _h, Node _parent)
        {
            f = _f;
            h = _h;
            g = f + h;
            parent = _parent;
        }
        public float g { get; private set; }
        public float f;
        public float h;

        public Tile tile;
        public Node parent;
    }

    class NodeComparer : IComparer<Node>
    {
        public int Compare(Node x, Node y)
        {
            return x.g.CompareTo(y.g); 
        }
    }
}
#

i have to cast explicitly like so new NodeComparer() as IEnumerable<Node>.

How do i get around that? 😮

cosmic rain
candid trench
#

really? well, my bad

#

can i use a hashset?

#

or any other container? xD

cosmic rain
#

Wdym? What are you even trying to do?

candid trench
#

trying to sort the queue by the value g in its members

#

at insertion

cosmic rain
#

Then use a sort on your queue or something. You're just trying to assign an empty list with a weird parameter.

candid trench
#

what i really want is a priority queue, but as someone else pointed out earlier, they're not implemented in the version of .net that unity uses

hollow hound
#

Wanted to ask about modular AI movement system.
I have behaviour where enemy moves towards the player.
I also have behaviour where enemy moves towards the player only to some distance, and then maintain this distance.
Also behaviour where enemy dashes on some condition.
I want flexible way to compose AI movement. For example, I want to create some way to create variations like [towardsPlayer + Dash] enemy, [towardsPlayer + maintainDistance + Dash] enemy, [maintainDistance + Dash].
My first Idea was to create movement decorators with ScriptableObjects, but there is some problems with this approach. For example, towardsPlayer triggers on collisions to check if its "arrived", so if I want to wrap it, I will need to redefine onCollision triggers in the whole wrap link.
Also I have some problems with passing dependencies. Components such as rigidBody and enemyTransform should be public to define them in Start() of movementController which doesn't seem right way to do.
Is there are ways to solve this problem, or maybe different approach?

sinful terrace
#

Hello, I'm not sure if this is a more begginer problem and I'm just stupid but can someone please tell me why this code doesnt work

if(PlayerCam.rotation.y > 0f && < 90f) {

    }
quartz folio
#

and rotation.y is not at all what you think it is

sinful terrace
#

oh

#

how do I get the y rotation values

quartz folio
#

.eulerAngles, .localEulerAngles depending on the space you want

sinful terrace
#

so I would use .eulerAngles.y ?

lyric wadi
#

yes

sinful terrace
#

i got the same error

lyric wadi
#

may be the && < 90 needs

hollow hound
sinful terrace
#

this was the error

sinful terrace
#

IT WORKS

lunar forum
#

So, I'm making a game over scene with a couple of buttons. I also have a script attached to a game object to contain the button functions, which I then attach to the buttons in the editor. But when I look for the methods that each button should use, I can't actually select a method from the script.

lunar forum
#

I tried doing that first and it didn't work, which tells me I even screwed that up somehow cause it worked just fine when I tried it this time.

#

No clue. But thanks!

compact spindle
#

Hey guys, my intellisense for Unity just blew out for VSCode and it hasn't come back for 2 days so I've been relying on Unity's error log...I have Ryder but idk how to use it yet as well as vscode--would Ryder be a better option?

orchid tree
#

So I am developing a 2d top down roguelike, obviously it has procedural dungeon generation. I made a mini map that displays the dungeon and your current room witch works perfectly as I intended. However my problem is because I didn't use a Canvas and instead used world space game objects with sprite renderers on them, the mini map appears on different position across different screen sizes. I was wondering if there is a solution to this where the map will always appear in the top right of your screen, or if I have to completely rewrite my code to use a canvas instead of a game object. Thanks

quartz folio
compact spindle
#

would that apply for every programming language? idk how many languages it supports

cold parrot
compact spindle
weak vapor
#

anyone know why array[^0] (to access from end) might not be working?
throwing outside range error

#

im sure the array is not empty

#

it's an array of non-value type calsses

#

it's kind of maddening TT

#

the caret makes the code so pretty

#

array.Length - 1 will have to suffice

somber nacelle
#

It's ^1 for the last index

left gale
#

I've never heard of that syntax at all.

rain minnow
#

It's new . . .

left gale
#

Is it a unity or a c sharp thing

weak vapor
somber nacelle
cinder monolith
#

how do i change the size of camera in c#

daring cove
#

How to do a suspension system for a car using Unity's builtin components?

I'm using spring joint, but the tire seems to be disconnected from the attached rigidbody and thus is getting dragged by the vehicle.

I want the suspension to act like a shock absorber. So it smoothens out any bumps and potholes and doesn't just move with the terrain.

flat mesa
#

where can I put meta data inside of Unity Gaming Services (eg base stats for enemy/characters)

candid trench
stable osprey
#

Some things I found are:

  1. You don't change queueSize in the methods you inout it.
  2. You don't actually use id.. this makes it single threaded, and even worse, does the operation in each of the 64 threads that are assigned as workers.. which is worst-case-scenario for compute shaders.
  3. You just output an int. That's not useful at all from the CPU.

Notes:

  • That's not a good way to use a compute shader.
  • You'd ideally want to make it multi-threaded and output something the C# part can use (e.g.: path to node).
  • It would help if you thought of Compute Shaders as modules that do certain stuff and return nice outputs for you to use in C# or Screen directly.
winged mortar
#

Implementing Bi-Directional A* in C#

vagrant sparrow
#

Anyone else have issues with Unity 2022.2.12-13 making your C# files read-only, so you cant save in Visual Studio ? I have to force a domain reload to fix the issue. Its happening constantly

granite nimbus
#

which is faster, GameObject.Find or GameObject.FindWithTag?

#

well I assume the second one is faster, but idk

dusk apex
#

They're both slow. Use whatever fits your bill.

#

The first relative to name. The second relative to tag.

tepid river
#

both shouldnt be used

#

its not just slow, its also unsafe.
if you use "find" it means you have no idea how many of these objects actually exist.
leading to all kind of edge cases. "exactly one found", "none found", "Multiple found" etc

granite nimbus
#

I know they're slow

wide fiber
#
 void Moving()
    {
        Vector3 movement = p_input.xAxis * transform.right + p_input.zAxis * transform.forward;
        movement *= speed;
        movement += new Vector3(0, rb.velocity.y, 0);
        rb.velocity = movement;
    }```

Hi sorry, i managed to create movement but how do i rotate with this input? 😅
feral wigeon
#

hello all... how can i check if 2 fields are equal??
I would like to ensure that when the user chooses a password he must also confirm it ... in this case I make the button interactive
I tried like this but I can't also because thinking about it, the 2 variables for the password are always emptyif I don't confirm them first...

if (confirmPassword == password)
{
ConfirmRegButton.interactable = true;

         ConfirmRegButton.onClick.AddListener(() =>
         {
             StartCoroutine(Main.Instance.Web.RegisterUser(UsernameRegInput.text, PasswordRegInput.text));
         });
     }
granite nimbus
#

other than using Find

dusk apex
granite nimbus
dusk apex
#

Specific tag (through the whole scene)

#

They've both got to check the scene objects.

lucid valley
dusk apex
lucid valley
#

I imagine Unity would keep track of objects with a tag in a dictionary or something for faster lookup

granite nimbus
dusk apex
lucid valley
#

sure, but not all objects will have tags

dusk apex
#

Pretty certain tag is explicitly in the inspector for every game object.

lucid valley
#

yeah, but it is optional

#

in general yeah, avoid any Find function

#

you could have your own manager to store specific objects under certain conditions too

#

or use static lists (though i'd avoid that, more hassle if you turn off domain reload)

dusk apex
lucid valley
#

either way, i still think FindWithTag is going to be quicker than Find

tepid river
#

i would have the object set itself as a reference to the static class, and through load order make sure object loads before the class

keen spruce
#

Can someone please tell me where I can find the Dynamic Batching settings in URP ?

vestal geode
keen spruce
#

If I have 60 moving cubes in scene with same material and SRP batching compatible can I get less than 60 batches with URP ?

vestal geode
keen spruce
#

Then Im stuck with one batch for each cube ?

vestal geode
#

"Stuck"?

winged mortar
#

The code din question also does not contain the problem you are having

keen spruce
#

I mean isnt there any way to decrease the draw calls ?

#

*stuck with a draw call per cube

worldly hull
#

this is more like a code design question

im currently using new input system, on player script i have all the events i needed, but i want to pack them well so my player script is less messy

public void OnReload(InputAction.CallbackContext context)
    {
        if (context.performed)
        {
            gunConfig.StartReload();
        }
    }```
something like this

now i have a total of 8 actions
worldly hull
#

do i leave these events on player, or move them away to those scripts?

vestal geode
worldly hull
#

im quite braindead now lol

keen spruce
#

Do you think SRP batching with 150 drawcalls will run well on weak mobile devices ?

vestal geode
keen spruce
frozen cedar
#

Hi,how do i make a bubbly oil liquid in unity

vestal geode
vestal geode
frozen cedar
keen spruce
#

Also, If I change the property of a material referenced in inspector has any differences than changing the properties through sharedMaterial ?

vestal geode
# frozen cedar oh no i mean the visual like boiling oil visual

There isn't really a one way to make something like that so you'd google for references and examples of how others have made similar effects, google for bubbling oil tutorial, if you find none such then you'd google for bubbling tutorial, oil tutorial and liquid tutorial and try to combine them
You'll probably need to make textures, shaders and particle effects

frozen cedar
vestal geode
vestal geode
stuck glacier
#

Can you SerializeField a class type?
For example, if I have a class names weapon with a few variables, and I type: [SerializeField] Weapon Axe;
Why don't the variables show in inspector?

hexed pecan
#

Weapon needs [Serializable]

#

And dont put it on the field but on the type declaration

stuck glacier
#

Ooh thanks!

#

"The type or name space "SerializableAttribute" could not be found"..?

wicked scroll
stuck glacier
#

How?

wicked scroll
stuck glacier
#

Okay I figured out the issue. Apparently I needed to say "[System.Serializable]", not just serializable

wicked scroll
#

your IDE will hunt those down for you

#

but it's useful to understand what's going on

plucky burrow
#

hey guys, ist this:

void Start()
{
  healthStat = new Stat(healthDefinition)
}

and this:

void Start()
{
  AddStat(healthStat, healthDefinition)
}

void AddStat(Stat _stat, StatDefinition _statDefinition)
{
  _stat = new Stat(_statDefinition);
}

not doing the same thing?

I want to make a copy of the stat and save it to a List later on, thats why I want to make a function for that.
First method works fine, second doesnt..

plucky burrow
#

a class

lucid valley
#

yeah, don't think you can just send a variable and reassign like that to the parameter

dusk apex
#

Consider out Stat stat and out healthStat

knotty sun
#

or just use

Stat AddStat(StatDefinition _statDefinition)
{
  return new Stat(_statDefinition);
}
plucky burrow
warm shadow
#

Okay I need help, I'm currently building a script that checks of all of the items in a Drag and Drop system is placed in the correct order or not. If they are it should play the correct sound effect, if it's wrong it should play the wrong sound effect. First I check if all the DropItems are filled, then I check if they are in the correct order: IsIDListInTheCorrctOrder(GetInFilledDragItemsID()) and from that play either correct or wrong audio. So the issue is that since it runs every frame, when its true or false, it keeps running, but I only want it to run once when the value change. How do I do this?
Here is the code:

void Update()
{
    if (IsAllDropItemsFilled() == true)
    {
        if (IsIDListInTheCorrctOrder(GetInFilledDragItemsID()))
        {
            CorrectAwnser();
        }
        else
        {
            WrongAwnser();
        }
    }
}
winged mortar
#

You can keep an extra boolean -> set it the first time the condition is true, and then check if its not true in the win condition itself

wicked scroll
warm shadow
#

I'll try it

warm shadow
swift falcon
#

Does anyone know how I can stop my character from getting stuck on walls? I tried a frictionless rigidbody but that just makes it possible to run up impossible angles.

hexed pecan
#

This is so you can run up slopes

coral kettle
#

can someone help me figure out how this works? a animation event with customevent (string). this is from an asset so I'm not sure what it's doing (in a different context, this would normally call the "Hit" method on any? or every? script that the animator is also attached to. I just dont know what it's doing here)

#

nvm, I found it. I thought it was a generic unity feature but it's not

mossy gust
#

Guys I’m trying to write a custom cutscene handler where there’s a typedef( or whatever you call it in c#) and a list of those typedefs, and there’s a timer, and I need to read the contents of the variables in the list to get the time that the cutscene happens

#

But idk how

#

Or better yet, the question is just:
How do I read variables from a list then check when a specific requirement is met with those variables

swift falcon
#

Hello, my goal is to build a generic entity spawning system based on triggering an event when an entity despawns that would call a handler defined in the spawner game object. I wrote the following interface:

public interface IDespawn : IEventSystemHandler 
{
    delegate void EntityDespawnDelegate(IDespawn despawn);
    event EntityDespawnDelegate entityDespawnEvent;
}

The idea is that a spawnable entity implements that interface. Here is my attempt at implementing the interface:

public class DummySpawnableEntity : MonoBehaviour, IDespawn
{
    public delegate void EntityDespawnDelegate(IDespawn despawn);
    public event EntityDespawnDelegate entityDespawnEvent;
    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            if(entityDespawnEvent != null){        
                entityDespawnEvent() ; 
            }
        }
    }
}

That won't work, the issue being:

Assets/Scripts/DummySpawnableEntity.cs(5,52): error CS0738: 'DummySpawnableEntity' does not implement interface member 'IDespawn.entityDespawnEvent'. 'DummySpawnableEntity.entityDespawnEvent' cannot implement 'IDespawn.entityDespawnEvent' because it does not have the matching return type of 'IDespawn.EntityDespawnDelegate'.

Implementing entityDespawnEvent does not make any sense right? What exactly is the return type of EntityDespawnDelegate?
Since I can't find any other similar approach on the internet, I take it it isn't a very good one.

limpid veldt
#

Hi there fellas i need to calculate the uvs for a quad. The texture the quad is using is a atlas of all of the tiles. I need to define a area when it calculates the uv with a index. The code bellow doesn't take this "area" in consideration. I need the parameter to be like this: IndexToUVs(int i, int topLeftCornerOfTheAreaInPixelsX, int topLeftCornerOfTheAreaInPixelsY, int areaSizePixelsX, areaSizePixelsY). Thank you for reading!

  public Vector2[] IndexToUVs(int i) {
        Vector2[] uvs = new Vector2[4];
        
        int atlasColumns = tileAtlas.width / (int)tileSize.x;
        float atlasWidth = tileAtlas.width;
        float atlasHeight = tileAtlas.height;
        float u = (i % atlasColumns) * tileSize.x / atlasWidth;
        float v = 1f - ((i / atlasColumns) * tileSize.y / atlasHeight) - tileSize.y / atlasHeight;

        uvs[0] = new Vector2(u, v);
        uvs[1] = new Vector2(u + tileSize.x / atlasWidth, v);
        uvs[2] = new Vector2(u, v + tileSize.y / atlasHeight);
        uvs[3] = new Vector2(u + tileSize.x / atlasWidth, v + tileSize.y / atlasHeight);

        return uvs;
    }
hearty perch
#

can someone tell my why i cant see "reset()" in button functions

leaden ice
hearty perch
#

OH

#

dint notice it

#

thanks

lavish mist
#

Hi everyone. Im trying to change the opacity of a group of images in an "animated" way, but I get error NullReferenceException: Object reference not set to an instance of an object Spawner.Update
My code:

public class Spawner : MonoBehaviour
{
    Image[] imagenAdvSpawn;
    Color color;
    float opacidad = 0;
    bool corrio = false;
    GameObject[] objetoImagenAdvSpawn;

    void Start()
    {
        color = GameObject.Find("Imagen Adv Sp").GetComponent<Image>().color;
        objetoImagenAdvSpawn = GameObject.FindGameObjectsWithTag("ImagenAdv Spawn");
        imagenAdvSpawn = new Image[objetoImagenAdvSpawn.Length];
        for ( int i = 0; i < objetoImagenAdvSpawn.Length; ++i )
        {
            imagenAdvSpawn[i] = objetoImagenAdvSpawn[i].GetComponent<Image>();
        }
    }

    void Update()
    {
        if(!corrio)
        {
            StartCoroutine(CambiarOpacidadImagenAdvSp(0f, 1f, 2f));
        }
        color.a = opacidad;
        for (int i = 0; i < imagenAdvSpawn.Length; ++i)
        {
            imagenAdvSpawn[i].color = color;
        }

        if(Input.GetKeyDown(KeyCode.T))
        {
            Debug.Log(objetoImagenAdvSpawn.Length);
        }
    }

    IEnumerator CambiarOpacidadImagenAdvSp(float opacidadIncilial, float opacidadObjetivo, float duracion)
    {
        corrio = true;
        float timeElapsed = 0f;

        while(timeElapsed < duracion)
        {
            opacidad = Mathf.Lerp(opacidadIncilial, opacidadObjetivo, timeElapsed / duracion);
            timeElapsed += Time.deltaTime;
            yield return null;
        }
        opacidad = 0.5f;
    }
}```
lucid valley
simple brook
#

Can y’all help I’m using unity recoder to get a video from a camera to a video file how do I set the camera it is set to? I’m using the movie sample

crude cairn
#

https://i.imgur.com/sVgdHwe.png
How would I access the TMP_Text of TextMeshPro inside my Stone.cs Script? I have over 50 Stone GameObjects, would I need to add the Score.cs Script to every single one of them or is there an easier way?

dim umbra
#

Anyone know what this warning means?

lucid valley
crude cairn
lucid valley
#

so you can access the static instance anywhere in code

#

do you know what that means?

lavish mist
crude cairn
#

yeah I have used singleton before but need to look it up.
Thanks

lucid valley
#

huh, but it should be set in Start

#

you 100% sure line 32 is for (int i = 0; i < imagenAdvSpawn.Length; ++i)

#

screenshot the error

lavish mist
lavish mist
lavish mist
serene lake
#

I am trying to get a network variable to be static, but it keeps giving me an error saying NetworkVariable is written to, but doesn't know its NetworkBehaviour yet. Are you modifying a NetworkVariable before the NetworkObject is spawned?

#

Does anyone know why this is happening

serene lake
#

Yes

#

Sorry I should have said that

#

I am making a tag game and I am storing a static variable on who the tagger is

#

And thats the error

lucid valley
#

tbh i'd be surprised if you could make a NetworkVariable static

serene lake
#

Do you know how I should do it then?

lucid valley
#

i donno, have a networked manager and store it there

serene lake
#

Alright

#

Thats what I was just working on

plain hatch
#

Looking for helpful devs for my new project

serene lake
#

It just gives me the error

lucid valley
#

the same error?

serene lake
#

Yeah

lucid valley
#

.... you've moved it to a manager

serene lake
#

Yup

lucid valley
#

don't make it static anymore

serene lake
#

And even when it was not there and not static it gave the error

serene lake
lucid valley
#

try reloading Unity

serene lake
soft hare
#

can some one help me with something https://hastebin.com/share/oxitapiget.java my if statement under declare war don't work and I asked chatgpt 15 times and all his answers were the same useless

serene lake
#

Also I reloaded

soft hare
#

yea i know but i dont know were else to ask

lucid valley
#

I'm sure theres a Java discord somewhere

soft hare
#

i sure dont know any

soft hare
#

sure

#

what is the project

tawny elkBOT
plain hatch
#

:v

#

Should've been told me lol

timber snow
#

I have a monobehaviour that interpolates it's position to a 'next position' every frame. When i move this monobehaviour in the editor, i need the 'Next Position' to change, instead of the transform position. Is there a way to override the behaviour of moving a game object in the editor

quaint gate
#

do unity compute shaders not support a byte type?

quaint gate
#

ah, so no

clear tiger
#

One message removed from a suspended account.

#

One message removed from a suspended account.

stray stratus
#

My VR game is freezing every 4 seconds. I am running standalone on the meta quest 2 using the Oculus XR plugin. I have tried opening the profiler and checking what was taking so many frames. The first thing was the EditorLoop, but I don't think that has anything to do with the game itself as I am sending the built apk to the headset.

I read somewhere that 3rd party plugins may freeze the program so I tried removing a couple. The most significant change happened when I tried removing the oculus XR plugin. This gave me much better fps, but obviously it stopped launching in VR.
None of my scripts seem to take much power and I have no idea what I should be looking for at this point. Any idea as to what might be causing this?

worldly hull
#

how do u guys apply recoil force on the character?
just like when u keep shooting, the character will keep looking upper and upper

#

my method is more like a bandaid cuz i really cant think of a better one

potent sleet
#

cinemachine noise

worldly hull
#

dayummmmmmm

#

do u know how i did it?

#
    private IEnumerator ApplyRecoil()
    {
        yield return new WaitForSeconds(gunConfig.recoilWindow);
        recoilX = 0;
        recoilY = 0;
    }```
i basically hard code out the cinemachine noise
potent sleet
#

I mean it's a way of many ways to do it sure

worldly hull
#
        //implement recoil
        if (IsAiming)
        {
            camConfig.recoilCamMove(recoilX * aimCompensation, recoilY * aimCompensation);
        }
        else
        {
            camConfig.recoilCamMove(recoilX, recoilY);
        }```
#

where camConfig is the camera control script on a cinemachine

gilded estuary
#

Ok, so I wanted to get some more opinions, for a debug menu, would it be wise to make it visually and then keep it in one separate scene and while in another scene, load it asynchronously and use it that way, or create the debug menu entirely in scripting like spawn in the canvas, buttons, their positions, etc. and make a gameObject, apply script to it and make it a prefab? I guess I was thinking of making two, one in a separate scene, and one during actual gameplay

lyric wadi
#

it doesn't matter magix you can create it and spawn it from a prefab or load a scene with it additively or do it in code it really doesn't matter

stray stratus
#

My VR game is freezing every 4 seconds. I am running standalone on the meta quest 2 using the Oculus XR plugin. I have tried opening the profiler and checking what was taking so many frames. The first thing was the EditorLoop, but I don't think that has anything to do with the game itself as I am sending the built apk to the headset.

I read somewhere that 3rd party plugins may freeze the program so I tried removing a couple. The most significant change happened when I tried removing the oculus XR plugin. This gave me much better fps, but obviously it stopped launching in VR.
None of my scripts seem to take much power and I have no idea what I should be looking for at this point. Any idea as to what might be causing this? (Repost because I really need help)

swift falcon
#

So i have this issue where i made the main menu play button and it just doesn't work,it's like it's not detecting my mouse

static matrix
#

mmmm.... Delegates

fresh cosmos
#

anyone knows why github dont always recognize changes in scriptable objects? if i have a bool in a scriptable object and check it, the changes in github dont update

static matrix
#

Bro who tf made it so raycasts collide with the casting object it is the most stupid bs ever

cold parrot
static matrix
#

Well surely the stack trace gets which script created the raycast, it cant be too hard to just say "Hey ignore a hit if the object contains the script that created the raycast" (Unless it is)

soft shard
static matrix
#

yeah, Ik its easy to workaround, but its still a little annoying

eager yacht
#

The physics settings have options for that...

static matrix
#

oh lol, yeah I need to look at settings more

#

Is it possible to make an emmisive material light up its surroundings?

simple brook
#

Can someone help with mp4 creation I wanna know how to pick a specific camera with unity recoder

crisp bronze
#

Hi, has anyone experienced this error when trying to Build?
An asset is marked with HideFlags.DontSave but is included in the build

candid trench
#

ok, super simple question.


class SomeClass {
  int i;
}

class SomeClassUser {

  SomeClass someClass = new SomeClass();

  public void ChangeSomeClass()
  {
    someClass = null; 
  }

}

If i call on ChangeSomeClass() on my SomeClassUser object.
Does the old SomeClass get destroyed ? or do i need to deallocate it manually in C# ?

wraith venture
candid trench
#

lovely

#

im coming from c++ so things are a bit different ive noticed

wraith venture
#

fair enough, garbage collector does a lot of the work for us in C#.

vernal compass
#

Any idea what I'm doing wrong here?

dusk apex
quartz folio
#

IDE is configured, they just need the correct object

#

(that function doesn't exist in the docs, so I'm not sure where they're getting the idea it exists from)

quartz folio
#

So why not use SplineUtility?

dusk apex
#

I wasn't sure. Some minor stuff were missing (reference count etc) and ide should have suggested that it wasn't valid - unless they ignored it and just simply had us try to fill in the gap.

quartz folio
#

If errors are underlined, the IDE is configured

vernal compass
#

Sorry I'm just very new to coding and never worked with Splines in unity, I'm really lost on what to do

quartz folio
#

The docs page you linked is for a function in SplineUtility

#

it's a static method

mint moat
#

I have a gun system which works by firing rounds of bullets at a time. Like there is a gun which fires 4 bullets per round, and a total of 5 rounds per reload. I am using coroutines for this. There is fire bullets coroutine which is responsible for actually firing the individual bullets, and then there is a round coroutine which is responsible to start rounds in case the primary fire is held down. Like if you hold the primary fire, I want the fire_rounds coroutine to start, which starts fire_bullet coroutine.

Code looks like this :

public void CalledWhenPrimaryFireIsPressedDown(InputAction.CallbackContext context){
  if (context.action.phase == InputActionPhase.Started)
  {
      Debug.Log("<color=green>Firing Rounds</color>");
      fireRoundsCoroutine = StartCoroutine(FireRounds());
  }
  else if (context.action.phase == InputActionPhase.Canceled)
  {
        Debug.Log("<color=red>Stopping Fire</color>");
        if (fireRoundsCoroutine != null){
            StopCoroutine(fireRoundsCoroutine);
            fireRoundsCoroutine = null;
        }
        else Debug.Log("Fire Rounds Coroutine is Null");
   }
}

private IEnumerator<WaitForSecondsRealtime> FireRounds()
    {
        int roundsFired = 0;

        while (roundsFired < maximumNumberOfRounds)
        {
            Debug.Log("<color=yellow>Round Started</color>");

            StartCoroutine(FireBullets());

            yield return timeBetweenRoundsWaiter; // cached WaitForSecondsRealtime; 

            roundsFired++;
        }
}

private IEnumerator<WaitForSecondsRealtime> FireBullets()
{
        int numberOfBulletsFired = 0;

        while (numberOfBulletsFired < numberOfFiresPerRound)
        {
            Debug.Log("Bullet Fired");

            yield return timeBetweenFiresWaiter;

            numberOfBulletsFired++;
        }
}
#

This works, a little... Like when I press the primary fire for the first time, it works perfectly, but when i press it again, a strange pattern appears.

#

It looks like two coroutines are starting at the same time

vernal compass
mint moat
# mint moat

configured for 4 bullets per round and 5 rounds per reload

#

I feel like I am not ending coroutines the correct way, when primary fire button is released.

dusk apex
#

Where does "Round Started" get print?

#

Ah, I see.. cs Debug.Log("<color=yellow>Round Started</color>");

mint moat
#

whoops updated the code, there was this another function but i removed it cz discord wont allow long msgs

#

I missed it initially mbmb

dusk apex
#

So are you wanting more than one instance of the coroutine "FireBullets" to operate?

#

If not, simply do not allow the starting of that coroutine till it's done.

mint moat
#

I just want the same pattern to continue, like if you see before the first Stopping Fire, Rounds start, and fire bullets. Once each round completes, another one starts, until the max number of rounds are done.

#

For some reason, when i press primary fire again, two rounds start at the same time

#

idk why is that happening

dusk apex
mint moat
#

At any time, one FireBullets coroutine should be active.

#

Which will be firing bullets at that time. Once that coroutine ends, another one starts because FireRounds is starting another one.

#

One thing is that, FireBullets always completes before another one is called

dusk apex
#

What if it's started again before finishing?

dusk apex
#

And timeBetweenRoundsWaiter was true. So a new round would have started.

mint moat
#

I have time values adjusted so that it never happens. Time between bullets is like 0.1, time between rounds is 1 sec

#

there are 4 bullets per round

#

0.4 sec in total for FireBullets to end

#

after 0.6s another one is started

mint moat
#
timeBetweenFiresWaiter = new WaitForSecondsRealtime(timeBetweenFires);
timeBetweenRoundsWaiter = new WaitForSecondsRealtime(timeBetweenRounds);``` so it cant be true
dusk apex
# mint moat ```cs timeBetweenFiresWaiter = new WaitForSecondsRealtime(timeBetweenFires); tim...

Sounds iffy. Maybe avoid firing bullets again until you've finished firing: ```cs
private Coroutine firingBullets;
private IEnumerator<WaitForSecondsRealtime> FireRounds()
{
int roundsFired = 0;
firingBullets = null;
var stillFiringBullets = new WaitUntil(() => firingBullets == null);
while (roundsFired < maximumNumberOfRounds)
{
Debug.Log("<color=yellow>Round Started</color>");

        firingBullets = StartCoroutine(FireBullets());

        yield return timeBetweenRoundsWaiter; // cached WaitForSecondsRealtime - Minimum wait time
        yield return stillFiringBullets;//Wait till done firing
        roundsFired++;
    }

}
private IEnumerator<WaitForSecondsRealtime> FireBullets()
{
int numberOfBulletsFired = 0;

    while (numberOfBulletsFired < numberOfFiresPerRound)
    {
        Debug.Log("Bullet Fired");

        yield return timeBetweenFiresWaiter;

        numberOfBulletsFired++;
    }
    firingBullets = null;

}```

pallid coral
quartz folio
#

Why is this IEnumerator<WaitForSecondsRealtime>? Does that work? Usually coroutines are not declared in a generic manner, and it's just IEnumerator

quartz folio
#

well, I would remove that so it's declared normally

quartz folio
# mint moat

You want System.Collections not System.Collections.Generic

pallid coral
dusk apex
pallid coral
#

Ohhhhhhhhhh

#

It was a grammar error

quartz folio
static matrix
#

Why am I getting this error?

From the line ChunkData.SpawnStuff(ChunkData.Structs[0]);
I get an out of index exception, despite the fact that 0 is in the index.

dusk apex
#

If you want proof beyond doubt, log the size. It should correlate with the error. Question would be, why was it of size zero.

static matrix
#

I did log the size, and it printed '2'

#

which is its size

#

should I stagger it?

dusk apex
mint moat
dusk apex
#

The yield time delay would be identical to what you originally had - plus maybe one frame for the done firing check.

mint moat
#

yeah, but my original code is starting two rounds at the same time, thats the issue

mint moat
dusk apex
#

There wasn't anything catching the possibility of a round finishing earlier than expected.

static matrix
mint moat
dusk apex
#

Single lines don't have much meaning.

#

I'm assuming you're checking at the very last minute before the error fires.

mint moat
dusk apex
#

If so, it would be zero as that's what the error states.

mint moat
#

look at the time between rounds

#

they dont start at the same time, but right after one another

#

which is also not desirable

#

What am I doing wrong that the same steps dont reoccur... The first time it works perfectly as intended

dusk apex
#

Not sure what you're wanting. Either your rounds can possibly overlap with faulty delays or not.

mint moat
dusk apex
#

There shouldn't be a difference between your original or and the I've edited relative to time.

#

Unless you're wanting to fire a new round before ending a firing a bullets.