#archived-code-general

1 messages · Page 264 of 1

green ice
#

they are not in conflict with what i am doing

#

is there a logic reason of why it happens?

naive swallow
#

Some of those errors might be unrelated to any of your code but a few of them definitely are

#

So take care of those first

upper pilot
#

What should I use to play multiple animations in specific order(in some cases multiple sprites will animate)?

#

It's important that next animation in queue waits until previous is finished

modern creek
upper pilot
#

No, I just want to queue animations

modern creek
#

Hm, I'm not an expert with unity animations but I thought linking the states was how to do it.. I can help if you want to implement it with DOTween, feel free to ping me

upper pilot
#

Idk if its worth it 😄

modern creek
#

Yeah, I mean, if you're already using it it's great but .. if you're just fine with unity animations and doing just fine there, then great. 🙂 I'm a terrible "animator" (like moving armatures, spine, etc) but I can manage my tweens pretty well

upper pilot
#

Maybe I explained wrong.
I dont need to make animations, I have 2d sprites.
I just need to play animatsions in sequence.

modern creek
#

Oh.. well.. I probably would look into a tweening library then.. DOTween is pretty widely used and makes chaining animations together reasonably easy

jolly plank
#

is it possible to use blend trees and layering together?
eg. i have a blend tree, i create a sync layer, to overwride the clips in the blend tree

modern creek
#

that's how I accomplished the above which has all kinds of things like shader animations, movement animations, squash and stretch, etc - and it needs ability to "fast forward" if the user moves before the animations are done

modern creek
#

yeah

upper pilot
#

Yep checking

#

uh I feel like learning this will take too long for my current needs, but I did use Tween in different engine.

modern creek
#

For sure, it's not a drop-in sort of solution but.. once you sorta have your head around it, if you're animating things in 2d games (or any, really) then you'll wonder how you did it without a tweening library

upper pilot
#

Yeah I bet

modern creek
#

How are you animating things now? Like, doing something like "start animation", setting a flag, and moving it manually in an update()?

upper pilot
#

I havent started yet, but sprite renderer/animator then I do something like .Animation.Play("Run"); From what I can remember.

modern creek
#

oh, ok, so that is an animation (like, "unity animation" proper)

upper pilot
#

Yeah, my goal is relatively simple

modern creek
#

Tweening is more for things that aren't "unity animations" in the same way.. i think animations can do everything tweening libraries can for the most part (maybe more?) but the tweening libraries tend to handling the animations through code

upper pilot
#
List<Animation> animation = new();
animation.Add(new Animation(player_1, "Run"))
animation.Add(new Animation(player_2, "Jump"))

This would play both at the same time since they are in the same queue list.

#

This is pseudo code

#

The idea is that once both of them are finished, we move to the next queued list

#

But I am still not sure if thats the best way, I will have to figure it out 😄

modern creek
#

Yeah, so.. you can do this (arguably easier?) with a tweening library, but basically what you want to explore is a callback for an animation being completed, and then putting the animations into a Queue<Animation> (not a list) and popping the next one off the queue if there's any in there

upper pilot
#

Queue<Animation> is part of dot tween?

modern creek
#

animations have animation events - you'll want to add an event to the end of the animation that calls some code and tells it its done

#

no Queue<T> is a C# data structure (just like list)

upper pilot
#

yeah that makes sense

#

oh I didnt even know

modern creek
#

but list is more for things that you need to "do all the things to everything in the list" where queue is "put these things in order and then take them out of the queue when they're .. called on".. just like the english interpretation of the word.. you get in line, you wait your turn, and when you're at the front you do your thing (and leave the line)

#

so you'd have a queue of animations.. add to the queue (as many times as you want), and when each animation is done with "itself" then it tells the script to start the next animation (with a callback / "animation event"): which would see if anything is waiting in the queue, take it out of the queue, and start it

upper pilot
#

yeah, but in some cases I have to start multiple animations in same queue

#

Also I am confused with the docs

#
        Console.WriteLine("\nDequeuing '{0}'", numbers.Dequeue());
        Console.WriteLine("Peek at next item to dequeue: {0}",
            numbers.Peek());
        Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue());
#
Dequeuing 'one'
Peek at next item to dequeue: two
Dequeuing 'two'
modern creek
#

yeah, so.. starting mutiple things at the same time is where this approach will start to fall apart a bit

upper pilot
#

Doesnt Dequeue remove "one" from a list? so Peek should return "three"?

charred robin
#

Is there a way I can make unity compile in the background instead of waiting until it is focused?

modern creek
#

dequeue takes the frontmost item off the list, but peek takes the frontmost item but leaves it in the queue

knotty sun
upper pilot
#
The object that is removed from the beginning of the Queue<T>.
modern creek
#

yeah, dequeue and peek are different things

modern creek
#

"dequeue" = get the front thing and remove it
"peek" = get the front thing and leave it

knotty sun
#

yes, so
Dequeue - one
Peek - two
Dequeue - two

upper pilot
#

But peek is supposed to check next element?

knotty sun
#

it is two is after one

upper pilot
#

If you dequeue "one" then you are left with "two", "three" right?

modern creek
#

peek doesn't look at the 2nd item in the list

#

after you dequeue your queue is : 2-3-4-5, so peek gives you 2

upper pilot
#
The Peek method is used to look at the next item in the queue
modern creek
#
numbers.Enqueue("one"); // one
numbers.Enqueue("two"); // one-two
numbers.Enqueue("three"); // one-two-three

string s = numbers.Dequeue(); // s = one, queue = two-three
string s = numbers.Peek(); // s = two, queue is still two-three
upper pilot
#

maybe by "next" it means first

#

or "current"

#

there is my confusion probably 😄

knotty sun
#

in a Queue next is always first

upper pilot
#

yeah thats confusing, but I got it now

modern creek
#

"next" doesn't mean 2nd, it means the next item you'd get off the queue

upper pilot
#

Make sense

modern creek
#

there's almost never a reason (in programming) to be getting the 2nd item as a normal operation.. typically with data structures (list, queue, stack, dictionary, hashmap - which you should learn, btw - there's a couple methods that are the 99% most common uses)

upper pilot
#

What are use cases for stack, hashmap in game dev?

#

I never saw those in any tutorial I've ever watched

modern creek
#

stack: open dialogs on top of each other

#

hashmap = a zillion things, can't even begin to describe 🙂

upper pilot
#

Do you use hashmap in your projects?

modern creek
#
HashMap<PlayerFlags> playerFlags = new(); // where player flags is an enum of special things, like, maybe "completed tutorial" or "vip player"

if (!playerFlags.Contains(PlayerFlags.CompletedTutorial)) { ... show tutorial ... }
knotty sun
#

Stack is very useful if, say you want an Undo function, stack will save your functions and return them in reverse order

modern creek
#

I use hashmap every day, everywhere

upper pilot
modern creek
#

because lists are not optimized for searching

upper pilot
#

Like reverse all changes done by that function?

knotty sun
#

Stack is a FILO queue, First in Last Out

modern creek
#

there's some technical details you don't really need to know but .. if you want to find out if something is in a list you have to check every item in the list.. if you want to see if an item is in a hashmap, the system is very fast at doing so because when it put it INTO the hashmap it gave it some special sauce to find it quickly

upper pilot
#

So should I use hashmaps instead of Lists? If its faster?

modern creek
#

stack operations:

Do thing A (stack is "A")
Do thing B (stack is "A, B")
Do thing C (stack is "A, B, C")

Undo - get the top thing from the stack, ie, C: stack is "A, B"

upper pilot
#

So Stack wont work for my needs right? Since I need the opposite order I guess

modern creek
#

hashmaps are terrible if you need to do everything to every item, that's what lists are for, but they're very good if you need to do see if something exists in your set of things

#

you need queues

upper pilot
#

Alright, I can have Queue<AnimationQueue> basically

modern creek
#

as long as we're chatting about collection data structures, you should also learn about dictionaries - dictionaries are for "get a specific item by a key" things

knotty sun
#

btw Since .Net 4 Dictionarys are faster then HashMaps

upper pilot
#
public class AnimationQueue
{
  List<Animation> list = new();
}
#

yeah I use dictionaries + lists mostly

modern creek
#

well, as I mentioned before your Queue<Animation> will break down a little bit for simultaneous animations, or anything complicated.. i'd honestly look into DOTween since you can carefully compose your animations in any number of ways.. timed.. chained.. waiting for user input, etc

upper pilot
#

But if I make AnimationQueue return when all animations are finished, it wont break right?

#

Tbh I am still not sure if I need Queue since I can do the same thing with List hmm

modern creek
#

yeah, i mean, there's nothing wrong with using a list (instead of a queue) if you're not comfortable with it, but it's sorta .. not the proper structure to use

upper pilot
#

I am so used to List and Dictionary that anything else seems useless haha

#

Got it

knotty sun
#

Then you need to learn, use the right tool for the job

modern creek
#

you could also just use arrays manually if you wanted, like

for (int i = 0; i < list.length; i++) list[i].StartAnimation();

or whatever, but those approaches are a little error prone

#

(ie, off by one errors)

upper pilot
#

