#archived-code-general
1 messages · Page 202 of 1
Keep your last frame's position and rotation in a variable. That way you can raycast from the last point towards the current point
And then if the ray hit anything, you have the hit point
Any tip about how can I avoid this with my ragdolls?
Probably nothing with code
game devs have been trying to figure that one out for decades
fix your colliders
My colliders? In which sense?
dont you have capsule colliders?
I tried adding .sleepThreshold but didn't work
Yes, I have
this looke like you need more damping or less aggressive angle limits
ok so check if they're not intersecting and that are thin enough to only wrap the limb
also add some angular vel friction on Rb
Less aggressive angle limits means increase or decrease the angle limit numbers?
Allowing for wider angles, and reducing how much force is used to maintain that, if applicable
dunno how your ragdoll is set up
It was a time ago I did this but I took a T pose object, make unity to create the ragdolls, and then I tried to apply that to my enemy, because applying it directly didn't work :/
the default ragdoll is ok but it does need tweak, did you check the colliders also? screenshot them in scene view
How do I reduce the force required to mantain it? Don't know about a field which does that
Is the ragdoll made up of CharacterJoints?
here this might help (its timestamped to issue)
https://youtu.be/RB18IyKZiB0?t=735
Learn the creation workflow for Ragdolls in Unity, how to toggle between an Animator and Ragdoll, and think through some optimization ideas when you have a large number of potential ragdolls in your game!
Ragdolls are a hugely popular mechanic in games that add, usually a funny mechanic into your game. What they always do though, is allow you t...
if so, you can set the twist and spring limit spring and damper values.
Non-zero values will make the limits soft.
brilliant thanks!
should I have to worry about if another object moved out of the path during that time though?
aka it might have passed through it last frame
but now raycasting this frame will have it hit nothing?
I only use that type of joints
(I'm making a gif to show the colldiers)
In the gif there is a bit of overlapping, but that is because the arm doesn't want to rest
For bullets that are fast enough (faster than 100m/s), you don't have to worry. You could fire a spherecast to account for the diameter of the projectile
if my bullets travel at like 20 velocity I dont need to worry
should I still be using raycasts or just colliders if they are "fairly slow" like that?
(its not really a bullet but a fireball)
A non-trigger collider and a rigidbody with continuous collision detection is sufficient
why non-trigger?
atm Im using a trigger collider
Because CCD only works with physical colliders
oh interesting
If you do not need the projectile to pass through anything, then regular collider
a lot of the time I need it to pass through multiple things
enemies need their proj to pass through enemies and platforms for ex)
player proj just need to pass through platforms
You can use layer-based collision detection then, make it ignore collisions between two layers via the Physics settings
gotcha, was worried about how much "knockback" might happen if it wasn't a trigger
A trick is to set the projectile's mass to the lowest value you can (near zero) and it won't apply any visible knockback
Is there really no way to get these values from AnimationClip in code
Hey, how to unload a loading scene? I currently have this code
private IEnumerator ChangeSceneAfterLoaded(string sceneName, float minimumLoadingTime)
{
AsyncOperation sceneLoadingOperation = SceneManager.LoadSceneAsync(sceneName);
sceneLoadingOperation.allowSceneActivation = false;
yield return new WaitForSeconds(minimumLoadingTime);
sceneLoadingOperation.allowSceneActivation = true;
}
what are you trying to do ?
with them
insert an animation event at runtime using the frame # (stored in a csv file)
But seems like you can only get start/end frames from ModelImporter
ohh you can ?
doesn't that give you the amount of frames needed ?
yeah but that is not attached to AnimationClip so can't access that detail in runtime
I will probably use an editor script to just extract the start/end frame and put it in a scriptable object or something
hmm could get the length in seconds i suppose ? do some math to get the frames (idk how I stink at this)
why not insert the animation event before?
not sure why an event would need to be changed at runtime
figure in code you could change what the event does
yeah i dont get the usecase for it as wel
Tbf Im pretty nub with animation stuff tho
yeah i may just do that. it's a weird usecase
previously our attack system used timings instead of animation events
so the attack triggered a specific timing instead of based on a frame #
so it would be better for us to just refactor it to properly use animation events
Ah I had that also
Trying to line up cooldowns+animation without animator events sucked
You would think a 0.3s animation and waiting for 0.3s would work
Only sometimes lol
yeah exactly
I would put in animation events everywhere and refactor
Sounds like less time long run
put like an Action to invoke as the Animation Event , then plug/listen whatever methods u want to it
UnityEvent also works if you're working with designers and need inspector to assign methods
yeah i will refactor to do that
we assign all the listeners in code, so no need to do anything in the inspector
thanks
Let's say I want to make a list of classes that are all derived from a generic base class. Is there a simple way to do this?
oops
could you do?
List<TheBaseClass<object>>
Not really.
MyType<Foo> and MyType<Bar> are completely different types
and MyType<object> is not a supertype of MyType<Foo>
This is a problem I ran into recently.
I think I am regretting making my parent class generic, because now I don't have easy access to parent functions
I have an EntityState abstract class that's derived by a variety of specific state types
each of which declares its own state machine type
Hello, I'm currently using Physics2D.Raycast for my turret to check if target can be seen. To achieve that, I'm iterating over every single enemies on the map (that can be up to 50 or more than a hundred little creatures) and do the following:
- Compare distance with the previous nearest enemy
- If nearer, Raycast (on the enemy layer only) to confirm it is a visible enemy
- Replace previous enemy if it is both nearer than previous enemy and visible
So this is how my turret works, problem now is I can have multiple turrets, and one is fine, but I tested with 40 turrets and I'm down from 400+ FPS to less than 30.
Any better implementation for my usecase ?
(Top down game btw)
and each of which references an instance of that state machine type
I wanted to be able to put common logic in the EntityState class (e.g. a "try set state" method that would ask the state machine to enter the state you called that method on)
But that would require knowing the type of the state machine
So EntityState would need a type parameter
which would make it impossible to refer to any arbitrary EntityState
https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance
Covariance and contravariance allow for you to use more or less specific types in some situations
Never had it come up yet.
why not do an area casting like overlaps and skip the distance checks, only wait for enemy to be inside areas? (all you need is collider)
right now I have:
FixedSpawnpointBase<T> : Monobehaviour, ISpawner
FixedSpawnpointType1 : FixedSpawnpointBase<MyType1>
FixedSpawnpointType2 : FixedSpawnpointBase<MyType2>
DifferentTypeOfSpawner : Monobehaviour, ISpawner
I wound up just copy-pasting the same logic into every derived type, lol
it feels like a situation where c++ templates would work
I want to work with functions in FixedSpawnpointBase, on objects exclusively from derived classes
what navarone said...but also how close to each other are the turrets?
They could be anywhere on the map, depends where the player puts them
well, that much is fine so far. you can write methods in FixedSpawnpointBase<T> that work with T.
but you could even just put like 3-4 colliders on a turret each closer so you only iterate over the closest few and grab the closest one
if no target move further out
another option if fixed map size, is to have colliders not on turrets, but around the map to essentially "split" the map into sections
grab the closest section and iterate over it, if no enemy grab the next one
etc
imo the colliders on each turret would be easiest to implement
(the collider setup is how my enemies currently work, they do different actions depending on which collider player is touching)
so... how do I make this not repeating
Need a little assistance. After trying to create a inventory/Ammo system I started getting this error:
assume it will get worse in future if I don't figure it out early
does ISpawner not cover everything you need to do here?
restart unity. probably just an internal bug.
let me try. Thanks
I see you're using a field on spawnHandler
Okay ! I'm relatively new to Unity. I'll need some time to understand what you guys just suggested and look more into the available Unity functions
. That's what blindly following guides does to me... I'll be back if I have questions
This error generally appears when you're doing something wrong with the Collections system.
(not System.Collections -- the Unity collections package)
I've watched a few videos from this guy that seemed to be up to date and good
You can go to Preferences -> Diagnostics, then check this guy
TempMemoryLeakValidation
Restart the editor. You should get more information about the source of the problem.
FixedSpawnpointBase has functions that other ISpawners really don't need to implement
and that I need
awsome. Let me give that a try. Thank you
@tulip cosmos ignore the timestamp but this video and the next one show how he uses SO and colliders to do something very similiar to what we were describing
Oh perfect, thanks !
Is it not possible to make FixedSpawnpointBase<T> figure out what to do in its own methods?
jason weimann? is also very good...however his videos aren't always super straight to the point, but very good for "more advanced" topics
so? in FixedSpawnpointBase<T>, you can work with objects of type T
Brackey for super basics...but at this point 5 years is a starting to get outdated
Yeah? I don't understand what you are asking
Explain what ISpawner is. It looks like you aren't actually using that interface at all right now.
ISpawner is an interface so spawnedentityhandlers (components on what is spawned) can report back their status, of if they despawned or died, so spawner knows if it is allowed to respawn
why not just add spawned items to a list and have the spawned thing remove itself from the list when it dies?
so why not give it a TrySpawn method that tells it to check if it can currently spawn something, and to do so if possible?
I don't understand where the hangup is.
ISpawner does not implement a generic TrySpawn because that really should not be public for some spawners
Found the issue.
I was using a scriptableObject as the dictionary key and Unity really does not like that
Thanks for the help
idk maybe I could make the interface do more work
maybe just a ConsiderSpawn or Tick or something
I try to avoid dictionaries 😄
I don't see why that'd be an issue.
Something so that you can tell the spawner "think about spawning"
FixedSpawnpointBase<T> would then implement that method.
why? they're extremely powerful
You want to avoid downcasting like this.
hence why I ask
casting to a more specific type
because otherwise this is going to spiral out of control
I've always just had lots of bugs and annoying things with them
not much harder to just make a struct/class to hold all the info I need
wot
or sometimes I would just realize I need slightly more info and want to store like 3 things instead of key/value
and key/value/value gets confusing 😄
You can use almost anything as key/value they're very powerful
private class EntityInfo
{
public float t;
public bool present;
public bool entered;
}
private Dictionary<Entity, EntityInfo> entities = new();
an excerpt from a component that sends signals when entities enter an area, but only after they spend a long enough time in the area (same for exiting)
You are right, not the issue
If the weirdness persists, do a Reimport All
unless I have an enum to use as the key I just dont like them
¯_(ツ)_/¯
Assets menu up top -> Reimport All
I have no idea what kinds of "bugs" you could run into here
you're missing out tbh
dictionaries with unity objects as keys are super useful.
for what
that's like asking what lists are useful for
lol
so basically anytime you would use a list...you just use a dict instead?
its like one of the most basic form of "database" you can have
can one event do to much 🤔
A list is used to store an arbitrary number of things
A dictionary is used to relate an arbitrary number of things to other things
huh?
lemme find some random examples from my code
maybe I just dont have many use cases
private Dictionary<CompletionToken, float> countdowns = new();
CompletionToken is part of my game's AI. They keep track of when an entity has finished a (possibly very long) sequence of actions
I use this in a debug component.
When a token is marked "done", I do a 1-second countdown before throwing it out
Have you ever used PlayerPrefs?
so that it doesn't instantly leave my debug view
this dictionary holds those countdown values
Well if the scriptableObject in my dictionary is not the issue, then only thing I can think of is the Events.
Upon equipping an item I raise an OnEquipEvent and I have 4 classes waiting for a scriptableObject.
Inventory
UiManager
AmmoManger
EquipmentManager
is it possible the date can't get passed around fast enough?
yeah...not very long
I've got a massive playerInventory tho
same exact concept
just made some good code!!!
simple use case: say you want to associate a bunch of items to some ID. Typically GUID's are used which is just some long random string. A dictionary is useful here
You REALLY dont want to associate this with just index [0..n] because if you rearrange the items, you now have major issues where you lost the previous ID and would need some mapping for it, and now dictionary is relevant again
its only 20000 lines!
I do use 3 dicts there but most things I just use lists for
I'm running into a problematic situation where I have a list of SOs that are cards, and i need to remove specific cards selected from the deck... I'm trying to use List.Remove(card) but it removes the first instance it finds of that card when there are more than 2 of the same card in the deck, is there a way I can use the unity GUIDs or something to identify the unique instance of these duplicate and remove a specific one from the List?
a lot of times it feels like I just need to store of bunch of stuff and not necessarily associate it to anything
If you have the same object in the list twice, then there is no way to distinguish them
They're literally the same thing
Perhaps you want to instantiate each card before putting it in the deck, so that each object in the deck is a unique instance
ohh I just saw your last msg and didn't see ur previous ones. Not sure sorry
no worries.
No.
There's no such thing as "not getting passed around fast enough"
😄
the events aren't happening asynchronously or something
one of the cases where giving it an id and using a dict might be good
That's good to know. 2 things ruled out
not sure if its what you are doing
so SO's can't have GUIDs, and GOs can. basically that's what you're saying right? i didnt want to instantiate all the cards as GOs but if i have to
but you shouldn't be modifying data in SO during the game
No. I didn't say that.
you could be making a copy of it
Not editing at all. Just reading
I presume you have a folder full of card assets.
And that you've put these card assets into the deck list.
Is that correct?
yes, there's a list of SOs that are in the deck list
and you've dragged the same asset into the list more than once
yep
thats fine, i mean i doubt theres any dictionaries in something like flappy bird. really depends on the game
If you have 52 cards in your deck, but there are only 26 unique assets and you've dragged each one in twice
You can give SOs GUIDs but if you use like createinstance youll have duplicate Guids
ah ok
then your list only contains 26 unique objects
unless for some reason you want to create a new guid on instance creation
the two copies of the card named "Foo" are references to the same object
there aren't two "Foo" objects
there are two references to the same object
It doesn't matter if you slap an ID on the card. The two references in that list will point to the same card with the same ID.
What you can do is create a new list and Instantiate each object in the old list, then put the result in the new list.
you will now have a list of 52 unique objects.
They will be unrelated to the 26 assets. Instantiate creates a copy.
the two "Foo" cards in your new list are references to two completely separate objects
(neither of which is the object corresponding to the asset)
ok that makes sense! So
cardStack = new StackList<Card>(); foreach(Card card in startingDeck.cardList) { ** // this was problematic, add Instantiate line here and Push the new object into the stack instead** cardStack.Push(card); }
Right.
You would run into the exact same issue if you were using GameObjects (or any other unity object type, like MonoBehaviour)
You'd have multiple references to the same object, which are completely indistinguishable
I guess you could write a method that skips the first n-1 instances of an object so that it can remove the nth one
but that sounds annoying
so once I fix that, then the List.Find() should be able to identify the duplicate card types as unique instances?
Right. Note that these new instances are not related at all to the instances that came from the assets
so
[SerializeField] Card card;
void Awake() {
Debug.Log(card == Instantiate(card)); // returns false
}
If you still want to be able to check if a card is a specific kind, you might want to do something like this
public class CardDefinition : ScriptableObject {
public string cardName;
public float coolness;
}
public class Card {
public CardDefinition cardDefinition;
}
So you wouldn't be directly using the scriptable objects.
yea i've been using a name variable as an identifier anyway
You'd be creating a Card from a CardDefinition
That's what I wound up doing for items in a soulslike game
A scriptable object is used to define the weapon's characteristics. A weapon prefab includes a weapon spec
So your hand and deck would be made of Cards, which are a container for a CardDefinition and any other runtime data you need
yea I know that eventually I probably will need to do something like that, if I intend on having modifiers for specific instances of specific card prefabs (like adding a bonus to a specific instance of 1 attack card)
maybe a list of modifiers applied to the card, if your game allows for that
yeah
now you've neatly separated the read-only definition of the card from the stuff that can change as the game progresses
public class CardDefinition : ScriptableObject {
public string cardName;
public float coolness;
public int manaCost;
}
public class Card {
public CardDefinition cardDefinition;
public bool free;
public int ManaCost => free ? 0 : cardDefinition.manaCost;
}
if you want to know if a Card is of a specific kind, you can check if card.cardDefinition == someDefinition
also, if you want to be able to see the List<Card> in the inspector...
just slap [System.Serializable] before the Card definition
it's not a MonoBehaviour because it doesn't really have a reason to be one. I guess you might do that if the cards are physical objects in your game world
where the card really does "exist" somewhere
yea I know that refactor is coming, i should probably do it soon... lol thanks a lot im gonna save this convo for later!!!
np!
So with the tem Memmory validation on, This is what I see and it just keeps going
Fair, I wonder if I should be using dicts when pooling
Lists seem to work well tho
That's really curious. It looks like Unity is leaking memory that was used when logging...?
it makes sense if you're pooling many kinds of objects
instead of having a List<Foo> and a List<Bar>, you'd have a Dictionary<Type, List<Component>>, or something like that
note the moderate loss of type safety there
the pool itself would just be a list or whatever collection you want (queue/stack)
but having many pools is different. you could reference each pool you want based on the prefab, which is conveninent since the prefab is the object you are pooling
I have zero clue as to what is causing this.
What version of Unity are you using?
Oh right, that's the more useful variety
my suggestion would only have one pool for each kind of component
2023.1.10
we were talking about this two days ago
hm, that shouldn't be too buggy
that's just the Tech Stream release, not a beta or alpha
You could try updating to the latest 2023.1.x release.
(although, I ran into a weird slowdown when switching from 2023.1.6 to 2023.1.11...)
Things where working just fine until I starting adding this ammo class. 🤣
Does it stop if you get rid of the debug log statements?
The allocations are all full of debug text.
(also, it's whataburger time, so i must go)
its what NGO does in their sample projects, so i just took that part and its really nice
thanks again! looks like doing Instantiate definitely fixed the bug. for now i'll use this approach, until phase 2 of the project where I add in card upgrades. you the man/woman/child/person!!!
you'd use a dict if you want the prefab as the key and its pool as the value when/if creating a pooling system . . .
Can you be more spezific? What kind of code?
its movement based i have a plane game where the object rotatesalong the z axis
however i want to cap the maximum angle it can rotate
so they cant do 360s basically
ive got how to rotate the plane but idk how to cap it
i was able to cap the x axis but i cant figure out the z
i can send you the code itd probably be easier to understand that way
im bad at explaning xD
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
i was able to cap the x axis but i cant figure out the z
However you capped the x axis, do the same for the Z axis.
Anyway you really need to get your IDE configured
hey, I have a scene like this, and on my hexagones in the back i have a script that has OnMouseEnter and OnMouseExit functions to highlight the hexagons when i hover over them, everything works great except for the UI part. I want the hexagons to not get highlighted behind the UI elements. So basicaly i want the UI elemnts to block the mouse from triggering the OnMouseEnter function. Can anyone tell me the best way to do this?
don't use OnMouseEnter
use the event system which is integrated with the UI
ide configured ?
this means IPointerEnterHandler / IPointerExitHandler
Or the EventTrigger component
(also make sure your camera has a Physics Raycaster on it)
Your IDE is your code editor
the IDE config wasnt about solving your issue, it was a suggestion on something you should definitely be doing before any coding
the code still works tho only installed unity and vs on home pc today so i havent set it up
just because it works doesn't mean you shouldn't configure it from here on
something you need to do before asking code questions.
(this helps rule out basic/syntax errors solved by IDE suggestion)
see #854851968446365696
Is there a way to draw a line between two Vector3 coordinates without using debug.DrawLine?
I need to draw a lot of what's basically projectile streaks, the projectiles themselves are just an array of structs with current position and a velocity.
I tried using a pool of LineRenderer objects, but the lag gets unbearable with just a couple of thousand of them.
"Just" a couple thousand? Might want gpu instancing, ecs, or might be able to get away with some fancy particle system tricks?
I dunno the best way to handle that at all though. Someone else may know. Just my initial thought
Yeah, if a line renderer is being laggy, you're probably reaching the limits of what you can do with the gameObjects workflow.
Might want to look at the profiler first though. Perhaps it's just something in your code, or there's some other way to optimize it.
My main problem is that, if I understand it correctly, LineRenderer cannot have more than one line in it? So I currently create thousands of clones of a single line renderer
There's a low level GL library if you want to delve into that
They probably can't. At least not disconnected lines. Might be wrong though. Should look at the manual/docs for more info.
That being said, if you're actually using a pool, you could have enough of them pooled so that you don't need to instantiate them at runtime.
Anyways, hard to say anything specific without more info(profiler data, code)
Yea you cant have a real disconnected line renderer. The only workaround I know is some material with transparent sections or hiding parts of it but that still probably wont be feasible for this
Ok, so then how can I make debug.drawline work in final game then?
That is for debugging, so afaik you can't
Maybe you just want to use particles (trails specifically)
VFX graph is pretty good if you wanna generate thousands of particles/strips if you've got a gpu to spare
sweet, thats what I've been doing
public Dictionary<Bullet, ObjectPool<Bullet>> bulletPools = new();
Can I relay to particle system the relevant info, or I will need to restructure my setup to use particles instead of structs with projectile data?
Ideally of course relay in the way of "here's an array of coordinates, draw particle at each one"
Im out of date on what you are talking about
but you basically just want a laser?
reading up...maybe not...you could just put particles on an object and move the object between the points you want
Naw, I need to visualize the bullets, and there can be thousands of them
so just...bullet trails?
yes
have you tried looking on youtube?
cause I see a lot of tutorials that seem like what Im guessing you want
My issue is scale. I have implemented solution RN using line renderer, It just lags
Like 5 fps with 1200 trails
2d or 3d
3d
trail renderer might be what you need
disclaimer: I only do 2d stuff so have no idea wtf this stuff is 😄
Again, profile the game. See what exactly is causing the lag..
very true, however even if its not causing the lag running like 100k line renderers is bad idea imo 😄
100k?
They are not running 100k. They were talking about a couple thousand. Which could still be too much.
ah, thought he said trails for 1200 objects
But without profiling it's hard to say.
and multiple lines renderers per trail
I don't really know what you mean, or the effect you're going for. But what you described above is a good use for particle trails and you can have way more than GOs
If you have 1000s of the projectile even, thatll cause lag too
if hes pooling them and doesn't have a ton of colliders/rb I dont think that would be too bad?
It's all speculations untill they provide proper profiler data...😅
You cant just throw pooling at everything, I'd say at 1000s of projectiles you will pretty much always experience lag
And if you dont, your user probably will on their not as good PC
lol I've got a 3070 and 5y old cpu and forget thats still a good PC 😄
Does anyone know why when I press the game scene in unity, I cant see my prefab? For context, im making a 3d space shooter and when i go to the game i cant see the shooter itself even when the camera is placed on it
Yeah, I'm trying to profile RN, and as I expected, if I don't spawn new line renderers - no lag, with no changes in code, the only thing that doesn't fire if I don't spawn them is this bit in foreach loop for each projectile struct:
if (p.line)
{
if (!p.line.gameObject.activeSelf)
p.line.gameObject.SetActive(true);
p.line.SetPosition(0, p.curPos - (p.velocity * Time.fixedDeltaTime * 4));
p.line.SetPosition(1, nextpos);
p.line.endColor = clr;
}
Placed ON it? Might be too close and is culled?
Show the inspector of the camera and the rest of the editor
#💻┃unity-talk is a great place to post picture and show stuff also if its not code related
For this, it can probably just be done with GameObject, so you arent limited to spawning bullets. Whatever takes from this system will do what they want
Oh yeah, forgot the channel. Unity Talk is the right place
hadn't considered that thanks
I've got bulletpooling and a particle system pooling
might keep those separate but anything I pool thats an "object" I'll keep in bulletpooling 👌
What exactly do you see in the profiler though?
is there any benefit to unity ObjectPool like u can write ur own in 10mins
You can write a Vector3 in 10 mins as well.
There's also UnityAction, which is basically the same as Action.
There's no particular benefit, they just provide a default implementation. They probably also use it somewhere in the engine code too.
Also, saving 10 min of time is nice.
UnityAction + UnityEvent afaik has benefit of appearing in editor and Vector3 not the same thing. Now that I looked at it aint even sure u save those 10mins u need to learn the thing first 
You'd save ten minutes 🤷♂️
UnityEvent, yes. UnityAction doesn't really affect anything afaik.
But yeah, you can say the same thing about almost any feature:
Why do you need a CharacterController component if you can implement one yourself in 10 min?
Probably a better one too.😬
Still waiting for a native non-PlayerPref save utility.
It's not required but.. then again, it's 2023.
I wouldn't be surprised if unity's object pool had some extra secret batching methods which you can only do with the source so your methods would always be worse off ;)
That was my idea abt it but reliable reddit sources
told me its not the case so wtf
funny you say this. i literally just created my own object pool for learning and building simple features. writing up a simple tutorial on it now . . .
The real kicker to making a good object pool is making it smart enough to load and unload resources when needed
instead of just caching yourself a billion GOs for later use
Either way, you're pooling so there's only so much you can improve with your own custom pooler. It's a memory allocation vs garbage collection concern, where you'd just need to make time to properly unload stuff.
exactly what i do; it's why i always make my own
i have the option to preload a certain amount instead of the entire capacity. you can add more until you hit capacity. it has the option to expand beyond capacity if needed, and will check to unload resources back to capacity when the current active amount is below a threshold
you can choose to recycle the objects which will always grab the oldest spawned item and re-use it (this method cannot expand, obviously) . . .
Aye, sounds pretty good
you can go further and add delayed despawning to objects, similar to Destroy(gameObject, 3f). it's another collection to track but more functionality . . .
I asked this yesterday in #🤖┃ai-navigation but channel does not seem very active, if anyone happens to know anything ...
my own 2 cents on the preceeding topic is... please god don't try to use game objects for "bullet"... unless its like super mario 3 bullets
Are there free / near-free tools/services/software to 'make my voice into an ai-actor' that can then do tts (reading prewritten but not recorded, dialog) at runtime? This is for use in a mod, so it will not be 'sold' and there is also no budget.
Does anyone know how the chatgpt mod for skyrim handles this?
Google "train text to speech ai model on voice samples".
iirc mozilla has one too
building an entity component system. how should I conceptualize cameras
should cameras be entities
or components of entities
or properties of systems
or exist on their own, injected into systems that needed them
etc.
Why not use Unity's ECS?
And if you don't want to, why not model it the same way?
this is for a custom game engine i'm building with javascript. came here because I figured there'd be some experts here with wisdom for me
sorry should have clarified
Unity doesn't technically use a pure ECS right?
because components both encapsulate data and behavior
unity components act as both systems and components
right?
Unity has 2 forms now, the MonoBehavior way with components like you say, and the #1064581837055348857 way. As far as I know, DOTS ECS is 'pure' ECS, but you can ask those people, it usually comes down to semantics on what pure ECS means.
Still, this is a Unity server about Unity questions, so its quite weird to ask here about building your own game engine. I would assume your graphics library of choice also has a discord.
https://docs.unity3d.com/Packages/com.unity.entities@1.1/manual/index.html
The entities docs here, you can read up on what Unity ECS is.
So I want to add triggers to the red circle as well as the yellow once, however I want to make sure that the red doesn't get trigged if my object is on the yellow. Is there a nice way to do this or is it just put the yellow trigger slightly infront of the red one?
Hello, I'm using ffmpeg with unity by starting an ffmpeg process as can be seen in this image. It works as expected if I play the game in unity editor but If I take a windows build it isn't working. What should I do?
You should see if this code crashes somehow
Wrap it in a try-catch and log any exception on the screen
Generally having a console system in your game to log messages and/or errors is a good idea since you also want to see those in a build somehow.
Otherwise idk, I never used this
ohk,i'll try to put this in try-catch. Although it works perfectly in editor. But I thought maybe the ffmpeg folder not getting included in the build
Who knows
hi everyone, i have just started working on unity 3d AR foundation , i got the scene set up for AR with the session origin and plane manager and anchor creater and all that stuff, i even got to spawn a character as anchors created but the issue is that i am having difficulty detecting the planes , they take long to detect and feels very glitchy , how can i fix this? and any suggestions on how to start working with AR to make a nice game
I have two colliders. I am detecting their collision in the editor by Physics.BoxCastAll() to get their raycast hit.
I want to get the collide point between them.
targetHit.collider returns correct but targetHit.point returns Vector3(0,0,0) always.
The interesting part is, when i give a maxDistance to Physics.BoxCastAll(), it works but that is not what i want since i dont know the direction at first.
The code is:
https://gdl.space/exinazemiw.cs
What is Layers.Area?
Oh let me add into the pastebin
you should also print targetHit.collider.name
Area => 1 << (LayerMask.NameToLayer("Area"));```
should work but you can do it more simply like this:
```cs
Area => LayerMask.GetMask("Area");```
Oh didnt know that
Anyway I suggest this as a next step
If I have a list of X,Y coordinates, and need to find clusters of coordinates in the list which form connected clusters, is the best way to do this a graph-based search algorithm? like DFS/BFS
yes
you may need an n^2 first pass where you create an adjacency list using the distances
Figured. Just wanted to make sure in case there was a lighter/simpler way. ty
There may be a fast way that involves spatial data structures like quadtrees
it depends on your needs
i am basically looking through a grid, so it isn’t that shitty to do the search. I need to do a first pass that searches whole tilemap first anyway to find relevant tiles to be consilidated
Are you trying to find clusters of coordinates that are nearby?
or is the idea that every pair of coordinates less than x distance apart are connected?
I have 2 scripts, a terrain generation script, and then a cave generation script. The caves generate below the terrain and now I need another script to cut through the the terrain to create entrances to the caves. I also have a water plane and a cave ceiling that I need to cut through as well. How can I do this?
The terrain is the built-in Unity terrain, right?
So you need to cut terrain holes where the caves intersect the terrain surface.
No I am using a script to generate a mesh using perlin noise
I can provide the script if you need
I'm not familiar with mesh generation in Unity. It sounds like you need to subtract the cave mesh from the terrain mesh, I guess.
What does that mean lol
Boolean mesh operations combine two meshes. This is a subtraction of one cube from another cube, for example.
It'll depend heavily on what your generated meshes look like, and how you generate them.
So we do probably need to see those scripts
My cave mesh and terrain mesh are 2 seperate meshes, and here is my terrain gen script:
nvm, issue was I wasn't dealing with the colliders offset
Would I be able to create a hole prefab that subtracts it's mesh from all meshes it collides with?
what can i use besides playerprefs to save data or can i make in order that playerprefs works when i build the game?
Playerprefs saves data permanently (even if you uninstall).
We normally save JSON/BSON files for data that persists after application close.
i mean there are workin in editor but not when i build the actual game
are you saving files into the project folder?
no
i don t think so
thanks i guess i will try it
What's the difference between interfaces and abstract classes?
mainly, interfaces can only be extended and abstract classes can be instanciated, just like normal ones
you can't construct an abstract class
An abstract class is like a class, but it can have abstract members with no implementation
Deriving classes must override those members.
extended?
Interfaces are just a collection of properties and methods. They do not contain implementations of the methods (yes, I know about default implementations; ignore those for now)
You can only derive from one parent class. You can implement many interfaces.
An interface represents a contract. You promise you can do XYZ.
How to create different development modes inside editor?
For example I want:
Development mode
Game-designer mode
each mode changes the way how to work in editor. Scripts will compile based on this mode. Is it possible only using defines or there is some built in solution?
Abstract classes need to be inheritted from. C# only allows single inheritance, so you’d be using up your ONE parent. Interfaces do not.
Abstract classes can have implemented methods (methods that actually do things), virtual methods, fields, static fields… the works. Interfaces don’t (but do allow some of this stuff in C#9, which Unity doesn’t allow).
@civic folio Example of an abstract class: FixedSpawnpointHandlerBase is an abstract class full of concrete methods that handle spawning (taking in info, requests to spawn, requests to despawn, checking if already spawned, etc).
It is abstract because it has an abstract method to actually spawn something. Child classes are responsible for handling the actual spawning, because different types of objects might have different requirements.
What is there that I can't do with interfaces
All the children inherit the methods defined in the abstract class.
If I used an interface, I would need to copy paste like 10 different functions, and 10 different fields etc to make everything match.
Example of an Interface: ISpawner is an interface for any spawner. It has just a few methods for entities to report if they died to the spawner. The spawner could be a fixed spawnpoint, but also could be something totally different (like an enemy that spits out enemies). Either way, the spawned thing needs a way to tell what spawned it that it is dead/despawned. ISpawner has 2 methods for that.
Because it is an interface, the enemy does not care if the spawner was a fixed spawnpoint or enemy or whatever.
But everything in an interface is abstract. (for the most part)
interfaces cannot define fields.
they also cannot define any inheritable behavior
Every ISpawner NEEDS to define a completely custom method for each requirement of the interface.
If you want a bunch of classes to inherit the exact same function, that it inheritance, not interface.
And for referenced, my abstract FixedSpawnpointHandlerBase ALSO implements ISpawner
the two can be used together
how does that work for classes?
well, they're classes
abstract classes can define fields
never mind
it just allows you to have abstract members
and prevents instantiation of the class
that's about it
abstract class just means you can’t make an instance of the class
you NEED to inherit to really use it
do you understand?
yes
as a rule of thumb, most interfaces have an extremely tiny set of methods. Because anything that implements it is forced to implement each of them
abstract classes can get fucking massive, because you are making methods to get inheritted.
My ISpawner interface is basically 4 lines long
my abstract FixedSpawnPointHandlerBase is about 200 lines long
because it actually has its functions and machinery filled out
Interface just means “I expect this class to have functions X, Y, and Z, with those return types and arguments.”
an interface should be a set of methods that accomplish a specific task.
and they should be super generic
if Foo implements Damageable, Foo promises it can be damaged.
ISpawner’s methods are:
-Get prefab the spawner makes
-Request spawner to spawn something
-Tell spawner that something it spawned died
-Tell spawner that something it spawned despawned without dying
any spawner should realistically be able to do those 4 things, no matter what shape or form it takes
It also doesn’t explicitly ask for the spawner to do something too specific.
Like with Fen’s IDamageable, you would want something like “RequestTakeDamage”, more than “ForceTakeDamage”. This way it is clear that the thing implementing the interface is deciding wtf to do when information is passed into it.
That’s all I got for now. Make sense?
RequestTakeDamage is smarter because we might want some things to implement invincibility or invincibikity frames later. And we don’t want to micromanage that shit. That is the responsibility of the IDamageable to decide what to do with the incoming damage request.
One last note; Interfaces CAN enforce properties. So you can’t make a field, but you can force anything that implements it to give a getter for something.
do you know any toturial for making a game like "Dark Messiah Of Might And Magic " in unity or skyrim (just sword fight ) ?
i need these 3 things
1- first person melee combat just like Might And Magic (sword fight , defend and kick and the part 2 sowrd stuck and you have to press left button fast )
2- npc ai behaver ( i loved the part when enemy health was low they were ran away ) , walking
3-i need learn to make stronghold crusader ( the part i order units to move or make a place for workers and workers work like wood cutters )
I would appreciate any help you can give
also do ai in unity is a real thing ? like can i actually ask for code from it ?
( i want tutorials not the ai code thing was just a question )
Hey, How to unload these scenes?
is there any way to enable read/write of texture through script?
I think not, if you want to make a Texture Read/Write you will need to make a copy
Only if you're creating the texture. If a texture has already been created and loaded, then you can't change read/write after the fact. Read/write determines if Unity will unload the texture data from the CPU after it has uploaded it to the GPU. Once it's unloaded, it's unloaded and you can't get it back without reloading the whole asset from disk again, which you can't do from script.
okay thank you
How do I make copy of the texture?
new Texture
GetPixels
SetPixels
Apply
In order to get the pixels from the original texture, it has to be read/write enabled.
no, that is a Read operation not Read/Write
you can also use GetPixelData/SetPixelData
read/write enabled must be checked either way. it keeps a copy of the texture in main memory.
isReadable is set to true if "read/write enabled" is checked
I presume you can blit the texture into a new texture that is marked as readable, though.
yeah exactly
mildly surprised you can't just ask to have the data copied back from the gpu
you can
In my case, there's no need to send the data to the gpu. I'm creating a color palette replacer asset. right now each time user will have to enable read/write for the texture.
you only need Read/Write if you use GetRawTextureData. GetPixelData should work fine
it's not working.
This method returns a NativeArray<T0> that points directly to the texture's data on the CPU and has the size of the mipmap level. The array doesn't contain a copy of the data, so GetPixelData doesn't allocate any memory.
if the data isn't stored in main memory, then this would not work
the premise here would be:
- load the old (non-readable) texture
- create a new (readable) texture
- blit the old texture into the new texture
GetPixelData does not have that restriction
just checked. throws an exception
UnityException: Texture 'Icon' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.
not documented then
the data does not exist anywhere in main memory, so it is impossible to read it.
it would be useful if it explicitly mentioned isReadable, yes.
it looks like this only copies data on the cpu side if both textures are readable
yep, needs GPU textures to bypass this
you can use Texture2D.ReadPixels to copy from the current render target to any texture, which will let you pull data out of the gpu
I'm loading a scene and trying to run some initialization logic right after, but it happens in a weird order:
Debug.Log($"Loading scene");
var operation = SceneManager.LoadSceneAsync(sceneIndex, LoadSceneMode.Single);
yield return new WaitUntil(() => operation.isDone);
Debug.Log($"Loaded scene");
```And I get this order of events:
- Loading scene
- Start is called
- Loaded scene
Also tried callback but no difference```cs
Debug.Log($"Loading scene");
var isDone = false;
SceneManager.sceneLoaded += SceneLoaded;
SceneManager.LoadSceneAsync(sceneIndex, LoadSceneMode.Single);
yield return new WaitUntil(() => isDone);
Debug.Log($"Loaded scene");
void SceneLoaded(Scene scene, LoadSceneMode mode) {
SceneManager.sceneLoaded -= SceneLoaded;
isDone = true;
}
You're probably getting punked by the timing of the coroutine.
WaitUntil will check the condition after Update and before LateUpdate
So it will only allow the coroutine to proceed after Update is completely over (which means it'll be after Start runs in the new scene).
I do not know exactly when the scene actually gets loaded.
ill try async await
it is before
will OnCollisionEnter() also be called if a child object wich has a collider hits another collider ?
if parent has rigidbody iirc it should
I have a scroll rect canvas that contains some inner objects, it appears that the rect raycast target is in front of the children objects sitting in the masked canvas of it... is there any way to have IPointer events from the children trigger in this setup?
Is there a way for me to have a const/static/other way to make a variable global gameobject, that is in the scene? I have the main camera on an "arm" that is on a "swivel" to make a third person camera, and I want to be able to access the camera's "arm" and "swivel" like I would the camera with Camera.main
try a singleton instance?
you'll want to use static somewhere, yes
so the scroll rect is blocking you from pointing at its children?
yea that's what im observing in the EventSystem
if i move the removalcardUI object out of the deckviewer (and disabled it), the Ipointer events work on the card
i guess I could go with the old input system like OnClick? i'd rather not have to do that though
moved to UI
ah, that'll do it
hey guys, I've got a very simple editor build script that builds for Windows, Linux and Mac with a single click, but Im running into a problem where for Linux, Im getting "cannot find clang.exe". The caveat is... if I manually switch the build target to Linux and build (either using my own script or the build button from unity) it works as expected... anyone has run into this issue before? (using Unity 2020.3.25)
SuperUnityBuild is perfect for this kind of thing, btw
but if you want to track down the bug in your own script, are you sure you're correctly changing build targets in your script?
Im basically just calling "BuildPipeline.BuildPlayer(options);" where the options set the target to be StandaloneLinux64, its as basic as it can be. I dont switch the editor platform because that interrupts my own script from running lol since the editor reloads
hi can some1 help me pls? i have problem with paint texture when i use it unity gets super slow.
hm, yeah, I'm looking at how SuperUnityBuild does it, and it, ultimately, just calls BuildPipeline.BuildPlayer
I don't know much about build scripting unfortunately
Perhaps Unity is setting a $PATH variable depending on which editor platform you're set to?
dunno.
Currently having an issue where my vertical mouse movement is not rotating the camera up or down. The horizontal motion is working, just not the vertical.
float mouseY = Input.GetAxisRaw("Mouse Y");
if (Mathf.Abs(mouseX) > 0.0f || Mathf.Abs(mouseY) > 0.0f)
{
Vector3 rotation = new Vector3(0.0f, mouseX * rotationSpeed, 0.0f);
transform.Rotate(rotation);
Camera mainCamera = Camera.main;
Vector3 cameraRotation = new Vector3(-mouseY * rotationSpeed, 0.0f, 0.0f);
mainCamera.transform.Rotate(cameraRotation);
Vector3 currentCameraRotation = mainCamera.transform.eulerAngles;
currentCameraRotation.x = Mathf.Clamp(currentCameraRotation.x, 0.0f, 80.0f);
mainCamera.transform.eulerAngles = currentCameraRotation;
}
else
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}```
you're setting the main camera's euler angles
hmm
I wonder if the euler anlges are actually winding up ranging from -180 to 0 or something
you should log them to see what you're getting
Modifying euler angles like that can cause surprising results.
Wait, could it be that I have the rigidbody's rotation frozen in that direction?
you never unfreeze it
so perhaps
the rigidbody will already be unhappy that you're setting the transform's position and rotation directly, mind you
well, just the position
That didn't make a difference unfreezing the rigidbody
Log the value of currentCameraRotation.x before you clamp it
Rotating on one axis can mess with the euler angles on all three axes
I always store the desired pitch and yaw, and then construct a rotation from those values
Nothing is getting logged. Just getting "NullReferenceException: Object reference not set to an instance of an object
PlayerController.Update () (at Assets/Scripts/PlayerController.cs:50)" in the console lol
well, then figure that out..
It's referencing mainCamera.transform.Rotate(cameraRotation);
then mainCamera is null
Ohhhh, wait I just realized I'm an idiot lol. I haven't assigned anything as the "maincamera" and the only reason I'm seeing the camera move is because the camera is a child object of the "player" object 😅
that'll do it :p
Also, you probably want to make that the local euler angles
not the world-space euler angles
since you're tilting the camera up and down
Now I'm getting some funky stuff happen lol I think it's due to the camera being a child object of the player. I'm gonna play around with that and come back for some more help later. Thanks
That much is fine.
A pretty common strategy is to parent the camera to the player
then rotate the player around the local Y axis and the camera around the local X axis
I'm guessing your problem is that you're using transform.Rotate to rotate the camera
well, more specifically
not using Space.Self
transform.Rotate(cameraRotation, Space.Self);
you want to rotate the camera around its local X axis
X is right
so that will tilt it up and down
If you rotate it around the world X axis, it'll rotate in all kinds of directions
in fact, in this situation, you could just directly edit the localEulerAngles of the camera
mainCamera.transform.localEulerAngles += rotationDelta;
is there a way to make physics2D sync transforms fpr one gameobject/collider? I want to call collider.bounds during initialization, but the position is totally wrong because it hasn't been synced yet to its transform
hey so is there ANY way for me to have an ETC render texture? I plan to write to it through a compute shader that does the ETC compression so its fast, but I need it as a render texture as I cant afford to have the memory cost of having both the render texture and a texture2d hangin out(plus the texture2d will take up space on both the CPU and GPU, doubling how much memory it actually takes)
I already have the rendertexture and texture2d at rgba32, but since they are 16kx16k textures, thats still 2 gigs for just the entire texture2d...
they are so large as they are atlas's I create on the fly during play since unity doesnt have any way to send an unknown amount of textures to a compute shader at once
Ive got a couple classes in a namespace, and im trying to reference one of the classes thats not the main class, how can i do that
how to call something from another namespace? Just include it at the top of your script.
not sure what you mean by "main class" here
the class that matches the name of the file
i am
that's only relevant if you want to be able to use the class as a component
Unity will look for a class whose name matches the file
well i need to be able to use it as a component
then you need to make a separate file
i think
this has nothing to do with namespaces, btw
Don't stick monos in the same class
i dont
no support for that with the editor unfortunately
i have multiple classes idk what its called but i have it like class : mainclass so the only mono is the main class
would be nice cause I have like 100+ scriptable objects in such small scripts :(
put them in separate files
man i was trying to avoid doing that
well, you can't
more files is better than more problems
ill just put them back into the same class
single giant files generally cause more problems than they solve
least i dont have to put 50 scripts on a object or wtv
anyway, I’m trying to troubleshoot issues with querying Collider2D ‘s bounds. The two main problems are: size is zero if disabled, and it can be desynced from the transform.
is there a way to accurately and reliably calculate the bounds of a collider?
I don't really understand why unity complains about scriptable objects being in a single class. You're using the asset menu attribute to define what SO you're creating an instance of anyway.
and usually you want your data files to be somewhat together
Using Hinge Joints it happens that I can only trigger the door opening once. After it's finished moving I can't interact with it anymore. Any idea why that is? I can't find an option that gives me a way to interact multiple times with a door
Unless your joint is destroying itself (due to the settings on the component) what you're describing is caused by something you coded and not the joint itself. Show the interaction code
I have no interaction code - I just added the joint and am moving via my Character Controller (+ extra rigid body) towards it
The settings on the hinge joint then are probably applying too much force for your character to move it then. Try playing around with the settings, even just manually putting the force down to 0 when its stuck and see if its moving
It's quite weird to describe. I have limit -90 to 90 so make it open in both directions. If it hits the first limit I can go around it and "push" it to the other limit/side. After that it won't move anymore. Also if I keep pushing it lightly (not reaching the limit) I can bounce it forth and back forever. It just stops as soons as it hits a limit a second time
also now removing the limits I try to go around it and push it back and forth. At some point it goes harder and harder and then stops to move completly
oh man nevermind
Im unsure since that's not default joint behavior, maybe something else is moving so that its hitting a limit
the stupid rigidbody I have attached is actually physically moving away each time I use a door
I need to make it kinematic
sorry
No need to be sorry, joints are quite weird to work with
Hi, anyone know anything about how Steammanager works? whenever I build my game and load a scene that has the SteamManager prefab in it with the SteamManager Script, the game just crashes.
when are querying the collider? in Update or Fixed?
in start
just for that one frame?
if you copy and run the code just one frame in Update, does the same problem occur?
does calling Physics2D.SyncTransforms do anything?
or you could sync the transforms. ah, beat me to it . . .
Calling SyncTransforms works. But it affects EVERYTHING in the scene. And there isn’t a more localized option.
ouch . . .
it wouldn’t be such a problem if I could just request a sync of a single transform as I need it.
I'm surprised they don't have that option . . .
public abstract class EntityModification<SO> : Storable<SO>, IEntityModification where SO : EntityModificationSO {}
public class AbilityStatMod : EntityModification<AbilityStatModSO> {}
public class AbilityStatModSO : EntityModificationSO
{
public override IEntityModification Construct(IEntity entity)
{
return new AbilityStatMod(this, entity);
}
}
public class ArmorItem
{
public bool EquipItem()
{
foreach (EntityModificationSO mod in Modifications)
{
//Can't do this because it's abstract
//var newMod = (IEntityModification)new EntityModification<EntityModificationSO>(mod); <----
var newMod = mod.Construct(IEntity entity); //Works fine
newMod.AddModification();
}
.....
}
}
Does this implementation seem off? I'm not too sure how to solve this otherwise.
Instead of invoking new, I construct it from within the SO because I override a method and return an interface
No clue how I got myself into this position
Yeah, that's probably it unless I make the base class non-abstract, but instances of the base would make no sense. Unless there's a way to do some shennanigans with gettype, but I doubt that works since that's all runtime stuff.
is there a way to make retrace lines show in the screen in unity 2d?
rarytraces, you mean?
I want to move like Vector3.Slerp, but with a fixed distance, not a lerp percentage. Any ideas on how I'd do that?
If I could calculate the length of the slerp, I could easily calculate a t value.
I guess I could just sample a few hundred points and call it a day.
you know. i might also just make it so that I tell it how long the move should take, rather than actually setitng a speed
that avoids the problem entirely
need help with a boomerang im creating. It goes out like fine, but doesn't go back to the player. Any way I can do this?
{
[SerializeField] private GameObject particleOnHitPrefabVFX;
[SerializeField] private float projectileRange = 10f;
[SerializeField] private float returnTime = 0.5f;
private float moveSpeed = 22f;
private Vector3 startPosition;
private float state = 1; //if state is 1, then it is away from player, if the state is 2, then it is coming back to player
private Vector2 currentPosition;
private void Start()
{
startPosition = transform.position;
StartCoroutine(BoomerangStateRoutine());
}
private void Update()
{
MoveProjectile();
StartCoroutine(BoomerangStateRoutine());
DetectSwitchState();
}
private void DetectSwitchState()
{
if (Vector3.Distance(transform.position, startPosition) > projectileRange)
{
state = 2;
}
}
private void MoveProjectile()
{
transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);
currentPosition = transform.position;
}
private IEnumerator BoomerangStateRoutine()
{
//if state is 1, do nothing
//but if state is 2, lerp back to start position and destroy the gameobject
if (state == 1)
{
yield return null;
} else if (state == 2)
{
transform.position = Vector2.Lerp(currentPosition, startPosition, returnTime); //go back to original spot
Destroy(gameObject);
}
}
}```
Time to debug
Have you made sure that it's changing states and that you're changing the direction that it travels after.
I know its changing states but im not sure how to change the direction back
transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);```
So you're constantly translating, even when you go into state 2, which is fine, but you also lerp in your state2 there to go back to your postion
ohh ok i see
what for (im kinda stupid lol)
i dont think translate works the same way as setting the position. it synchronizes the whole motion
just setting position is a single frame command. if you want to move with the position you need a for loop for the lerp
ok
oh yeah where are you updating the lerp time or am I blind
either way ya probably one to stick with one method
yea you could try translating instead if you dont want to lerp it
i think one liner without for loop would work in that situation
ok thanks
I have a case statement inside a for loop (not in code sample) and I'm trying to WaitUntil another MB returns true... however, I never get the response from the other MB inside the loop, and the loop just exits. I'm stumped as to how this can happen?
case "SCRY": scryUISelector.isComplete = false; handManager.Scry(Int32.Parse(item.Value)); yield return new WaitUntil(() => scryUISelector.isComplete); Debug.Log("ending scry"); break;
the Debug line never prints in the console. I watch the isComplete turn to true
I suggest just forgetting the coroutine right now and just move the boomerange to the location you want, switch the state, then do the same backwards.
coroutines good for if say you're tossing 20 boomerangs and stuff like that
ok cool
ill try that rq
If the debug never prints, then the execution doesn't continue in that method. Is that a proper coroutine? Could it be that it's stopped(for example due to the host MB being disabled) before completion?
I am absolutely braindead, thanks
I didnt make the other MB's method a coroutine
oh wait
i dont have to do that
huh
So yea, the method calling the for loop & switch is an IEnumerator. The method from the ScryUISelector is not IEnumerator
Is the code running at all? Put a log before the WaitUntil
yeah it is
debugger line goes up to the Scry method, then i go into the other and watch isComplete = true
it isnt stuck in an infinite loop either
idk if my debugger is just being weird
but, the for loop definitely terminates early, there are more actions left for it to process that it doesn't do
and if I remove the WaitUntil line, those actions do process (just out of order)
ok i think it's what dlich originally said, i didnt realize the caller of the Coroutine may be disabled by this point in time
Alright guys? I'm using multiple colliders like this to detect things like the player and objects, etc. Is it possible to also detect which are overlapping with those colliders and return a list or something?
Which tiles* are [...]
Not sure I understand the question, but I assume you just need to separate your colliders onto different objects. Then associate that new object with a tile, because right now you'll have no distinction between which collider was hit
Hey guys so im working on a player movement script for and im wondering if its a better practice to manipulate Rigidbody.velocity directly or to stick to Rigidbody.AddForce() .
I feel like using AddForce() is a better decision for the long haul but its gonna be a lot more work for making the controls feel snappy
yeah that's true, i think im gonna primarily try to use forces though. that way i can have the player be affected by explosions or other physics objects. I'm having to get pretty creative with it though lol. like for stopping the player instead of using rb.velocity = Vector3.zero I ended up having to use rb.AddForce(-rb.velocity, ForceMode.Impulse);
it should be -rb.velocity*mass? impulse uses mass
i have my mass set to 1 so i didnt notice! i appreciate that
Do state machines and ai behavior trees function the same way? Are behavior trees just a node version of a state machine?
Hey, so I've been having trouble trying to fix this error (InvalidCastException) that keeps occurring (Shown in the screenshots) and I have narrowed down the location to the coroutine "ProcessDeathEvent" however, this should not be the case as the same coroutine works on a seperate game object with similar components. Linked below are the areas of code surrounding the bug
Process death Event Code:
https://hatebin.com/hsyzqnnagn
https://hatebin.com/qfwqaalpau
Check HP (Coroutine running) Code
https://hatebin.com/obygppcdjb
Could I get some help with this please?
What makes you think that the coroutine is relevant to the issue?
Agreed, nothing in that stack trace seems related to the provided code. It seems to be an issue in some netcode editor scripts
Can someone tell me if this is wrong and has an error or right (this is a player wasd movement script
Hi, I would like to use Debug.drawray to debug a specific frame of my ingame logic. I use Debug.break to pause the editor at specific frame, but I see multiple rays... how to clear the old rays?
Currently trying to implement a jumping function into my game. I'm using a raycast to check if the player is grounded, and if so then when the player hits the spacebar it jumps.
Debug.Log(isGrounded);
if (isGrounded && Input.GetButtonDown("Jump"))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
Debug.Log("Jump");
}``` The raycast shows true, however the if statement condition aren't getting satisfied. I have "Space" configured as the positive setting in input for "Jump"
The Debug check for "isGrounded" does show "True" at the time I am pressing space.
you need to pass a keycode, not a string
I've tried passing a Keycode for "space" but that just throws an error saying "Space isn't configured"
oh. sry. i stopped using the old input system 3 years ago
do Input.GetKey(KeyCode.Space)
although, assuming your input settings are correct, or even the default ones, idk why Input.GetButtonDown("Jump") wouldn't work for you so it might be something else
It might have been working, I just wasn't seeing "Jump" being printed cause "True" was getting printed so rapidly. However, I did see "Jump" for sure when using your recommendation. My player still didn't jump though, but that could just be changing force variables
in that case ur probably better off with the initial code haha. unity's input manager is pretty convenient.
Hey guys... Is there a way to import the binaries to unity without sending with it the source code?
My problem is a designer that insists on messing with the code.
Yup, that was the case. I just changed the "jumpforce" to something crazy and yeeted my character lmao
Sure, you can build your code to a dll and then he can import that into a Plugins folder
yeah oftentimes the most frustrating issues end up having the dumbest solutions all along xD
oh i meant to reply to killer3p0 (im losing my mind)
That's a good idea.
Not sure it is doable right now, but might consider for the future.
The whole "it just added a serialized variable" is pissing me off so much
Currently well in over my head trying to understand projection matrices (in general but specifically in regard to cinemachine virtual cameras). I'm trying to get the frustum of a virtual camera, so I can check if a world point is within the frustum. My approach so far has been to try and get the 4x4 projection matrix of the lens and combine it with the local transform matrix to get the frustum.
In my head that makes sense but I have a feeling this is completely wrong.
Here's code of the class and the grid system it uses: https://gdl.space/papavaqeka.cs
Ignore the disgusting length of the function, I start messing with getting the matrix at line 112 of CameraManager.cs
Matrix4x4 vcamFrustumMatrix = GetVirtualCameraProjectionMatrix(vcam);
// Combine with camera game object's transformation matrix
vcamFrustumMatrix *= virtualCamera.transform.localToWorldMatrix;```
Have tried researching thoroughly, any help on how to approach please! Also if this should be in beginner please let me know
How can I do mesh subtraction during runtime?
you're still working on cutting holes for caves in your terrain, right?
Yep
yeah, I haven't got a good idea of how to pull that off in unity in particular
I found ways to do it using the editor, but not during runtime which is important bc of my procedural generation
This is a mesh-based terrain
one mesh for overworld terrain, one mesh for a cave system
that's my understanding
ohhh mb then
It sounds to me like you just need to subtract the cave mesh from the terrain mesh, but I have no idea how you'd accomplish that in Unity
That wouldn't make sense as the terrain isn't solid and is hollow and the cave mesh is placed below it
oh, do you need to carve a path into the cave mesh?
I would plan on randomly spawning a hole prefab that has a script to cut through meshes
In that case it'd be a similar premise, but cutting both meshes
yes
Is this something that I could use?
https://forum.unity.com/threads/booleanrt-realtime-3d-boolean-operations-for-runtime-editor.157009/
i'm imagining doing this
Yes exactly like that
But I need it to happen inside of unity during runtime
I am getting CS1001: Identifier expected in "KeyCode" part of the code. How do I fix it?
{
index++;
}```
That is not valid syntax.
but it is valid
I can assure you that it is not.
. is the member access operator.
It may only be used with a literal name
Foo.Bar.Baz is valid
If you want to store a list of cheat code keycodes, why not just make an array of KeyCodes?
Then you could do Input.GetKeyDown(cheatCode[index])
I did try that but it led to like 10 errors
well, then perhaps ask about those errors
sup nerds
gottem
consider reading #📖┃code-of-conduct before proceeding
do you also want to get muted?
"error CS1922: Cannot initialize type 'char' with a collection initializer because it does not implement 'System.Collections.IEnumerable''
"warning CS0219: The variable 'index' is assigned but its value is never used"
"The name 'cheatCode' does not exist in the current context"
then stop spamming the channel with nonesense
Share your !code .
📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
You've got a number of separate problems here.
spamming, i don't see it
This code does not include an array of KeyCode.
You declare cheatCode in Start, it doesn't exist in Update
Edit: and index too
also, I should point out that this just declares cheatCode in Start
you initialize it in local scope
interesting code
it should be class field
Local variables die when the method exits.
more specifically, they die when their scope ends
in this case, that happens to be when the method exits
So, yes, move that array out to the class
and use KeyCode!
KeyCode[] cheatCode = new KeyCode[] { KeyCode.C, KeyCode.H, KeyCode.E, KeyCode.A, KeyCode.T };
that oughta do it
now you can just check if Input.GetKeyDown(cheatCode[index])
You cannot construct a name at runtime like this.
Alright, it works now but I'm getting an error after I have entered it "IndexOutOfRangeException: Index was outside the bounds of the array."
hi is there anyway to make many game object form shapes? for example i want to make many cube form a heart shape, i mean sure i can do it manually but is there any other good alternative instead of doing it manually?
you're trying to use an index bigger than ur array size
remember arrays start at 0 index
so 5 elements is #4
etc
I'm guessing this happens after you push all five cheat keys
sounds like you need the animation system?
You will want to check if you've hit them all and stop trying to index the array
Unity's Splines package can help you instantiate objects along a path.
how would you do a sequence of certain order pressed xD
if (Input.GetKey(codes[0]))
{
if (Input.GetKey(codes[1]))
{
if (Input.GetKey(codes[2]))
{
if (Input.GetKey(codes[3]))
{
if (Input.GetKey(codes[4]))``` ?
nah, just increment the index
press c -> press h -> press e -> press a -> press t
-> IndexOutOfRangeException
boing
ahh
Yes, but when I press d (which is not part of the array) after I entered it, it gets treated as a key from the array. I have else to set index to 0 for that reason but it does not work after I entered the code.
In general you'd use a state machine
ah, so you want to reset if you push the wrong key
Write code to do it?
Sounds reasonable enough. Show your new code.
yea i suppose if its a cheat sequence thingy
it was always in the code
if !getkeydown will reset the index
this would instantly reset index to 0 if you didn't happen to push the current index's key that frame
that sounds wrong
perhaps you wanted GetKey?
so that you have to press and hold the keys
C
CH
CHE
CHEA
CHEAT
I tried doing this before, but it was to many inputs for Unity to handle since it didn't work, but 3 worked fine
your keyboard might also not handle that many keys
If you want to reset progress if you push any other key, then you'd have to check for quite a few different keys
that is also a posibility
I don't think there's a convenient way to do that with the old input manager other than checking each keycode in sequence
I would just make it so that you have one second to push the next key
if you run out of time, it resets
Idk maybe I'll convert it to the new input system, but this is what my teacher uses
So I got used to it by now
I got a big brain moment and it works, I just set the index to 0 after the cheat has been activated
thank you all
how to do it? did you have any link to help me creating the code?
you need to calculate points on the edge of the shape.
How are you imagining creating these shapes?
Do you want to be able to use a picture? Something you draw in the editor?
If you specifically want to do math shapes, then you want a parametric equation: something that tells you x and y given another variable (usually called t)
you would sample the equation at a bunch of t values and create objects at them
is int? serializable by unity?
No nullable types are not serializable by default
Can make your own nullable type if you want
The rules for serializable types are clearly listed here:
https://docs.unity3d.com/Manual/script-Serialization.html
I'm using this to detect if the player is touching the ground. However, when the "isGrounded" never goes false even after the player jumps and is not close to the ground. isGrounded = Physics.Raycast(transform.position, Vector3.down, groundCheckDistance); Should I be using a collision check instead of raycaster?
it might be touching some sorta trigger collider
or the player's collider
you can use layermasks to prevent that from happening
Oh, I do have a capsule collider at the players feet
I am not
Should i explain, or will u look it up on ur own?
I can look it up lol
Oki then, hope that helps!
It certainly does, thanks
Its the first time i got this error lol
seems like i accidentally made some number go beyond its limit?
am i getting it right
and i have no clue what the heck AABB a is, does anyone know?
So LayerMasks is the reason why I should be using different layers with all of my gameobjects
Thank you 
Kinda
doesnt mean you have to use a diffirent layer for every object, its good to generalize
Oh boy do I have a lot to edit lol
by the sounds of it, you are making a platformer, right?
and you want most of the objects with colliders to be considered ground
layer masks are really useful
ikr
Nah, I'm making an FPS shooter. But I don't want my character to be able to jump again or move if they're already in the air
oh
I have different categories for layer masks. With layer masks, you want the collision matrix not to have two layer masks that are identical
but yeah, regardless, you can just give all the things that u should not jump off a layer separate layer
or do the opposite, make the layer only for ground stuff
Do layer orders matter?
layer masks I have in my game: Terrain, Enemy, Entity, Player, CameraSpawner, CameraDespawner, EntityIgnoreEntity, EntityIgnorePlayer, SolidEntity, OnlyTouchEntity…
if all the non ground objects have triggers, not colliders, you can just use 1 line to ignore triggers in your detections
sorting layers yes. LayerMasks used for collision no
sorting layers tell you how sprites render on top of each other
Ahhh, okay
a layer mask as a 32 bit integer. Each bit (0 or 1) correspends to if you are checking for a specific layer collision
oh whaat
So a layer "Concealment" can be any where in the layer list and bullets can pass through it as long as I call it properly
so if terrain is layer 1, and player is layer 5, a layer mask of 000…00010001 might mean we are looking for objects in either Player or Terrain layer
basically a bitwise enum
0_o
there’s a little inaccuracy in my explanation because of layer #0 etc, but that is the basic idea
this way you can do bitmath.
I had so much headache with detecting specific layers, and all that time i could've just used integers
yeah, you need to change stuff in the project settings too
you can make certain layers just not collide with each other
This just made my life easier cause I was wondering how I was gonna do that
So let’s say I want to make a layer override to allow a given entity to actually ignore the player now. I could get a layermask for player (0000…001000), then say: excludelayers |= playerMask
i mostly used layermasks for certain specific lines of code, so i didnt have to deal with the matrix
or stop exculding player by excludeLayers &= ~playerMask
you want to use the collision matrix
no, not always
collision matrix makes the physics system automatically not check for collisions between different layers
i have my reasons not to use it
which is much cheaper
you should use it. and then you can add overrides to specific colliders
but if you use the collision matrix, you don’t need to specify a bunch of specific overrides for every single collider you make
you could avoid collision matrix, and just put layer overrides
but that’s just a lot more work in setting overrides
I usually dont need objects to straight up ignore some colliders, i usually use em to check if thats the specific collider im looking for
ignoring a collider is cheaper, because the physics system doesn’t need to start sending callbacks
yeah but then my game wouldnt work in the way i want it to
your collision code should almost always ALSO check for layer when handling collision
but for example, my player has no business colliding with a camera spawner.
I don’t even want to compute that collision. and i don’t want to deal with that callback being called OnTriggerStay for no reason
ig i'll look into that, cuz i do have some cases like that
in general, you want to avoid collisions between layers that have no business being involved with each other
mario’s fireballs do not need to check contact with mario, at all.
boos don’t need to check collision with ground… at all.
so instead of having a collision, and telling it to specifically ignore in the callback… just don’t have a collision
I there an easy way to mass select objects?
you can search for objects with a specific component on them
t:Foo will find every object with a Foo on it
oki, thanks!
I mean in the editor so I can change their layer
yes, that's what I'm suggesting
you can do that search in the hierarchy
sure. and ALSO check the layer in the collision callback.
I'd everything back to normal
Oh lol
That syntax works in both the project view and the hierarchy
You can then ctrl-a in the hierarchy
i just did that manually lol
using UnityEngine;
public static class LayerMasks
{
public static int entityLayer;
public static LayerMask entityMask;
public static LayerMask arenaMask;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void Init()
{
entityLayer = LayerMask.NameToLayer("Entity");
entityMask = LayerMask.GetMask("Entity");
arenaMask = LayerMask.GetMask("Arena");
}
}
it basically lets you make a class called Layers and Tags with machine constants for individual layers, layer masks, and tags
automating it is probably smarter...
just download a package lol
It makes your code look like:
if (collision.gameObject.layer == Layers.PLAYER) {
or collider.excludeLayers |= Layers.TERRAIN_MASK | Layers.PLAYER_MASK
which also makes it super easy to find code that depends on specific layers
ok but what if I stubbornly did it myself in a way that's worse
huh? what then?

Well adding "LayerMask.GetMask("Ground")" to my raycast has now broken my player movement completely.
Maybe this means I should finish watching the tutorial
how could i check if a file is in the assets without throwing a error if it isn’t
i cant assign the file to a variable because if it isn’t in the assets there’s no file to assign the variable to, and it won’t detect the type
a that obv means i can’t just put the type into a if statement and call it a day because well same issue
i'm guessing you mean, how can you check if a C# type is available from a script that may or may not be in the project?
look up File.Exists