#archived-code-general
1 messages · Page 264 of 1
Doesn't matter. Errors halt the current thread and could cause it to skip over unrelated code
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
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
Are you using a tweening library for these animations? like DOTween?
No, I just want to queue animations
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
Idk if its worth it 😄
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
Maybe I explained wrong.
I dont need to make animations, I have 2d sprites.
I just need to play animatsions in sequence.
Oh.. well.. I probably would look into a tweening library then.. DOTween is pretty widely used and makes chaining animations together reasonably easy
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
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
Yep checking
uh I feel like learning this will take too long for my current needs, but I did use Tween in different engine.
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
Yeah I bet
How are you animating things now? Like, doing something like "start animation", setting a flag, and moving it manually in an update()?
I havent started yet, but sprite renderer/animator then I do something like .Animation.Play("Run"); From what I can remember.
oh, ok, so that is an animation (like, "unity animation" proper)
Yeah, my goal is relatively simple
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
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 😄
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
Queue<Animation> is part of dot tween?
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)
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
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'
yeah, so.. starting mutiple things at the same time is where this approach will start to fall apart a bit
Is there a way I can make unity compile in the background instead of waiting until it is focused?
dequeue takes the frontmost item off the list, but peek takes the frontmost item but leaves it in the queue
man, read the docs, Peek looks without removing
yes, but Dequeue is removing
The object that is removed from the beginning of the Queue<T>.
yeah, dequeue and peek are different things
Yes
"dequeue" = get the front thing and remove it
"peek" = get the front thing and leave it
yes, so
Dequeue - one
Peek - two
Dequeue - two
But peek is supposed to check next element?
it is two is after one
If you dequeue "one" then you are left with "two", "three" right?
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
The Peek method is used to look at the next item in the queue
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
in a Queue next is always first
yeah thats confusing, but I got it now
"next" doesn't mean 2nd, it means the next item you'd get off the queue
Make sense
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)
What are use cases for stack, hashmap in game dev?
I never saw those in any tutorial I've ever watched
stack: open dialogs on top of each other
hashmap = a zillion things, can't even begin to describe 🙂
Do you use hashmap in your projects?
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 ... }
Stack is very useful if, say you want an Undo function, stack will save your functions and return them in reverse order
I use hashmap every day, everywhere
How is that different front a List<PlayerFlags>
because lists are not optimized for searching
What do you mean return them in reverse order? 😮 That does sound interesting.
Like reverse all changes done by that function?
Stack is a FILO queue, First in Last Out
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
So should I use hashmaps instead of Lists? If its faster?
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"
So Stack wont work for my needs right? Since I need the opposite order I guess
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
Alright, I can have Queue<AnimationQueue> basically
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
btw Since .Net 4 Dictionarys are faster then HashMaps
public class AnimationQueue
{
List<Animation> list = new();
}
yeah I use dictionaries + lists mostly
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
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
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
Then you need to learn, use the right tool for the job
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)
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.
Queues and Stacks are useful when you really need to denote that a specific object is supposed to be used in a certain way.
I didnt know Queue exist until today
you need to learn data structures
much easier to read, less error prone to just do something like
foreach (Animation animation in allAnimations) animation.Play();
HashSet is another common one. A HashSet is basically a dictionary without values.
scroll up a page @hard viper 😉
Queues and Stacks are extremely useful, especially in game dev
All of them
wtf is a hashmap
But which are priority? I cant imagine myself using red-black tree
It sounds like black magic
Array, List, Queue, Stack, Hash Table (same as HashSet, same access as Dictionary).
You don’t need trees and linked lists until you are deeper in
Hash Table is same as HashSet or they just didnt include it on that list?
@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!
HashSets function based on Hash Tables.
a HashSet uses a hash table just to know if something is in the data structure or not.
hashset: no value
hashtable: key with value, and they are the same thing..
a Dictionary uses a hash table to go find the value for the key
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. 🙂
the only difference between a dictionary and hashset is that a dictionary stores values, and hashsets don’t
I would be really surprised if I start using black magic, it feels weird discovering those things 😄
lol, come back in 5 years
lol come back when you learn some manners
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
Nice, so there is a limit to how far you should go with game dev 😄
wtf is array
Stacks and Queues are more useful in the middle of an algorithm
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
Thats exactly how it is atm, but I have a list of data structures to look into. so I will do some research tomorrow on them.
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
you definitely should have at least list/hashmap/queue/stack/dictionary in your repetoire imho
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
I will do that, thanks
yeah, these are bread and butter
Any reason you didnt include Array?
yes
do include array
off-by-1 errors are notoriously bad for the world imho
arrays are useful.
Array is first data structure learned in JS, but List seems to be just better idk
I use 0 arrays in my codebase
Array is best data structure
js array is dynamic
You can loop through List same as through array
take arrays and chuck 'em into the sun imho!
array is also the base used for most data structures
it is c# list
hot take
arrays are good. very simple tbh
yeah, but that's not the point.. the point is the difference in how it looks:
foreach (thing t in allthings)
vs
for (int i = 0; i < things.count; i++)
the second one imho contains hard-to-see bugs
you can still foreach in an array
Lists and Arrays.
shhh don't tell him
it’s literally the same thing
Exactly, I like foreach more and more and if I really really need index, I can use 2nd option or just var index
it defeats my completely arbitrary point 😉
haha
arrays are good, and arguing otherwise is asenine
When do you use Array vs List?
they are faster than lists, and better when the conditions for them are good
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
I like for more because it lets you manage multiple things and control what happens.
use an array when the size of the list does not change
there are other factors, but that is the simple #1 reason
Cant you change array size later anyway or is there a way to prevent that?
no
list is wrapper of array (though everything is wrapper of array except treeset iirc)
I have a lot of Lists that dont change their size 😄
a List holds an array, where if it doesn’t have enough space, it makes a brand new array, and copies everything over
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.
Makes sense
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
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?
i would
That previous image wasnt for C# apparently lol
LinkedList, SortedDictionary, SortedList, SortedSet are there, should I care about any of these atm?
sortedlist is useless iirc
Hashset
that’s what I recall as well
because sorred list has overhead that does not scale well
Why are all of those data structure lists missing Array lol
Im trying to think if a rhyme like “hexagon is the bestagin” for array but Im coming up flat
sorted list is just bad
Every c# datastruct has some sort of iterator usually
for sortedlist to be good, the implementation would need to be a linked list, with binary search
LinkedList has any game dev use?
useless
Thats harsh Im sure there is a use
not really useful tbh
There is some sort of structure where you connect multiple elements with Next,Previous
Anyone remember what its called?
that is a linekd list
oh
Thats a linked list
but you need to know it since it is used in tree/graph and open hashtable and skiplist
Does it have any uses for Dialog system maybe?
tree/graph and open hashtable and skiplist
new words again haha
linked lists don’t let you skip to a specific index quickly. You need to traverse in time of O(n)
I really know nothing -_-
i would represent a dialog system as a directed graph
Recently Ive trying to understand concurrent binary trees https://onrendering.com/data/papers/cbt/ConcurrentBinaryTrees.pdf
Its a really smart tree
- 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
directed graph isn’t a data structure, but a mathematical structure
yeah its outside of data structure list, but I added it as something to research
Should I add anything else to this list?
for dialogue you usually want like one of those database trees
segmented set or something
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...
because you may have dialogue that meets up eventually
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
Just s tip, you should still init your list with some expected capacity to avoid the cost of resizing it
Alright, thanks
How do you init a list with expected capacity?
this is rarely the case
I usually do =null to avoid issues
Since my Lists tend to contain class instances
List<Character>
new List<int>(5) gives a list with capacity 5, and no entries filled in
but if you knew you’d need 5 entries, you might want to ask if you should use an array instead
So List<int>(5) returns null for each element?
the list has a count of 0
or 0 in case of int
but the array it holds has size 5
Which is a problem
no
capacity is just telling the list to get ready its internal array to hold that many entries
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
capacity. not count
(new List<int>(5)).Count gives 0
Ah, actually segmented tree is something similar, but more specifically this type:
https://www.javatpoint.com/threaded-binary-tree
Threaded Binary Tree with Introduction, Asymptotic Analysis, Array, Pointer, Structure, Singly Linked List, Doubly Linked List, Graph, Tree, B Tree, B+ Tree, Avl Tree etc.
(new List<int>(5))[3] gives an error, because index is out of bounds
Got it, that makes sense then
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
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?
then you just wasted a ton of memory and time allocating room for an extra 980 things
Since Array doesnt have some secondary Array to store data like a List does?
you should not over-allocate memory like that
Usually object pooling and stuff you do want to consider a bunch more indices
you will just pay the cost when its not needed, unless you actually get that high regulrally
an array is basically a pointer, which also knows how far it is allowed to go
or make it dynamically grow if you pass a point
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
you should never overallocate a ton more memory than you need
that is really bad practice
eh, usually in a c++ environment it's suggested
allocating memory is like the slowest single thing you can do
he asked about allocating 1000 for 20
that’s not ok
upfront initialization is always better than expanding out your data structs
mem is cheap
thats literally what i said, that its never a good idea to over allocate, but can be good to pre allocate when you know what range you will be in
i never said you suggested to overallocate
like if i know it will reach 20, yeah i will make it with that capacity
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?
Ideally for your object pools you should be checking at a threshold to expand it dynamically instead all at once.
it depends on a few factors but yes
Whats an object pools?
there is a high cost to creating and destroying objects
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
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
So you'd create list of 100 beforehand to avoid having to allocate it in that frame?
depends on the implementation
some grow it as needed then reuse what has been created
some make a bunch upfront
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
Makes sense
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
Right so if you expect maximum request to be 50, you should always make sure to have 50 empty slots
How do you even expand on a List capacity at runtime?
List automatically does it
Anyone familiar with tilemap perlin noise generation?
Without making a new List
list will automatcally rellocate at a larger size when you exceed capacity
whenever you Add to a list, it grabs more space if you don’t have it
generally it doubles in size when that happens, but what it does depends on the implementation
usually it is double
I understand, but that point was to prevent allocating 50 elements at once
oh it doubles
makes sense
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
generally it does, it really depends on implementation
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
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
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
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 😄
wil jsut grab the oldest live one and use it, if the pool is empty
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
Hey, I'm trynna use the closest line renderer for this script, but I can't figure out how
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hey, I'm trynna use the closest line renderer for this script, but I can't figure out how ⬆️
im not seeing any line renderers
yep, not a single LineRenderer in that script
Inb4 "well I got it from chatgpt"
Yes it's currently using two transforms, I'd like the script to use getposition on the closest line renderer to get the start and end position
right, so AI gave you crap code and you expect us to fix it for you?
I'm working on it right now, but I have some problems getting the script to work with line renderers, I thought someone with more experience might be able to help guide me in the right direction.
DO NOT
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?
Show code
{
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
you do know that code will only work once, right?
AddComponent
No
Why would that prevent me from setting the volume?
you add a component whenever this runs
because the AddComponent fails so the rest of the code does not execute
But, it plays, and the other parameters set correctly as well
imo, you should separate creating the SFX component, and playing it
doubt
GetComponent first, if it returns null AddComponent, not the best way to do it but, meh
if (currentSFXComponent == null) currentSFXComponent = CreateSFXComponent();
currentSFXComponent.Play();
Im very very tired but why would the add component fail?
_sfx.transform.position = position;
_sfx.name = "SFX." + clip.name;``` I changed this
becaise you can only have one AudioSource on a GameObject
that’s not true
Thats not true
Besides he makes a brand new go at the start
How would it have an audiosource?
good point, i missed that
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
Thats completely irrelevant to his problem
My problem is it seems like volume is either set to 0 or 1 in the code
then if the volume is not correct is must be
_sfx.volume = handler.prefs.PlayerPrefs_GetSFX();
Everything else works expect for that
Add debugs between to see what values are, but are you sure that nothing else ever modifies this object?
{
return 0.05f;
//return Prefs.Audio_Effects * 0.01f;
}```
Here is that function
No, it doesn't
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
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;
}
}```

as a rule of thumb, I try to keep Start, Awake, etc as simple as possible
but just writing separate methods
how about the secret start method
don’t tell him about that
You mean Awake?
Awake is wonderful imo. Because it gets executed the moment the script gets made.
instead favoring explicit setup methods that someone else has to call
Start is not so good imo, because it might wait until next frame, and jank up
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.
idk if i shared this, but my computer was fried last week. Changing now to a windows machine
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
the silver lining is that VS has a lot more shit for windows than mac
oh yeah, Visual Studio on Windows is a while other thing
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
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?
++secret
Next your gonna tell em about a service locator hehe
that's called the Yellow Pages
Hmmm and here I was thinking you are too young to know what yellow pages even are
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; } }
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
yep that works. Thank you:)
why is it saying type mismatch? https://hatebin.com/wrfuvcslvs
Are you trying to reference a scene object in a prefab
no im trying to refence the script
Like the literal text file your code is in?
the c# script
Why do you want to reference the script file
so my NPC script can refence it
Okay, but what is the purpose of referencing a script file
there's not really anything you can do with that
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
So then you probably want to reference an instance of the script, not the text document with the code written in it
You cannot reference a component present in a scene within a prefab
So now that we've established that this answer you gave makes zero goddamn sense, I ask again: Are you trying to reference a scene object in a prefab
no
So, show the inspector of the object you're drying to set your reference on
i fixed it
i can
No, you can't
i just did
Prefabs cannot reference objects in scene
No, you can't
Prove it
That's not referencing an in-scene object on a prefab
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
i dont know what it is but it works so im happy
do you not even read the comments in your own code?
i used chatgpt i didnt write that new code
why am I not surprised
it works
not the point, you still have no idea whatsoever what youi are doing
Ensure that there is a manager in the scene just logs an error. Never change chatgpt
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
Its almost like people are lazy and want everything to come made just for them
if i have a question which includes code but is around the audioSource do i ask it here or in #🔊┃audio
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
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
the text autocomplete robot has now showed you the worst possible way to reference an object
What you need to understand is that ChatGPT literally hallucinates word salad and uses clever math to make sure that the world salad reads coherent to you. That is all it does.
well done text autocomplete robot, for giving bad advice without proper context once again
I prefer the term Stochastic Parrot and who in his right mind would take any advice, let alone coding advice, from a Parrot?
why do i get this when i edit script during playmode and save?
https://i.imgur.com/UtmZkyM.png
it used to not break
it suddenly loses reference or something
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
All your variables have to be serialized for it to work properly, it's basically useless
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
Lookup Command pattern, on that point using Interfaces is a bit more modular than abstract classes
this tutorial is for javascript/redux but it does a good job of explaining a solid approach approach
(there's a few ways to do something like this and which you choose depends on how you want to model your state/actions)
https://redux.js.org/usage/implementing-undo-history
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?
I have an undo redo system. Can give advice
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?
Assets typically don't unload with the scene, so it should be fine.
alright
wat o.o
Unity.Burst.BurstCompiler.CompileFunctionPointer
can we call this from a build ?
welp Unity.Burst.BurstCompiler.CompileFunctionPointer seems to hang
even though it sais that burst is enabled
I'd assume that burst compiler is not included in the build, but I might be wrong.
Better go ask in #1062393052863414313
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.
File -> Import inside the unity editor
yea that works but I miss being able to just double click to import
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?

Or which project to import to
i used to just double click on the unity package file and it would import it
id just have to click confirm
help
!vrchat will prob be a better place
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
im banned apparently
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?
Wall according to https://docs.unity3d.com/ScriptReference/Camera-fieldOfView.html the fov field on the camera represents the vertical field of view.
So to get the portion of the vertical viewport you need to cover it'd just be:
float fov = myCamera.fieldOfView;
float verticalPortionOfViewport = spreadAngle / fov;
Any tips for keeping your code from becoming too dependent on Unity? For example if you'd perform an engine swap.
or maybe (spreadAngle * 2) / fov if you allow the spread in either direction
Does the other engine also use C#?
it's always a square
yes
yeah ill try that thanks
The best thing you can do is keep a strict separation between the Unity presentation layer and your internal game state and simulation code.
nothing here has to do with squares
yeah it does
and the end result here is a portion of the viewport
I feel like this can be incredibly tough outside of things like turn-based games.
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
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
yes it can
basically what you're asking for is very difficult and likely impractical
I feel like it would involve a lot of Monobehaviour wrapper classes.
that just call your own shit.
Which is what I meant by a script separation between the presentation and the game layer. Note that the presentation layer is quite a huge portion of the game though. Only part of your code even has the potential to be reusable
not to mention if you dabble with the job system or anything, that's all not going to be portable
As opposed to full separation, what can you do on a smaller scale? Usually you'd use interfaces for this sort of thing, but Unity doesn't play nice with those, especially in the inspector.
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
You wouldn't use the inspector for those parts anyway, remember this is supposed to be portable.
Wdym by change the name of your audio source?
That whole concept is weird so that's probably where you're getting tripped up. You have some invalid view of how Unity works
Components don't have names. Only the GameObject they're attached to has a name
oh ok thats kinda of annoying but thank you
Why?
i just find it weird
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
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.
Doesn't sound like anything related to unity at all. Wouldn't you just disable those things in your browser settings?
Seems weird to tell that to my customers instead of at least showing some sort of browser window to one click do it. Or better, to disable them completely while focused. Unity fixed right click on canvas, so...
Congrats if your game is popular enough that you have to support Opera
AFAIK the gestures can't be disabled programmatically, Unity or not
So im using playable.GetDuration() from Unity Timeline and it keeps returning infinity rather than the expected 1s it should. has anyone uncovered this issue before
code here : https://pastebin.com/QCQZ3K8J
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
GetDuration returns infinity, or charCooldown ends up being infinity?
its constant / infinity (GetDuration) so charCooldown ends up as 0
but i figured the problem out
i was using the wrong playable
thank you!
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?
so you cant create uielement in other thread
There's absolutely nothing wrong with doing all sorts on the main thread. Most Unity applications do
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?
🤔 a lot of people here dont even touch async/thread/task anything for 99% of their game
UI is like the last thing I'd care to multithread
i dont think this is possible with just physics, unless your player stands still at all times. With just forces, this will 100% bump into other objects, the player, or each other. Simplest way would be doing this via like animation or directly affecting the transform position.
unless it's like a minimap or constantly being updated
🤷♂️ so far ive never seen someone in here really use threads in a large part of their game. some people smarter than me have even gone as far as saying its not needed at all. iirc the person above is doing something else though, not even sure if this is a game.
On the topic of main threading..
Yes but we want to avoid stutter/jank
{
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.
did you try the way that the docs does it?
https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequestTexture.GetTexture.html
Yeah, but it does freeze the game
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
what the docs has definitely shouldnt freeze the game
large image?
maybe your issue lies elsewhere, try attaching the debugger and seeing what happens exactly
yeah, i did the circular movement part using the transform position...but i can't do the final part that is the objects will go in opposite circular direction like the red line in the image...how do i do that?
🤷♂️ I cant really say much without seeing what you did. For that last line, if it's not supposed to be exact you could always use rigidbody movement at the end and just add force
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?
Sending image as parameter instead of transform would be one way to make it better
Yeah, you're right. However there is surely a way to reference the event trigger itself!
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
Actually wait I think you can do it
There's something like "eventsystem.currentselected" which shows the object mouse is hovering over, for which you can do the same thing
I may have forgotten the correct name but there is something like that fo sho
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?
it is certainly more readable
Is the GC worth it however?
there is no difference in garbage collection here
Well, var is constructed
Disregarding readability, is this micro optimization worth it?
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
Correct me if I'm wrong, It's local variable and their value is disposed of as soon as they are out of scope
Okay I'll stick with this new way I guess!
Does creating a new local list in a function create garbage? 
creating any instance of a reference type creates garbage
Ooh ok i see
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
this is code related channel
I'm asking a code-related question
more pipeline specific
Sorry, this is in URP.
#archived-urp but the answer is between your camera culling layers and the layers you choose to render on the SRF
He means it's more of a pipeline specific question, not code related question
Gotcha
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
Someone know how to remove the UNITY_SERVER define? I build a dedicated server and now the UNITY_SERVER define persists...
that's it, now go to your materials on the editor with that specific shader and it'll be editable
Try switching to a different platform
no, I want other scripts to access this
is there a way to save modifications made to a prefab during runtime
and similar
gotta access by string
sorry I mean Set^
https://docs.unity3d.com/ScriptReference/Shader.PropertyToID.html can be used to avoid allocating a string each time get set methods are used
I do a const int in the class level
I need to also know property name
for example
https://docs.unity3d.com/ScriptReference/ShaderUtil.GetPropertyName.html
this gives me the name and the type, but I dont know how to edit said properties
one reason is because, of type conversion at compile time
https://docs.unity3d.com/ScriptReference/ShaderUtil.GetPropertyType.html
This? ShaderUtil seems to have all you need to get the info, but you then need to set the buffer info on the material itself
oh alr tyy
Thanks, that worked
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?
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
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?
i'm now using CompareTag, checking if transform.parent is null, and I chanced my list to type Transform, but the issue persists. did i miss something?
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
so, what's the issue now?
nullreferenceexception on the
gnomeCollector.collectedGnomes.Add(hit.transform.parent);
line
have you checked which reference is null?
i'm not sure what you mean, this is all i know so far
There's two things that can be null on that line, gnomeCollector and gnomeCollector.collectedGnomes. Check which one it is.
it's.... it's the gnome collector. gosh damn it! such a small thing to miss.. thanks..
Learn the steps so you're familiar with the error; because it's the most common one you encounter https://unity.huh.how/runtime-exceptions/nullreferenceexception
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
!vs
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)
I have tired every step and it stil does not work
How can I make a sound play only on the left or the right side of headphones?
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
this makes it sound like you've tried random steps in a random order
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
What i have to do to solve this problem?
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?
Update is called every single frame, so what you're essentially doing is starting 100+ coroutines per second
StartCoroutine does not block whoever called it until the coroutine is done.
That'd make the entire game freeze
It just puts the IEnumerator into a list and tells Unity to handle it
Ah, so it just nullifies the waitforsecond in the update
Not really no, it just means every second hundreds of coroutines are created and all of them are being executed simultaneously
and that just makes the waitforsecond useless
again, StartCoroutine will not make Update "wait"
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
All it does is tell Unity "I want you to resume this thing every frame "
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
void Update() {
StartCoroutine(Delay());
Debug.Log("Update");
}
IEnumerator Delay() {
yield return new WaitForSeconds(1f);
Debug.Log("Done");
}
This will immediately start logging "Update"
I would assume attackweight is becoming 0 really quickly and so none of the coroutine are being executed anymore
One second after starting the game, it will start spamming "Done"
when it was in update, it just instantly spawns all the enemies with no delay, yeah
You should really be calling coroutine like this only once from somewhere
got it, I think that's why it crashed unity before I set an if else condition
do you understand why this code does what I said it does?
and why it does not wait one second before logging "Update"?
it just continously spams update like you said?
also yep I understood your explanation
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
ah aside from initialising variables in Start(), it could also used for Coroutines like the code I shared
Yes, although coroutines doesn't really care where they are being started from. They can be started from anywhere
I've called it from the OnTriggerCollision2D before and it worked there
so as long as it's not in update() it would most likely work?
Close Visual Studio, hit "Regenerate project files", and then double click a script asset
Open the Solution Explorer window and then screenshot the entire editor
(ctrl-alt-L or View -> Solution Explorer)
Sort of! You have to start a coroutine on a MonoBehaviour
well that looks weird
yh I know
yeah
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!
I don't even have 2019
it sounds like it's missing C# support entirely
I bet there is an error message somewhere that states why the solution is incompatible
One thing to try first -- right click on Assembly-CSharp and see if there's a "reload" or "refresh" option
wow
thank you!
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
It's pretty common, it also says Unloaded from time to time
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.
Is there a Vertical/Horizontal Grid Equivalent for sprites?
or should I use UI for that?
I'd just use UI if you were making an inventory or something related like that
there is the Grid component.
It translates grid cells into local positions for the Grid's game object
I am making an icon list above 2d character sprite.
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
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
I might try that
I see, I never worry about resizing tbh, but maybe I should 😛
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.)
You'd have to explain exactly how this "end screen" works and the code behind it etc. we can't help from this description
Presumably you have code somewhere doing this
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;
}
}
Sorry where does this code live? How does it get called?
nothing here would hide the screen
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
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.
you should really just share your entire script
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)
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
(use a paste site)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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.
if (lives <= 0 && Input.anyKeyDown)
{
NewGame();
}```
well you have this in Update
so i'm gonna go ahead and say that's your problem.
Eugh, holdover from the idea that pacman just goes on forever. Thanks, sorry to waste time with a simple issue.
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?
Playerprefs works
is playerprefs preferable to editorprefs? I dont care about this data in builds
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
EditorPrefs seems to br the same thing but for the editor
So it sounds like what you need
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
How do you unsubscribe from a Unity Event which you set in the inspector?
you cannot
isnt that a core part of an event handler?
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
If it's something temporary, subscribe in code. Or consider using C# events
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.
blinding
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok srry
all good. Now I'm hungry for some gabagool
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
Shwo the full stack trace?
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)
That's a really weird looking stack trace...
Plastic SCM? what
It seems like OpusEncoder is calling... PLasticSCM????
PlasticSCM is Unity's version control system
https://github.com/DevJohnC/Opus.NET/blob/8e904ec9d67eae08d6db6e43f0a5f30bdf4bc5f0/OpusWrapper/OpusEncoder.cs#L69
This looks like a direct call into the encoder native plugin
I feel like something is getting messed up with the natie plugin execution here
it's like.. calling the wrong native plugin??
wierd
Are you using Version Control/PlasticSCM?
only git
if not I'd try uninstalling it from the project (via project manager) and see what happens
Yeah try uninstalling the Version Control package
i'll try
Actually I think PLastic is just handling the exception for some reason
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
but it's still weird as hell actually - IDK
and for us to have a clean looking C# stack trace when that happens? 😵💫
thats Json.net
seems you're missing the newtonsoft package
or you have bad asmdef
there was no problem until i removed plasticscm
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
omg why are u on 2019
wouldnt you want an IDE thats faster and slightly smarter lol
i can try
download 2022 if you can later
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
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"
Git xD
Yeah at least make it check if other packages rely on the thing you're about to delete
A bit of decency please
It's like the most unstable package manager I've seen
true
weirdly VC doesn't seem to have Json.net as dependency 🤔
maybe dependency just shows Unity packages..
okay now im back to square one
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
Linerenderer is just bad with sharp angles
you can improve it by adding vertices to the corner radius iirc
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
provide more context
What should I show
where you call it, where any errors you are getting as a result of that not working are happening
"not work" — how does it not work?
what function are you calling it in? Have you checked it's being called?
Does that Debug.Log in Start get called?
wtf. I thought that was not printing cause rb was broken but it's not
why is start not getting called 
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sorry
Please post the whole code using one of those links. And double-check that logs are not disabled in your console window
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
You should make sure a material is assigned. But also, what's shown in the mesh when you select it?
and you have rotated the camera around, checking from all sides?
Yeah, I figured maybe the normals were flipped but I'm still not seeing anything
Also check the scale of the object, and select it while pressing F to see if it focuses anything
Looks fine. I guess you have info logs disabled in the console, and the VVV log is being printed twice. One object works fine, and you have a second object you've forgotten about that has no Rigidbody2D
Ahh, that helped me. The position is waaaaaay off.
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
The only way your other log could not be called would be if there was another exception earlier, on the first line of Start
nevermind I'm dumb as hell it is getting called it's just trying to find a GameObject that doesn't exist
I spelled BearSpawnLoc wrong in the heirarchy lmao
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
Which script is this code on?
Path Agent which is attatched to the red cube
Give it a kinematic Rigidbody
Interesting, if the unity docs say that only one of the 2 game object needs a rigidbody why, in this case, do both?
Well I think your main issue is that you're moving a static collider. Generally any moving object should have a Rigidbody
Since you're moving a static collider it's more of a teleportation and not a physical motion
That makes sense i thought tha tmight be an issue but figured the speed would counteract that. Thank you
if im using a rule tileset is there any way for me to make it randomly choose between two tiles?
Yes bro that is perfect, thank you so much
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
depends on what you want to do specifically. Generally speaking there is no best way. Maybe narrow down the question a bit. Its very expansive.
i have different models with same armature and i want to change my character when i want in the game
just switch out the model-prefab?
Are these different models meant to be totally different characters with different abilities and attributes like Overwatch and other character-based games, or literally just a mesh change being the only difference like maybe something closer to Subway Surfers?
i spawn it or juste hide the model i don't wanna use that the real question
Same armature not same model but same size
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
Thx for help
if you just want to change the textures, then swap out the material, otherwise swap the prefab that holds the animator, model and rig
^ Swapping out the materials is also a good option if the mesh doesnt need to change
yep i will swap the prefab because its not only the mats
what is this?
Have you googled it
Yeah its something to do with colab settings but when I search collab settings nothing comes up in my project
You went to Project Settings and looked under Services for version control?
I dont know what that is sorry
What, the project settings?
I have that but what is services for version control?
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
If there's a Version Control or Collaborate item, make sure it's turned off
https://forum.unity.com/threads/collaboration-error.1274522/#post-8339514
https://forum.unity.com/threads/spamming-the-console-collab-collab-service-is-deprecated-and-has-been-replaced-with-plasticscm.1321206/#post-9448253
cheers
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
how do you view the resources tab like that
this is the Profiler and in Hierarchy view
Might be better asked in #💻┃unity-talk or #⚛️┃physics , though a CharacterController handles its own physics, so its likely intended behavior of the physics engine to interact with rigidbodies
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
im makeing a gorilla tag fan game might sound dum
Is there a specific code-related problem your trying to solve with it?
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
ok
as Dibbie said above, start and then ask a specific question. Literally no one is gonna sit there and help just create an entire "mod menu". Split your problems into steps, look at existing solutions online, and then try. also #854851968446365696 on how to ask questins.
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.
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;
}
}
}
what do you mean by decollides instantly
so it does not stop moving when i want it to and i assume its because it stops colliding with the XR Rig
will you please post large blocks of code correctly, I'm sure you have been told this before
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.
how would i do a timer in c# i have never done that
googles. Can also look into coroutines, but knowing how to do a timer should be worth trying
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;
}
}
```
That coroutine doesn't do anything useful
that is not my current problem
ignore that
urm just look at the question and the code from earlier
Only statements made after the yield statement and in the coroutine function would yield.
I dont need help with that rn
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
there is all the code and look at the question i just asked
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.
As I just stated it is no longer doing that. My problem is straight up the character is moving when variable is clearly off.
Show the logs.
It moves because the conditions are met
wdym
It moves because the conditions are met
i dont follow
Which part?
well what conditions
if(walkCurrently == false) {
cowboyAnim.SetBool("walk", false);
}
``` does this not mean that it will it will stop walking
well the animation will
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.
That means the walk animation will be set to false
yes so it will stop
Not if it's true instead of false
Provide the code where you've destroyed it
where it determines the variable
I dunno where I destroyed it...
Not that I'm aware of. There wasn't any debugging done to prove that it was false
Where do you call destroy?
One sec
the line cowboyAnim.SetBool("walk", false); tells me that
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Well, it moved so walk currently is true or something else is moving your character. Debug the damn variable already.
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
https://paste.ofcode.org/jxUiL5ZJyN8kszwCbNJEet
So I made a hdrp day night cycle, but I was wondering, how could I make it so the clouds move around, the density changes over time etc? I have 0 idea how
Is that the only place you're calling destroy in code?
Yeah
If you double click the error, does it take you to the code that's throwing the error?
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.
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:
@dusk apex it is in debug mode and i ran the code
Did you make these scripts?
yeah
Maybe consider showing the necessary code
What's the necessary code?
The script..
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
well i debug moded and ran the code whtat now
I have so many scripts