I wouldnt mind discussing it if you have time today or tomorrow.
But I understand its time consuming to teach someone.

I will look into those data structures you mentioned and see if I can find some examples for game dev.

hard viper
#

Queues and Stacks are useful when you really need to denote that a specific object is supposed to be used in a certain way.

upper pilot
#

I didnt know Queue exist until today

hard viper
modern creek
#

much easier to read, less error prone to just do something like

foreach (Animation animation in allAnimations) animation.Play();
hard viper
#

HashSet is another common one. A HashSet is basically a dictionary without values.

modern creek
#

scroll up a page @hard viper 😉

knotty sun
upper pilot
#

I found this

#

Which one of these I should learn?

knotty sun
#

All of them

hard viper
#

wtf is a hashmap

upper pilot
#

But which are priority? I cant imagine myself using red-black tree

#

It sounds like black magic

hard viper
#

You don’t need trees and linked lists until you are deeper in

upper pilot
#

Hash Table is same as HashSet or they just didnt include it on that list?

modern creek
#

@upper pilot Yeah you can use a list instead of a queue but it just means you'll be writing more code.. like:

List<Thing> allThings = new();
allThings.Add(newThing); // x 100
Thing lastThing = allThings[allThings.Count-1]; // this is ugly imho
Thing lastThing = allThings.Last(); // this has to "go through" the entire list to get to the last thing, potentially
allThings.Remove(allThings.Count-1);

Queue<Thing> allThings = new();
allThings.Add(newThing); // x 100
Thing lastThing = allThings.Dequeue(); // Done!
hard viper
#

a HashSet uses a hash table just to know if something is in the data structure or not.

fervent furnace
#

hashset: no value
hashtable: key with value, and they are the same thing..

hard viper
#

a Dictionary uses a hash table to go find the value for the key

modern creek
#

i may have gotten those list methods wrong tbh - maybe it's RemoveAt()? I dunno, even, and I'm proud I don't - you shouldn't really do it. 🙂

hard viper
#

the only difference between a dictionary and hashset is that a dictionary stores values, and hashsets don’t

upper pilot
# knotty sun bet?

I would be really surprised if I start using black magic, it feels weird discovering those things 😄

hard viper
modern creek
#

eh, i don't use red/black trees and i've been developing for 25 years

#

i haven't needed to do anything hardcore enough that requires them

upper pilot
#

Nice, so there is a limit to how far you should go with game dev 😄

fringe ridge
hard viper
#

Stacks and Queues are more useful in the middle of an algorithm

modern creek
#

i mean you can always do things better-er but sometimes being pragmatic, deadlines, bank accounts etc require you to just "get it done"

#

and also you may not need to optimize things so whatever is easier to understand and implement is "better" in that capacity

upper pilot
fervent furnace
#

once you know how to code avl tree then you know how to code indexable tree and dynamic "segment tree"
btw apart from leetcode, havent used any sorted set

modern creek
#

you definitely should have at least list/hashmap/queue/stack/dictionary in your repetoire imho

hard viper
#

people will go insane with trees, graphs, linked lists… if you have a small amount of simple data, a list will usually cut out the hassle

hard viper
upper pilot
#

Any reason you didnt include Array?

modern creek
#

yes

hard viper
#

do include array

modern creek
#

off-by-1 errors are notoriously bad for the world imho

hard viper
#

arrays are useful.

upper pilot
#

Array is first data structure learned in JS, but List seems to be just better idk

modern creek
#

I use 0 arrays in my codebase

west lotus
#

Array is best data structure

fervent furnace
#

js array is dynamic

upper pilot
#

You can loop through List same as through array

modern creek
#

take arrays and chuck 'em into the sun imho!

hard viper
#

array is also the base used for most data structures

fervent furnace
#

it is c# list

hard viper
#

arrays are good. very simple tbh

modern creek
#

the second one imho contains hard-to-see bugs

hard viper
untold hemlock
#

Lists and Arrays.

modern creek
hard viper
#

it’s literally the same thing

upper pilot
#

Exactly, I like foreach more and more and if I really really need index, I can use 2nd option or just var index

modern creek
#

it defeats my completely arbitrary point 😉

upper pilot
#

haha

hard viper
#

arrays are good, and arguing otherwise is asenine

upper pilot
#

When do you use Array vs List?

hard viper
#

they are faster than lists, and better when the conditions for them are good

modern creek
#

and yes you can pretty much use Array[] T the same ways as List<T> but.. personally I just like to pretend index based accessors are left in the 90s

untold hemlock
hard viper
#

there are other factors, but that is the simple #1 reason

upper pilot
#

Cant you change array size later anyway or is there a way to prevent that?

fervent furnace
#

list is wrapper of array (though everything is wrapper of array except treeset iirc)

hard viper
#

you have to make a brand new array

#

all the data structures use arrays

upper pilot
#

I have a lot of Lists that dont change their size 😄

hard viper
#

a List holds an array, where if it doesn’t have enough space, it makes a brand new array, and copies everything over

untold hemlock
# upper pilot When do you use Array vs List?

I use Lists when I want to add or remove some stuff to it (e.g.) a list of props to destroy. I use arrays when I use something like GetComponents or I have something that needs it.

upper pilot
#

Makes sense

hard viper
#

if you want to use .Add or .Remove over time, do not use an array

#

for arrays to be really good, you need to know the exact size when you make it, and stick to it

#

otherwise you might as well have made a list

#

Arrays are simple structures

#

they are also way faster than anything else, given the use case is correct

upper pilot
#

I see, I do use Add/Remove quite a bit, but there are cases where I have a predefined List, but even then the size can change.
I.e. my class can have List of 3 elements, but different instance of that class will have List of 4 elements.
In both cases the list doesnt change its size within that instance.
Does that mean I should use Array?

hard viper
#

i would

upper pilot
#

That previous image wasnt for C# apparently lol

#

LinkedList, SortedDictionary, SortedList, SortedSet are there, should I care about any of these atm?

fervent furnace
#

sortedlist is useless iirc

latent latch
#

Hashset

hard viper
#

that’s what I recall as well

#

because sorred list has overhead that does not scale well

upper pilot
#

Why are all of those data structure lists missing Array lol

hard viper
#

because it’s obvious

#

list and array have the same scaling

west lotus
#

Im trying to think if a rhyme like “hexagon is the bestagin” for array but Im coming up flat

hard viper
#

sorted list is just bad

latent latch
#

Every c# datastruct has some sort of iterator usually

hard viper
#

for sortedlist to be good, the implementation would need to be a linked list, with binary search

upper pilot
#

LinkedList has any game dev use?

fervent furnace
#

useless

west lotus
#

Thats harsh Im sure there is a use

hard viper
#

not really useful tbh

upper pilot
#

There is some sort of structure where you connect multiple elements with Next,Previous

#

Anyone remember what its called?

hard viper
#

that is a linekd list

upper pilot
#

oh

west lotus
#

Thats a linked list

fervent furnace
#

but you need to know it since it is used in tree/graph and open hashtable and skiplist

upper pilot
#

Does it have any uses for Dialog system maybe?

#
tree/graph and open hashtable and skiplist

new words again haha

hard viper
#

linked lists don’t let you skip to a specific index quickly. You need to traverse in time of O(n)

upper pilot
#

I really know nothing -_-

hard viper
#

i would represent a dialog system as a directed graph

west lotus
#

Its a really smart tree

upper pilot
#
- tree/graph and open hashtable and skiplist
- Directed Graph
Data structures C#:
- Array/List/hashmap/queue/stack/dictionary
- Array → If size of array doesnt change
- List → If size of List DOES change

Am I missing anything?

#

I bet I am, but dont overwork me

hard viper
upper pilot
#

yeah its outside of data structure list, but I added it as something to research

#

Should I add anything else to this list?

latent latch
#

for dialogue you usually want like one of those database trees

#

segmented set or something

hard viper
#

This full course provides a complete introduction to Graph Theory algorithms in computer science. Knowledge of how to create and design excellent algorithms is an essential skill required in becoming a great programmer.

You will learn how many important algorithms work. The algorithms are accompanied by working source code in Java to solidify y...

▶ Play video
latent latch
#

because you may have dialogue that meets up eventually

hard viper
#

This is a 6 hr lecture compilation about graph theory

#

you should be at least familiar with the basics in the first 15 min or so

west lotus
upper pilot
#

Alright, thanks

upper pilot
upper pilot
#

I usually do =null to avoid issues

#

Since my Lists tend to contain class instances

#

List<Character>

hard viper
#

new List<int>(5) gives a list with capacity 5, and no entries filled in

upper pilot
#

I cant really create fake/empty Character class right?

#

oh

hard viper
#

but if you knew you’d need 5 entries, you might want to ask if you should use an array instead

upper pilot
#

So List<int>(5) returns null for each element?

hard viper
#

the list has a count of 0

upper pilot
#

or 0 in case of int

hard viper
#

but the array it holds has size 5

upper pilot
#

Which is a problem

hard viper
#

no

#

capacity is just telling the list to get ready its internal array to hold that many entries

upper pilot
#

Yeah I might need Array in some cases, I just use what I know because its convenient, but I will do research to see what other data structures are useful for what I do.

#

oh

hard viper
#

capacity. not count

upper pilot
#

Is it necessary for small Lists?

#

Or just a good practice

hard viper
#

(new List<int>(5)).Count gives 0

latent latch
hard viper
#

(new List<int>(5))[3] gives an error, because index is out of bounds

upper pilot
#

Got it, that makes sense then

hard viper
#

but then the list doesn’t need to make a brand new copy and move over the array until you try to put a 6th thing in it

upper pilot
#

What if I create List<int>(1000) but only use 20 slots?

#

Should I aim to create a list with maximum expected elements?

#

so if I create array with (5) elements that array will actually hold some value right?

hard viper
upper pilot
#

Since Array doesnt have some secondary Array to store data like a List does?

hard viper
#

you should not over-allocate memory like that

latent latch
#

Usually object pooling and stuff you do want to consider a bunch more indices

quaint rock
hard viper
#

an array is basically a pointer, which also knows how far it is allowed to go

latent latch
#

or make it dynamically grow if you pass a point

quaint rock
#

the list can reallocate and expand on its own, but if you know the final size you can allocate it up front, and avoid the reallocation and copy when capacity is breached

hard viper
#

you should never overallocate a ton more memory than you need

#

that is really bad practice

latent latch
#

eh, usually in a c++ environment it's suggested

hard viper
#

allocating memory is like the slowest single thing you can do

quaint rock
#

its never suggested to overallocate

#

its jsut a good idea to pre allocate at times

hard viper
#

that’s not ok

latent latch
#

upfront initialization is always better than expanding out your data structs

#

mem is cheap

quaint rock
hard viper
#

i never said you suggested to overallocate

quaint rock
#

like if i know it will reach 20, yeah i will make it with that capacity

upper pilot
#

So its fine to allocate up to a potential maximum

#

Even if I dont reach it(but I might)

#

Its more about how often it happens right?

latent latch
#

Ideally for your object pools you should be checking at a threshold to expand it dynamically instead all at once.

quaint rock
#

it depends on a few factors but yes

upper pilot
#

Whats an object pools?

quaint rock
#

there is a high cost to creating and destroying objects

latent latch
#

For things like particles, needing an extra 100 capacity in one frame when your pool only has 50 available is one of those scenarios you want to avoid

quaint rock
#

if you need the same object alot, object pool is a way to ask for a pre existing one that is not currently in use

upper pilot
quaint rock
#

some grow it as needed then reuse what has been created

#

some make a bunch upfront

latent latch
#

you don't want to be instantiating 100 objects in a single update, so you having those objects ready beforehand will remove a lot of that runtime overheard

upper pilot
#

Makes sense

latent latch
#

and one of the problems you want to tackle is that you never run into a scenario where you don't have the capacity to support a request for an amount of particles over your capacity

upper pilot
#

Right so if you expect maximum request to be 50, you should always make sure to have 50 empty slots

hard viper
#

no

#

if you expect the typical request to be 50, then set to 50

upper pilot
#

How do you even expand on a List capacity at runtime?

hard viper
#

List automatically does it

upper pilot
#

List<int>(50)

#

How do you go from 50 to 100?

jade vault
#

Anyone familiar with tilemap perlin noise generation?

upper pilot
#

Without making a new List

quaint rock
#

list will automatcally rellocate at a larger size when you exceed capacity

hard viper
#

whenever you Add to a list, it grabs more space if you don’t have it

quaint rock
#

generally it doubles in size when that happens, but what it does depends on the implementation

hard viper
#

usually it is double

upper pilot
#

I understand, but that point was to prevent allocating 50 elements at once

#

oh it doubles

#

makes sense

latent latch
#

Some games will actually render up to a limit for particles and after that the'll just be invisible. That's one way to tackle them, but that's more of a total amount of things a computer can render problem lol

quaint rock
#

generally it does, it really depends on implementation

hard viper
#

default capacity is 4.
If you add up to 50, then list will allocate to 4, allocate 8 and copy over, allocate 16 then copy over, allocate 32 then copy over, allocate 64 then copy over

west lotus
#

My personal philosophy is to not make object pools grow, instead they all use a circular buffer and thats that, idk if the oldest decal or particle suddenly pops out of existence

quaint rock
#

its all a balancing of not allocating often during runtime, but also not just wasting memory for a what if situation that may not even happen for most game play sessions

#

also yeah for particles, i generally hard limit things

upper pilot
#

I see that does make sense, I will keep that in mind when I work on one of my games with a lot of bullets 😄

quaint rock
#

wil jsut grab the oldest live one and use it, if the pool is empty

hard viper
#

people have done benchmarking. If you initialize with too much capacity, it is generally slower than just not specifying and letting the computer handle it

ancient magnet
#

Hey, I'm trynna use the closest line renderer for this script, but I can't figure out how

west lotus
#

!code

tawny elkBOT
ancient magnet
#

Hey, I'm trynna use the closest line renderer for this script, but I can't figure out how ⬆️

latent latch
#

im not seeing any line renderers

knotty sun
#

yep, not a single LineRenderer in that script

vagrant blade
#

Inb4 "well I got it from chatgpt"

ancient magnet
knotty sun
ancient magnet
knotty sun
#

DO NOT

fervent coyote
#

Okay, so I'm using

AudioSourceObj.volume = 0.01f, and even through debugging proving it is set to 0.01, in the inspector it's one!
But when I set it to 0, it will actually be 0. So it IS changing it!! but it won't change it to a decimal in the code!

Can someone please help me figure out why is is reverting to one?

fervent coyote
#
    {
        if (clip == null)
        {
            return null;
        }
        //Create the gameobject sound
        GameObject _sfxObj = new GameObject();
        _sfxObj.transform.position = position;
        _sfxObj.name = "SFX." + clip.name;
        AudioSource _sfx = _sfxObj.AddComponent<AudioSource>();
        _sfx.Stop();
        //Define AudioSource parameters
        _sfx.clip = clip;
        _sfx.dopplerLevel = 0;
        _sfx.volume = handler.prefs.PlayerPrefs_GetSFX();
        _sfx.minDistance = 5;
        _sfx.maxDistance = 200;
        _sfx.spatialBlend = 1;
        //Add a random pitch
        if (clip.length < 0.75f)
        {
            _sfx.pitch += Random.Range(-0.10f, 0.10f);
        }
        Entity_DestructionTimer _dest = _sfxObj.AddComponent<Entity_DestructionTimer>();
        _dest.timer = clip.length;
        switch (origin != null)
        {
            case true:
                _dest.origin = origin;
                break;
        }
        _sfx.Play();
        return _sfxObj;
    }```
#

Here is the whole of it

#

handler.prefs.PlayerPrefs_GetSFX() returns 0.05f

knotty sun
#

you do know that code will only work once, right?

fervent coyote
#

Wait what?

#

Why?

knotty sun
#

AddComponent

simple egret
#

switch (origin != null) { case true: }?????

#

If statement: Am I a joke to you?

fervent coyote
#

No

fervent coyote
hard viper
#

you add a component whenever this runs

knotty sun
#

because the AddComponent fails so the rest of the code does not execute

fervent coyote
#

But, it plays, and the other parameters set correctly as well

hard viper
#

imo, you should separate creating the SFX component, and playing it

knotty sun
#

doubt

#

GetComponent first, if it returns null AddComponent, not the best way to do it but, meh

hard viper
#

if (currentSFXComponent == null) currentSFXComponent = CreateSFXComponent();
currentSFXComponent.Play();

west lotus
fervent coyote
#
        _sfx.transform.position = position;
        _sfx.name = "SFX." + clip.name;``` I changed this
knotty sun
#

becaise you can only have one AudioSource on a GameObject

hard viper
#

that’s not true

west lotus
#

Thats not true

#

Besides he makes a brand new go at the start

#

How would it have an audiosource?

knotty sun
hard viper
#

anyway, you should just have a CreateSFXComponent() function that makes a new component and returns a ref to it.

#

then have a separate method for playing it

#

do not overload responsibilities

west lotus
#

Thats completely irrelevant to his problem

fervent coyote
#

My problem is it seems like volume is either set to 0 or 1 in the code

knotty sun
#

then if the volume is not correct is must be
_sfx.volume = handler.prefs.PlayerPrefs_GetSFX();

fervent coyote
#

Everything else works expect for that

lean sail
#

Add debugs between to see what values are, but are you sure that nothing else ever modifies this object?

fervent coyote
#
{
    return 0.05f;
    //return Prefs.Audio_Effects * 0.01f;
}```

Here is that function
hard viper
#

did you debug log to see what the volume is at the end of the code

#

i would honestly debug.log in update, to just see if the volume is set correctly

#

or is changing

fervent coyote
#

Okay, haha

#

I figured out the issue

#

It turns out I'm an insane lunatic

#

You know the destruction timer script?

#

Well, apparently, this is in the start function

#
    {
        handler = Handler_Gamehandler.Game_GetGamehandler();
        source = GetComponent<AudioSource>();
        if (source != null) 
        {
            source.volume = handler.prefs.Prefs.Audio_Effects;
        }
    }```
hard viper
fervent coyote
#

I don't even know what that's there

#

I'm sorry

hard viper
#

as a rule of thumb, I try to keep Start, Awake, etc as simple as possible

#

but just writing separate methods

heady iris
#

how about the secret start method

hard viper
#

don’t tell him about that

heady iris
#

😇

#

I've been moving away from using Start and Awake at all in many places in game

fervent coyote
#

You mean Awake?

hard viper
#

Awake is wonderful imo. Because it gets executed the moment the script gets made.

heady iris
hard viper
#

Start is not so good imo, because it might wait until next frame, and jank up

heady iris
#

Yeah, I often find that I'm using Start just for that one frame wait

#

and that means I'm probably just hiding a problem

#

...as I just did this morning!

#

my game was spawning a spectator entity before another part of the game was ready for anything to be spawned

#

I punted it into Start. I'm going to make the order explicit later.

hard viper
#

idk if i shared this, but my computer was fried last week. Changing now to a windows machine

heady iris
#

I want to make it so that i can load a scene and wait around for a while before kicking off the game

#

without anything "jumping the gun" and erroring out because it tried to start too soon

hard viper
#

the silver lining is that VS has a lot more shit for windows than mac

heady iris
#

oh yeah, Visual Studio on Windows is a while other thing

hard viper
#

at least the super core features are there

#

smart renaming, smart find references for variables. dropdown list of accessible fields and methods. That shit is goated

#

straight up crack

#

never had an IDE do that for me before

#

my standards for an IDE in college were “I just need the colors of the letters to be right.”

#

and auto indent for python

somber nacelle
# heady iris how about the secret start method

there's a secret start method? 🤔
i know there's a secret awake method __internalAwake. Or were you just referring to like an init method or something that is explicitly called by user code?

heady iris
#

Ah, that's what I was thinking of

#

doubleplus secret

#

🤫

hard viper
#

++secret

west lotus
heady iris
#

that's called the Yellow Pages

west lotus
#

Hmmm and here I was thinking you are too young to know what yellow pages even are

halcyon estuary
#

How to i get access to the TextMeshPro Component in a childobject as a instant?void ShowPotionBoost(string text){ if (FloatingTextPrefab){ GameObject prefab = Instantiate(FloatingTextPrefab, transform.position, Quaternion.identity); prefab.GetComponentInChildren<TextMeshPro>().text = text; } }

somber nacelle
#

use TMP_Text instead of TextMeshPro. i'd bet you are not using the 3d text object (TextMeshPro) and are probably using the UI one (TextMeshProUGUI). They both inherit from TMP_Text though so you can get either using that type

halcyon estuary
#

yep that works. Thank you:)

unborn flame
naive swallow
unborn flame
naive swallow
unborn flame
naive swallow
unborn flame
naive swallow
#

there's not really anything you can do with that

unborn flame
#

i am refencing the waitingmanager in the npc script so that when the npcs are assgined to a room they are removed from the npc waiting list

naive swallow
wide dock
#

You cannot reference a component present in a scene within a prefab

naive swallow
naive swallow
# unborn flame no

So, show the inspector of the object you're drying to set your reference on

naive swallow
unborn flame
#

i just did

naive swallow
#

Prefabs cannot reference objects in scene

wide dock
naive swallow
unborn flame
naive swallow
#

A prefab is a file. It doesn't run any code

#

The fact that this is in code means it's running on an instance

unborn flame
#

i dont know what it is but it works so im happy

knotty sun
unborn flame
knotty sun
#

why am I not surprised

unborn flame
#

it works

knotty sun
#

not the point, you still have no idea whatsoever what youi are doing

west lotus
#

Ensure that there is a manager in the scene just logs an error. Never change chatgpt

wide dock
#

I'm honestly baffled by the amount of people using GPT as a "reliable" source of help in programming instead of actually trying to research, learn and understand what they're doing

west lotus
#

Its almost like people are lazy and want everything to come made just for them

lime gazelle
#

if i have a question which includes code but is around the audioSource do i ask it here or in #🔊┃audio

unborn flame
#

I understand to some extent, this was the first time i ran into a problem like this so i asked it now i know for the future

wide dock
# unborn flame

Ignoring the fact that using any Find method is usually slow and unnecessary, it will work, yes

#

But keep in mind that Find will search through the whole scene hierarchy

#

For every single NPC spawned

quartz folio
#

the text autocomplete robot has now showed you the worst possible way to reference an object

west lotus
quartz folio
#

well done text autocomplete robot, for giving bad advice without proper context once again

knotty sun
#

I prefer the term Stochastic Parrot and who in his right mind would take any advice, let alone coding advice, from a Parrot?

scarlet viper
#

it suddenly loses reference or something

quartz folio
#

It requires a lot of maintanance to get that working consistently

#

I don't rely on it at all

#

If you're not making everything serializable or recoverable then it will just break

#

maintaining for fast playmode switch* is way easier
* read all the pages, and sub-pages if you're interested in using it

leaden ice
hallow garnet
#

hi, I made an undo/redo system, I have an abstract class Action with Undo and Redo methods, and for now I have a MovedAction subclass which has a constructor to assign some info like old and new position, the object, and it's undo and redo implementations.
I save the actions on two lists, actionsToUndo and actionsToRedo.

It works completely fine, but I wonder if there is another way to go about it or if there's something I could improve, since I'm trying to learn all these patterns and designs and all that sort of stuff, this is my first time using abstract classes

rigid island
wicked scroll
lime gazelle
#

is there any specific channel related to videos? (video player)

#

anyway what happens if i set the videoPlayer.time to something greater than lenght of the vid its playing?

hard viper
kind pivot
#

hi, I was wondering if I load an assetbundle in one scene will it still be loaded if I transition to another scene? or would I have to load the bundle again?

cosmic rain
kind pivot
#

alright

frosty snow
#

wat o.o

Unity.Burst.BurstCompiler.CompileFunctionPointer

#

can we call this from a build ?

frosty snow
#

welp Unity.Burst.BurstCompiler.CompileFunctionPointer seems to hang

#

even though it sais that burst is enabled

cosmic rain
rancid flower
#

what is the default .unitypackage file opener?

#

cuz my shit broke one day and I accidently set it to the shortcut for the unity editor and broke it, cuz im silly.

leaden ice
rancid flower
leaden ice
#

I don't think you could ever double click to import from Windows AFAIK but not sure

#

I usually have 5+ different Unity versions installed so how would it know which to use?

rancid flower
leaden ice
#

Or which project to import to

rancid flower
#

i used to just double click on the unity package file and it would import it

#

id just have to click confirm

rigid island
tawny elkBOT
rancid flower
#

im banned apparently

fair mural
#

anyone got an idea as to how i can make the crosshair accurately reflect the potential bullet spread BASED off of FOV just like this reddit post from halo? what math can I do. do I just use arctan with the degrees of spread to radians? or is there a better way?

leaden ice
dawn nebula
#

Any tips for keeping your code from becoming too dependent on Unity? For example if you'd perform an engine swap.

leaden ice
#

or maybe (spreadAngle * 2) / fov if you allow the spread in either direction

leaden ice
dawn nebula
fair mural
#

yeah ill try that thanks

leaden ice
# dawn nebula yes

The best thing you can do is keep a strict separation between the Unity presentation layer and your internal game state and simulation code.

leaden ice
fair mural
leaden ice
#

and the end result here is a portion of the viewport

dawn nebula
leaden ice
#

to convert viewport points to screen points you'd use
https://docs.unity3d.com/ScriptReference/Camera.ViewportToScreenPoint.html
So you probably want something like

var topOfCrosshair = Camera.main.ViewportToScreenPoint(new Vector3(.5f, 0.5f + verticalPortionOfViewport / 2f, 0));
var bottomOfCrosshair= Camera.main.ViewportToScreenPoint(new Vector3(.5f, 0.5f - verticalPortionOfViewport / 2f, 0));``` to get the top and bottom of the crosshair in screen coordinates
fair mural
#

if you calculate the spread angle using vertical FOV, it'll return the Y spread. so, if you use a square crosshair, you wont need to calculate based on the horizontal FOV, because square crosshairs or square perspective angles in general always have a synced angle that is the came for width spread and height

leaden ice
#

basically what you're asking for is very difficult and likely impractical

dawn nebula
#

that just call your own shit.

leaden ice
#

not to mention if you dabble with the job system or anything, that's all not going to be portable

dawn nebula
celest musk
#

hello can someone help me either im special or i just cant find it im trying to chagne the name of my audio source but cant figure it out

leaden ice
leaden ice
leaden ice
#

That whole concept is weird so that's probably where you're getting tripped up. You have some invalid view of how Unity works

leaden ice
# celest musk

Components don't have names. Only the GameObject they're attached to has a name

celest musk
leaden ice
#

Why?

celest musk
leaden ice
#

I assume you're using GameObject.Find or something to try to identify these things? You're doing things in inefficient and off ways if so

hexed whale
#

I find this extremely weird, searched for like several hours, found only 2 forum threads about this. The problem is critical level, imho.
Is disabling opera mouse gestures for webgl unity builds even possible? This ruins my fast-paced game, like, to the point where, if there is no solution, I consider switching to pc xd

#

Imagine opening a new tab or closing the game completely by trying to use binoculars 🙂

#

Tried 2021, 2022, 2023. Nope.

leaden ice
hexed whale
mellow sigil
#

Congrats if your game is popular enough that you have to support Opera

#

AFAIK the gestures can't be disabled programmatically, Unity or not

soft ruin
mellow sigil
#

GetDuration returns infinity, or charCooldown ends up being infinity?

soft ruin
#

its constant / infinity (GetDuration) so charCooldown ends up as 0

#

but i figured the problem out

#

i was using the wrong playable

#

thank you!

frosty snow
#
UnityEngine.UnityException: VisualElementCreation can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
  at (wrapper managed-to-native) UnityEngine.UIElements.UIElementsRuntimeUtilityNative.VisualElementCreation()
  at UnityEngine.UIElements.Focusable..ctor () [0x00008] in <5566f9e97c3b47c3802abbb5405c3a92>:0 
  at UnityEngine.UIElements.VisualElement..ctor () [0x00081] in <5566f9e97c3b47c3802abbb5405c3a92>:0 
  at UnityEngine.UIElements.BindableElement..ctor () [0x00000] in <5566f9e97c3b47c3802abbb5405c3a92>:0 
  at UnityEngine.UIElements.BaseVerticalCollectionView..ctor () [0x0003f] in <5566f9e97c3b47c3802abbb5405c3a92>:0 
  at UnityEngine.UIElements.BaseListView..ctor () [0x00015] in <5566f9e97c3b47c3802abbb5405c3a92>:0 
  at UnityEngine.UIElements.ListView..ctor () [0x00000] in <5566f9e97c3b47c3802abbb5405c3a92>:0 

During the VisualElement static type initialization, we are calling native APIs that can only be called in specific contexts, and only from the main thread - otherwise an exception is thrown

the heck ?

object allocation is not meant to happen in the main thread due to render-stutters / jank
right?

fervent furnace
#

so you cant create uielement in other thread

quartz folio
#

There's absolutely nothing wrong with doing all sorts on the main thread. Most Unity applications do

broken jewel
#

i want to make something loke the following ---->
some objects gathered in a formation around the player..and those are floating and moving in circular path(the blue line)...after a moment those objects will move toward the front of the player following the red path with an impulse force....how can implement this thing? any suggestion?

lean sail
latent latch
#

UI is like the last thing I'd care to multithread

lean sail
latent latch
#

unless it's like a minimap or constantly being updated

lean sail
eager steppe
#

On the topic of main threading..

frosty snow
eager steppe
#
        {
                using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(MediaURL))
                {
                        uwr.SendWebRequest();
                        // wrap tasks in try/catch, otherwise it'll fail silently

                        while (!uwr.isDone) await Task.Delay(5);
                        if (uwr.result == UnityWebRequest.Result.ConnectionError)
                        {
                                Debug.LogError("[BACKEND ERROR] The sprite at URL '" + MediaURL + "' could not be loaded. Error: " + uwr.error);
                        }
                        else
                        {
                                Texture2D webTexture = ((DownloadHandlerTexture)uwr.downloadHandler).texture as Texture2D;
                                Sprite webSprite = Utilities.ToSprite(webTexture);
                                return webSprite;
                        }
                        return null;

                }
        }``` 

Should I even use Threading for loading song images? I want to avoid stuttering when loading them which is why I main thread it, but it crashes the engine regularly, and I have no idea why.
eager steppe
#

Problem with this is, I either store it in memory, which i probably shouldnt do since I store every song in memory anyway

or firm it and crash occassionally

lean sail
#

what the docs has definitely shouldnt freeze the game

fringe acorn
#

large image?

lean sail
#

maybe your issue lies elsewhere, try attaching the debugger and seeing what happens exactly

broken jewel
lean sail
nimble cairn
#
    public void ToggleUISphere(Transform t) {
        Image GO = t.GetComponentInChildren<Image>();
        GO.color = colorCalculator.CalculateColor();
        GO.enabled = !GO.enabled;
    }

Is there any better way of doing this? I don't want to have to drag and drop parent elements for every single UI parent that needs to use this function!

This method is called through the Pointer Enter Event Trigger.

#

Can't I just reference PointerEventData?

hasty canopy
nimble cairn
#

Yeah, you're right. However there is surely a way to reference the event trigger itself!

hasty canopy
#

Don't think so, although I would highly recommend using image as parameter instead so you can have more control over which image in specific you want effect to show on as "getcomponentinchildren" will grab the very first image it finds, which may not necessarily be the one you want the effect to work on

hasty canopy
#

I may have forgotten the correct name but there is something like that fo sho

nimble cairn
#

Let's give this a go

#

Yeah, kind of works. Thanks!

nimble cairn
#

OLD

Vector2 look = playerInput.Movement.Camera.ReadValue<Vector2>();
Vector2 movement = playerInput.Movement.Movement.ReadValue<Vector2>();

NEW

//   Input Handling:

//   Cache the playerInput.Movement object to avoid repeated access.
//   Replace repeated playerInput.Movement with a cached variable.

var movementInput = playerInput.Movement;
Vector2 look = movementInput.Camera.ReadValue<Vector2>();
Vector2 movement = movementInput.Movement.ReadValue<Vector2>();

Yea or nay?

somber nacelle
#

it is certainly more readable

nimble cairn
#

Is the GC worth it however?

somber nacelle
#

there is no difference in garbage collection here

nimble cairn
#

Well, var is constructed

#

Disregarding readability, is this micro optimization worth it?

somber nacelle
#

it's not extra garbage because you aren't creating a new instance of anything there. you're referencing an object that is already in memory

hasty canopy
nimble cairn
#

Okay I'll stick with this new way I guess!

hasty canopy
somber nacelle
#

creating any instance of a reference type creates garbage

hasty canopy
#

Ooh ok i see

junior kraken
#

Hi all. How do I render a layer only in a ScriptableRenderFeature and not to the main render target? If my main camera does not include the layer I want to render in the SRF, the SRF will not render it. If I do include the layer in my camera, the layer will render in the main render target when I don't want it to

deft timber
#

this is code related channel

junior kraken
#

I'm asking a code-related question

latent latch
#

more pipeline specific

junior kraken
#

Sorry, this is in URP.

latent latch
#

#archived-urp but the answer is between your camera culling layers and the layers you choose to render on the SRF

hasty canopy
#

He means it's more of a pipeline specific question, not code related question

junior kraken
#

Gotcha

rancid frost
#

How can i change material properties from editor?
I want to be able to get the properties from any shader and modify them directly from editor

dull belfry
#

Someone know how to remove the UNITY_SERVER define? I build a dedicated server and now the UNITY_SERVER define persists...

latent latch
oblique spoke
rancid frost
sacred sable
#

is there a way to save modifications made to a prefab during runtime

rancid frost
#

i believe there is a library for that

#

sec

latent latch
#

and similar

#

gotta access by string

#

sorry I mean Set^

west lotus
#

I do a const int in the class level

rancid frost
rancid frost
#

one reason is because, of type conversion at compile time

latent latch
dull belfry
glossy wave
#

how come i get a nullreferenceexception when trying to add my hit.transform.parent.gameobject to a list, but not when trying to destroy it?

quartz folio
#

An exception is thrown, execution doesn't continue past that point

#

also, if something has a transform then it has a gameObject

#

check if parent is null, checking parent.gameObject will always either be a NRE, or ok

#

Also, use CompareTag, and don't compare tags using equality

lone cape
#

there is any way to make LineRenderer be more 3D? I mean I have like 6(amount variable) renderers and is looks like (ss).

Vector3[][] positions = new Vector3[amount][]; // store 6 lineRenderers and points for them
.
.
.
for (int j = 0; j < amount; j++)
{
    LineRenderer ln = lineRenderers[j];
    positions[j] = new Vector3[ln.positionCount];
    for (int i = 0; i < ln.positionCount; i++)
    {
        positions[j][i] = Vector3.Lerp(startLocation, endLocation, i / (float)(ln.positionCount - 1));
    }
    ln.SetPositions(positions[j]);
}
while (Time.time - startTime < duration)
{
    for (int j = 0; j < amount; j++)
    {
        LineRenderer ln = lineRenderers[j];
        for (int i = 0; i < ln.positionCount; i++)
        {
            float noise = Mathf.PerlinNoise(i * noiseScale, Time.time * noiseScale)+ Mathf.Sin(j * 0.1f);
            positions[j][i] = Vector3.Lerp(startLocation, endLocation, i / (float)(ln.positionCount - 1)) + new Vector3(0, i%2==0?noise:-noise, 0);
        }
        ln.SetPositions(positions[j]);
    }
    yield return new WaitForSeconds(0.001f);
}

Any idea how to do it?

glossy wave
quartz folio
#

well, you're trying to destroy something that could be null, as it's not in the check

#

so that will be a NRE when you access the gameobject

glossy wave
quartz folio
#

so, what's the issue now?

glossy wave
#

nullreferenceexception on the

gnomeCollector.collectedGnomes.Add(hit.transform.parent);

line

quartz folio
#

have you checked which reference is null?

glossy wave
#

i'm not sure what you mean, this is all i know so far

mellow sigil
#

There's two things that can be null on that line, gnomeCollector and gnomeCollector.collectedGnomes. Check which one it is.

glossy wave
#

it's.... it's the gnome collector. gosh damn it! such a small thing to miss.. thanks..

quartz folio
hot timber
#

Can someone help me, I am new to unity and my vs can't Auto Complete I have tried going in the unity hub and add the vs moduel, also I have downloaded the Unity Development tools in the vs

tawny elkBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

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

hot timber
#

I have tired every step and it stil does not work

rose sparrow
#

How can I make a sound play only on the left or the right side of headphones?

wintry gust
#

Having trouble with generating mesh from script. I add a mesh filter, mesh renderer, then in code generate my mesh and add it MeshFilter.sharedMesh right?

I can't seem to see the mesh in the scene though. Am I missing a step? If I double click the Mesh Filter, I can see it's being properly generated and set

heady iris
#

go from top to bottom and complete each step without skipping anything

#

if it still doesn't work after doing this, share screenshots of your package manager and of your External Tools settings

green ice
#

What i have to do to solve this problem?

dense cloud
#

I want to understand why Coroutines don't work in Update()

 void Start()
    {
        attackWeightWave = 6;
        waveOneActive = true;


        ListInitialiser();   // Adds prefab enemies to list1 & Adds spawnpoint locations to list2
        StartCoroutine(WaveOneSpawner());  //Spawns enemy every 3 sec
    }
IEnumerator WaveOneSpawner()
    {
        while (waveOneActive)  // wave One attackweight = 6
        {
            if (attackWeightWave == 0)
            {
                break;
            }


            randomSpawnPoint = Random.Range(0, 5);            // selects random spawn point value 



            Instantiate(skeleton
            , spawnPointList.ElementAt(randomSpawnPoint).transform.position    // spawns enemy at a random location
            , spawnPointList.ElementAt(randomSpawnPoint).transform.rotation);

            yield return new WaitForSeconds(3);                             // wait for 3 sec before spawning another enemy

            attackWeightWave -= 1;


        }
#

This works now but initially I had it like this

  void Update()   // randomises enemy spawn location in the 3 spawnpoint with a 1.5 delay; 
    {

        while (waveOneActive)  // wave One attackweight = 6
        {
            if (attackWeightWave == 0)
            {
                break;
            }


            randomSpawnPoint = Random.Range(0, 5);            // selects random spawn point value 


            StartCoroutine(WaveOneSpawner()); //waitforsec 3 sec delay 
            
            Instantiate(skeleton
            , spawnPointList.ElementAt(randomSpawnPoint).transform.position    // spawns enemy at a random location
            , spawnPointList.ElementAt(randomSpawnPoint).transform.rotation);



            attackWeightWave -= 1;


        }

    }
#

The only explaination I could find is this

#

coroutine conflicts with update() and it bypasses waitreturn?

hasty canopy
#

Update is called every single frame, so what you're essentially doing is starting 100+ coroutines per second

heady iris
#

That'd make the entire game freeze

#

It just puts the IEnumerator into a list and tells Unity to handle it

dense cloud
hasty canopy
dense cloud
heady iris
#

no, the WaitForSeconds is perfectly useful

#

it continues to do its job

heady iris
hasty canopy
#

If I had to guess

hundreds of them are being executed,

after waiting for 3 seconds several of them are being instantiated and reducing attackweightwave by one (all happening within few milliseconds)

And any coroutine created after that are just exiting right away cuz attack weight is 0 now

heady iris
#

All it does is tell Unity "I want you to resume this thing every frame "

dense cloud
#

oh nono I meant it as in waitforseconds in update(), like what SYG said it calls couroutine a lot of times over a single frame

#

not that waitforseconds is useless totally

heady iris
#
void Update() {
  StartCoroutine(Delay());
  Debug.Log("Update");
}

IEnumerator Delay() {
  yield return new WaitForSeconds(1f);
  Debug.Log("Done");
}
#

This will immediately start logging "Update"

hasty canopy
#

I would assume attackweight is becoming 0 really quickly and so none of the coroutine are being executed anymore

heady iris
#

One second after starting the game, it will start spamming "Done"

dense cloud
hasty canopy
dense cloud
heady iris
#

and why it does not wait one second before logging "Update"?

dense cloud
#

also yep I understood your explanation

heady iris
# dense cloud

also, the reason the code shared here works is..

Unity will look for two different methods when trying to call Start. It accepts either a method that returns void or a method that returns IEnumerator

#

If it finds one that returns IEnumerator, it'll call the method and pass it to StartCoroutine

dense cloud
hasty canopy
dense cloud
#

so as long as it's not in update() it would most likely work?

heady iris
# hot timber

Close Visual Studio, hit "Regenerate project files", and then double click a script asset

hot timber
heady iris
#

Open the Solution Explorer window and then screenshot the entire editor

#

(ctrl-alt-L or View -> Solution Explorer)

hot timber
heady iris
heady iris
hot timber
#

yh I know

heady iris
#

Are you in Visual Studio 2022?

#

Make sure this isn't 2019 or something

hot timber
#

yeah

wanton egret
#

Hey, I have a problem with the Animations of my Sword. The Sword is a child object of the Character and so i cant animate both together right? I feel like I have to animate both objects indepently and make it somehow work this way but I have no Idea how to implement that. I'm somewhat new to Unity and so i dont know if there is a nice way to fix that. Thank you!

hot timber
heady iris
#

I bet there is an error message somewhere that states why the solution is incompatible

heady iris
# hot timber

One thing to try first -- right click on Assembly-CSharp and see if there's a "reload" or "refresh" option

simple egret
#

Says it's incompatible but it's not

#

Right click and reload

heady iris
#

did that do it? :p

#

bloody computers

#

no prob, glad it's working now

#

It must have been stuck looking at a solution file written before you got everything set up properly

simple egret
#

It's pretty common, it also says Unloaded from time to time

woven veldt
#

Hi Peeps. I have this machine model that has multiple objects on an armature. What is the best way of using entities with this model? Spawning it wise.

upper pilot
#

Is there a Vertical/Horizontal Grid Equivalent for sprites?

#

or should I use UI for that?

latent latch
#

I'd just use UI if you were making an inventory or something related like that

heady iris
#

there is the Grid component.

#

It translates grid cells into local positions for the Grid's game object

upper pilot
#

But it feels weird separating character icons from character sprite/prefab

#

I even put Healthbar into Sprite instead of UI for that reason

#

I can just create "slots" and use those

#

for icons and pretend its a grid

latent latch
#

well, UI does give you access to anchors if you do want resizing to be specific to resolution instead of constant height/size

#

but if you don't need that utility then I don't see a problem doing it without

upper pilot
#

I see, I never worry about resizing tbh, but maybe I should 😛

swift falcon
#

I'm having an issue where if the player clicks anywhere on the screen, or does a keyboard input, my end screen disappears, is there a way to deal with this? It's just meant to be an end screen where they press a button to return to the main menu but nothing else (game time is stopped, etc.)

leaden ice
#

Presumably you have code somewhere doing this

swift falcon
#

It's a pacman clone, so essentially once all the pellets are eaten or you die, it activates a function that enables a return to menu button, and then just an image.

private void EndGame(int state)
{
    menuButton.gameObject.SetActive(true);
    Time. timeScale = 0;
    if (state <= 1)
    {
        gameOver.enabled = true;
    }
    else if(state > 1)
    {
        gameWon.enabled = true;
    }
}
leaden ice
rigid island
leaden ice
#

Also shouldn't:

    if (state <= 1)
    {
        gameOver.enabled = true;
    }
    else if(state > 1)
    {
        gameWon.enabled = true;
    }```
Just be:
```cs
    if (state <= 1)
    {
        gameOver.enabled = true;
    }
    else
    {
        gameWon.enabled = true;
    }``` ?
#

but yes presumably the code that hides the screen is not here, it's elsewhere

swift falcon
#

Yeah, probably.. This is all in my gamemanager, it looks as though any input (besides directly on the button) is restarting the gamemanager, as I have the script to set gametime back to 1 only on the main menu.

leaden ice
swift falcon
#

Yeah I was getting it lol

#

How is best to share code here? It won't format right since it's too long (my brain is very turned off, I can't remember how to do it correctly)

tawny elkBOT
leaden ice
#

(use a paste site)

swift falcon
#

I didn't write most of this code (I'm not the main programmer and its just a tutorial), I'm just trying to get the UI working.

leaden ice
#

well you have this in Update

#

so i'm gonna go ahead and say that's your problem.

swift falcon
#

Eugh, holdover from the idea that pacman just goes on forever. Thanks, sorry to waste time with a simple issue.

zinc parrot
#

Hey so whats the best way to save a string in the unityeditor so that it persists between closing and opening unity and different scenes? I need to save an absolute file path without needing the user to define it more than once

#

is editorprefs what I am looking for?

zinc parrot
#

is playerprefs preferable to editorprefs? I dont care about this data in builds

hasty canopy
#

I don't even know what's editorprefs tbh with you, I just know for what you're describing playerprefs works and is widely used

zinc parrot
#

ah ok!

#

thanks!

hexed pecan
#

EditorPrefs seems to br the same thing but for the editor

#

So it sounds like what you need

heady iris
#

yeah

#

the Player in PlayerPrefs doesn't mean "the person playing the game"

#

it means they're for the Player, as opposed to the Ediotr

abstract birch
#

How do you unsubscribe from a Unity Event which you set in the inspector?

knotty sun
#

you cannot

abstract birch
#

isnt that a core part of an event handler?

knotty sun
#

no, unity events are split into two parts
permanentListeners (set in Inspector)
temporaryListeners (set in code)
unless you really realy know what you are doing, you only have access to the temporary ones

leaden ice
#

If it's something temporary, subscribe in code. Or consider using C# events

abstract birch
#

Ok thanks. Ill just use code unless there a better way to recreate something like this? Its a trigger that checks when the player left and ent\ered certain distance.

rigid island
#

blinding

tawny elkBOT
abstract birch
rigid island
#

all good. Now I'm hungry for some gabagool

winged tiger
#

hey can anyone help? I'm tring to write a simple voice chat using opus encoder:

if (Microphone.GetPosition(null) >= frameSize){
    float[] samples = new float[frameSize];
    audioSource.clip.GetData(samples, Microphone.GetPosition(null) - frameSize);

   // Convert float array to byte array
   byte[] sampleBytes = new byte[samples.Length * sizeof(float)];
   Buffer.BlockCopy(samples, 0, sampleBytes, 0, sampleBytes.Length);

   // Encode the audio bytes
   int encodedLength;
   byte[] encodedAudioData = encoder.Encode(sampleBytes, frameSize, out encodedLength);

   //TODO: send voice data
  Voice.Enqueue(encodedAudioData);
  Debug.Log($"there's the data :D");

  yield return null;
}
else{
    Debug.Log($"waiting data...");
    yield return null;
}

Why does this throws stack overflow on encoder.Encode(sampleBytes, frameSize, out encodedLength);? Thre frame size is 1600 and samplig rate is 16000

I got the opus encoder from here:
https://github.com/DevJohnC/Opus.NET

GitHub

Opus .NET Wrapper. Contribute to DevJohnC/Opus.NET development by creating an account on GitHub.

leaden ice
#

Shwo the full stack trace?

winged tiger
#
Unity.PlasticSCM.Editor.PlasticApp.HandleUnhandledException (System.Object sender, System.UnhandledExceptionEventArgs args) (at Library/PackageCache/com.unity.collab-proxy@1.17.2/Editor/PlasticSCM/PlasticApp.cs:231)
FragLabs.Audio.Codecs.OpusEncoder.Encode (System.Byte[] inputPcmSamples, System.Int32 sampleLength, System.Int32& encodedLength) (at Assets/Plugins/OpusWrapper/OpusEncoder.cs:69)
VoiceNetworking+<VoiceUpstream>d__19.MoveNext () (at Assets/Scripts/Sound/VoiceNetworking.cs:85)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <24d45e813e524a99bfb7a145158a7980>:0)
leaden ice
simple egret
#

Plastic SCM? what

leaden ice
#

It seems like OpusEncoder is calling... PLasticSCM????

winged tiger
#

...what is that?

#

whaat

leaden ice
#

PlasticSCM is Unity's version control system

#

I feel like something is getting messed up with the natie plugin execution here

#

it's like.. calling the wrong native plugin??

winged tiger
#

wierd

leaden ice
#

Are you using Version Control/PlasticSCM?

winged tiger
#

only git

leaden ice
#

if not I'd try uninstalling it from the project (via project manager) and see what happens

#

Yeah try uninstalling the Version Control package

winged tiger
#

i'll try

leaden ice
#

Actually I think PLastic is just handling the exception for some reason

simple egret
#

The lib uses pointers, but for it to flip a byte where it's not meant to so that is causes a stack overflow in another plugin is highly unlikely

leaden ice
#

but it's still weird as hell actually - IDK

leaden ice
winged tiger
#

oh my god since when JsonSerializer is from plastic

rigid island
#

seems you're missing the newtonsoft package

#

or you have bad asmdef

winged tiger
#

there was no problem until i removed plasticscm

rigid island
#

it probably had it as a dependency for serialization

#

You have multiple scripts that still have that namespace though idk if they're urs or not

#

Player.cs

winged tiger
#

what the hell is going on xd

rigid island
#

omg why are u on 2019

winged tiger
#

no idea

#

i just wanna write code

#

thats all

rigid island
#

wouldnt you want an IDE thats faster and slightly smarter lol

winged tiger
#

i can try

rigid island
#

download 2022 if you can later

winged tiger
#

ill do it

#

later

simple egret
#

I mean I don't know if developers at Unity are paid to shitcode all day, but the package manager sure is one of a special kind, to remove other packages than the only one you instructed it to remove

winged tiger
#

dammit

#

why newtonsoft diappeared :c

rigid island
#

who knows prob because it counted it as dependency

#

"oh you dont want this package let me remove ALL the other packages that came with it"

winged tiger
#

aaaaaaaaahhhh

#

how do i revert this

rigid island
#

Git xD

winged tiger
#

ah

#

got it xd

simple egret
#

It's like the most unstable package manager I've seen

winged tiger
#

true

rigid island
#

weirdly VC doesn't seem to have Json.net as dependency 🤔
maybe dependency just shows Unity packages..

winged tiger
#

okay now im back to square one

frosty sequoia
#

when i cast a line and have it bounce off the wall using this bit of code the width changes at sharp corners. does anyone know what causes this and/or how to fix it

hexed pecan
#

Linerenderer is just bad with sharp angles

quartz folio
#

you can improve it by adding vertices to the corner radius iirc

deep oyster
#

private Rigidbody2D rb; ... rb = GetComponent<Rigidbody2D>();
Why might this not work?

#

I have a rigidbody2d attached to the object

#

but it doesn't find it

somber nacelle
#

provide more context

deep oyster
#

What should I show

somber nacelle
#

where you call it, where any errors you are getting as a result of that not working are happening

quartz folio
#

"not work" — how does it not work?

#

what function are you calling it in? Have you checked it's being called?

deep oyster
quartz folio
#

Does that Debug.Log in Start get called?

deep oyster
#

wtf. I thought that was not printing cause rb was broken but it's not

#

why is start not getting called Hmmm

quartz folio
#

!code

tawny elkBOT
deep oyster
#

sorry

quartz folio
# deep oyster sorry

Please post the whole code using one of those links. And double-check that logs are not disabled in your console window

wintry gust
# wintry gust Having trouble with generating mesh from script. I add a mesh filter, mesh rende...

I'm still having trouble with this. The mesh is being generated, it's just not visible. What am I doing wrong?

private void BuildMesh()
{
    if (SplineMeshFilter.sharedMesh == null)
        SplineMeshFilter.sharedMesh = new Mesh();

    var mesh = SplineMeshFilter.sharedMesh;
    var vertices = new List<Vector3>();
    var tris = new List<int>();

    var length = _vertsP2.Count;

    for (var i = 1; i <= length-1; i++)
    {...}

    mesh.Clear();
    mesh.SetVertices(vertices);
    mesh.SetTriangles(tris, 0);
}
#

I have a Mesh Renderer as well

quartz folio
quartz folio
#

and you have rotated the camera around, checking from all sides?

wintry gust
#

Yeah, I figured maybe the normals were flipped but I'm still not seeing anything

quartz folio
#

Also check the scale of the object, and select it while pressing F to see if it focuses anything

quartz folio
wintry gust
deep oyster
#

I don't have Debug.Log disabled, I checked with a Debug.Log in FixedUpdate which is printing.
I just checked all the objects in the scene and only one has the BearController on it

quartz folio
#

The only way your other log could not be called would be if there was another exception earlier, on the first line of Start

deep oyster
#

nevermind I'm dumb as hell it is getting called it's just trying to find a GameObject that doesn't exist epic I spelled BearSpawnLoc wrong in the heirarchy lmao

nova shale
#

Hey all. I'm having an issue where OnCollisionEnter is not being fired. I've read a few articles/stackoverflow/ etc and have made sure that all the basics are hit. Neither are triggers, at least one is a non-kinematic rigid body.

This is the movement and collision code on the object that is moving

    void OnCollisionEnter(Collision collision) {
      Debug.Log(collision);
    }

    void FixedUpdate() {
      Vector3 newPosition = Vector3.MoveTowards(agent.position, currentPointPosition, 10f * Time.fixedDeltaTime);
      agent.position = newPosition;
      if (newPosition == currentPointPosition && path.childCount != currentPoint + 1) {
        currentPoint += 1;
        currentPointPosition = path.GetChild(currentPoint).position;
      }

      if (newPosition == currentPointPosition && path.childCount == currentPoint + 1) {
        Brain.DamageBrain(damage);
        Destroy(agent.gameObject);
      }
    }
#

The screenshots are just to show they are colliding and that the appropriate components are in place

nova shale
#

Path Agent which is attatched to the red cube

leaden ice
#

Give it a kinematic Rigidbody

nova shale
#

Interesting, if the unity docs say that only one of the 2 game object needs a rigidbody why, in this case, do both?

leaden ice
#

Since you're moving a static collider it's more of a teleportation and not a physical motion

nova shale
#

That makes sense i thought tha tmight be an issue but figured the speed would counteract that. Thank you

minor hazel
#

if im using a rule tileset is there any way for me to make it randomly choose between two tiles?

minor hazel
tepid brook
#

Hi guys, what is the best way to create a game with multiple model ? like overwatch if i want to change my character in the game

cold parrot
tepid brook
#

i have different models with same armature and i want to change my character when i want in the game

cold parrot
#

just switch out the model-prefab?

soft shard
tepid brook
#

i spawn it or juste hide the model i don't wanna use that the real question

tepid brook
#

like its just a skin

soft shard
# tepid brook like its just a skin

Ah I see, if changing skins is a relatively uncommon thing in your game (for example, changing on a menu before a game begins but not being able to change mid-game), spawning the mesh makes sense, if you plan to have a "skin changer" during gameplay, I still think initially spawning makes sense (then toggling if the mesh already exists rather than destroying) that way you only create the skins that actually get used, but this may depend on how your character hierarchy is setup - in my game for example, you change entire "characters" (abilities, models, animations, etc) from a menu and not just skins, so I have a hierarchy similar to this:

Root (scripts)
  - Physics (RB, collider)
    - Mesh
      - Rig
    - Obj Pool
    - Etc...

So in my case, I can swap out "Mesh" for a different prefab that also has the rig as a child

cold parrot
soft shard
#

^ Swapping out the materials is also a good option if the mesh doesnt need to change

tepid brook
#

yep i will swap the prefab because its not only the mats

woven veldt
#

what is this?

quartz folio
#

Have you googled it

woven veldt
#

Yeah its something to do with colab settings but when I search collab settings nothing comes up in my project

quartz folio
#

You went to Project Settings and looked under Services for version control?

woven veldt
#

I dont know what that is sorry

quartz folio
#

What, the project settings?

woven veldt
#

I have that but what is services for version control?

quartz folio
#

The item called Services

#

and the other item called Version Control, or Collaborate

woven veldt
#

okie

#

what do I need to do

jagged snow
#

I dont know if this is the right place to ask but is it normal to have a CharacterController component be able to push moving rigidbodies?

#

It doesnt seem like an intended effect

rigid island
#

Anyone know what this ProBuilderMesh.Awake() does ?
I was only able to shave off Physx mesh CollisionData ms converting to box collider but not sure what this component does that allocates, should I just make it into an FBX ?

#

just realized I should prob pool these as well..

#

12.3kb is wild

rigid island
#

amazing...pooling alone made it disappear..

#

nvm its there but just 20B, oh well

lunar python
#

how do you view the resources tab like that

rigid island
soft shard
frank carbon
#

i need help makeing a fan game can any one help?

soft shard
# frank carbon i need help makeing a fan game can any one help?

You may want to be more specific - what exactly do you need help with? What are you trying to replicate and what have you already tried? If your instead looking to recruit others or have someone else make whatever you want to build, this may be the wrong channel for that, but its unclear from your message what your goals are

frank carbon
#

im makeing a gorilla tag fan game might sound dum

soft shard
frank carbon
#

no

#

i9dk

#

idk

soft shard
# frank carbon idk

Hmm, it doesnt sound like you might have any specific question with what your trying to build (or maybe I misunderstand your goals), I would suggest to maybe start your project and then you can ask a specific question in the relevant channel if you get stuck, if your not sure where to start, I would maybe look through the game your trying to replicate and take note of the various features you want to make, then start planning to work on those features one-by-one

frank carbon
#

ok

frank carbon
#

i need help codeing a mod menu of admin

#

can any one try to help

lean sail
#

from your messages above, it sounds like you've yet to start the actual gameplay. Im not sure what you would want a mod menu to do, when you have no gameplay.

opaque fox
#

Hello so i am trying to make it so when the enemy i am coding collides with the player it stops moving. However when it stops colliding it walks towards it again but my problem is it almost instantly decollides with the player ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CowboyAnimationScript : MonoBehaviour
{
// Start is called before the first frame update

public Animator cowboyAnim;
public Transform lookObject;
public float maxTurnSpeed = 50f;
public float movementSpeed;
public float damageAmount;
public bool walkCurrently  = true;


private void Awake() {
    cowboyAnim = GetComponent<Animator>();       
 }

void Start()
{
    
}
private void OnCollisionEnter(Collision collision) {
    Debug.Log("Entered collision with " + collision.gameObject.name);
    if (collision.gameObject.name.Contains("XR Origin (XR Rig)")) {
        walkCurrently = false;
    }
}

private void OnCollisionExit(Collision collision) {
    if (collision.gameObject.name.Contains("XR Origin (XR Rig)")) {
        Debug.Log("EXited collision with " + collision.gameObject.name);
        walkCurrently = true;
    }
}

private void Update() {
    Vector3 direction = lookObject.position - transform.position;
    transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(direction), maxTurnSpeed * Time.deltaTime);
    if(walkCurrently == false) {
        cowboyAnim.SetBool("walk", false);
    }
    if (walkCurrently == true) {
        cowboyAnim.SetBool("walk", true);
        transform.position += transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed;
    }
}

}

latent latch
#

what do you mean by decollides instantly

opaque fox
#

so it does not stop moving when i want it to and i assume its because it stops colliding with the XR Rig

knotty sun
opaque fox
#

i have not

#

but ok that fine

latent latch
#

I'm assuming you mean your state of collisional changes too quickly because OnCollisionalExit happens right after Enter, so perhaps adding some timer to compare against so your flags don't flip instantaneously.

opaque fox
#

how would i do a timer in c# i have never done that

latent latch
#

googles. Can also look into coroutines, but knowing how to do a timer should be worth trying

opaque fox
#

turns out it is no longer ending the collision early however it is still trying to move. Although i am not sure if it is just the animation or both but i added this ever way ```c#

IEnumerator WaitForSeconds(float time) {
yield return new WaitForSeconds(time);
}

private void OnCollisionExit(Collision collision) {
    if (collision.gameObject.name.Contains("XR Origin (XR Rig)")) {
        Debug.Log("EXited collision with " + collision.gameObject.name);
        WaitForSeconds(3);
        walkCurrently = true;
    }
}
```
dusk apex
opaque fox
#

that is not my current problem

#

ignore that

#

urm just look at the question and the code from earlier

dusk apex
#

Only statements made after the yield statement and in the coroutine function would yield.

opaque fox
#

I dont need help with that rn

#

there is all the code and look at the question i just asked

dusk apex
#

What makes you think it isn't ending the collision early? Show us the console logs. Define "trying to move". For example: animation, positional translation, bool is true etc.

opaque fox
#

As I just stated it is no longer doing that. My problem is straight up the character is moving when variable is clearly off.

dusk apex
#

Show the logs.

opaque fox
#

it just walks towards the player

dusk apex
#

It moves because the conditions are met

opaque fox
#

wdym

dusk apex
#

It moves because the conditions are met

opaque fox
#

i dont follow

dusk apex
#

Which part?

opaque fox
#

well what conditions

dusk apex
#

Your conditions in Update

#

Prior to the moving

#

Debug that and you'll determine why

opaque fox
#
        if(walkCurrently == false) {
            cowboyAnim.SetBool("walk", false);
        }
``` does this not mean that it will it will stop walking
#

well the animation will

potent jackal
#

Hi guys, can anyone help me? I got an error that says: MissingReferenceException: The object of type 'AnimatorStateMachine' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.

dusk apex
#

That means the walk animation will be set to false

opaque fox
#

yes so it will stop

dusk apex
#

Not if it's true instead of false

opaque fox
#

huh

#

but its false

dusk apex
opaque fox
#

where it determines the variable

potent jackal
dusk apex
dusk apex
potent jackal
#

One sec

opaque fox
#

the line cowboyAnim.SetBool("walk", false); tells me that

potent jackal
#

!code

tawny elkBOT
dusk apex
opaque fox
#

wait i am really confused because when i look at the variable in the animator it stays off the whole time but the animation is clearly on

#

i have never debugged unity how

upbeat prawn
dusk apex
potent jackal
#

Yeah

dusk apex
#

If you double click the error, does it take you to the code that's throwing the error?

potent jackal
#

No

#

It takes me here:

dusk apex
#

Well, whatever the case is.. you've got something referencing that object that's trying to still access it but it's been destroyed already

#

Consider removing it from the field/list/array before destroying it.

potent jackal
#

Now I've got this error: NullReferenceException: Object reference not set to an instance of an object

#

And if I double-click it, it takes me here:

opaque fox
#

@dusk apex it is in debug mode and i ran the code

dusk apex
potent jackal
dusk apex
#

Maybe consider showing the necessary code

potent jackal
#

What's the necessary code?

dusk apex
#

The script..

gilded topaz
#

Does anyone else have the problem where you cant drag the stuff in the scene samples? Im new to unty so i dont know if its my fault

opaque fox
#

well i debug moded and ran the code whtat now

potent jackal