#๐ปโcode-beginner
1 messages ยท Page 840 of 1
Showing screenshots of the setup of the gun and the firing point in the scene would help
Including the inspector for this script
Inspector for enemy, enemy scene setup, and video
I have the exact same setup on the player, the only difference is that I use Rotate() on the player to move with arrow keys and LookAt() on the enemy which is why I initially though that was the problem
Why are you using FindGameObjectWithTag for the parent instead of a direct reference (like you did for firing_point)? Doesn't each tank have its own shell container? Or is it shared between tanks..?
It's in the level, I'm used to Godot so maybe not necessary here, but in Godot if you didn't reparent to an empty in the level, turning the tank would turn the airborne shell too if it's still in the scene.
I could do a direct reference
even in godot you can "serialize" references right?
using tags/names are the less ideal solutions
its a prefab, I'm guessing they need to find it runtime on spawn? but should use awake/start or pass it directly on spawn instead of every Shoot()
I see, well, you could also just have no parent at all, unless you want to keep it like this for a reason
godot parents a spawned object by default ? oof
Also I gotta ask, does the tank have an animator?
It does not
Yeah, unless redirected when instantiating
wild but yea if the thing is external to the prefab just perform some setup post spawn
Does the shell use a rigidbody, maybe it is colliding with the turret that's shooting it?
right, but does it have a Rigidbody?
It does not
Yeah I posted it above
Unless you use Raycast or something, thats bad way to do detection if you want accuracy
Translate is essentially teleporting it (OnTriggerEnter works with physics) you're in a draw of the luck if it ever does detect it w/ translate, assuming the tank has RB
indeed, that'll need to be fixed later
Yeah
The healthbar for now (until I fix it) is just a child of the main tank body
tis beginner channel probably not something that was solved yet ๐
in play mode, pause the game and select the enemy's FirePoint object
ensure that your scene view is set to show local handles, not global handles (check the top-left corner of the scene view)
the arrows should align with the barrel of the gun, and as the turret rotates, they should rotate with it
healthbar.transform.LookAt(camera.position) :p
if you want up and down locked
var pos = camera.position
pos.y = healthbar.transform.position.y
healthbar.transform.LookAt(pos);```
might need to flip the healthbar parent
I'm asking because it might be related to the issue, not trying to steer away from the actual problem
I haven't locked it to the y axis yet so it does dip but even then it should still spawn from the firing point even if it fires down
that looks valid (for a bullet that travels in the -X direction!)
the red arrow points right
next: pause the game after the enemy shoots and select the bullet that it fired
It could be an issue like:
Update -> Something resets the turret rotation
Update -> Shoot (in the wrong direction)
LateUpdate -> Set the actual turret rotation (which is what ends up rendering)
But i'm just speculating
there are a lot of possibilities, yeah
it would be helpful to see the entire script
!code
๐ Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
๐ 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.
please use the pasting sites when sharing entire scripts
a paste site will make it easier to browse, ye
!code
๐ Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
๐ 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.
you didnt do anything different now
look at the bot message
5 unmissable links right at the top
pick one, preferably the third one, copy and paste your script there
and share the link here
hm, it looks like the bullet's world rotation doesn't quite match the shooting point's rotation
That's what I just pasted...
you pasted a .txt
you wound up pasting the entire script directly into the chat
not a link
the site might have misbehaved
wait did the list change again
Yeah looks like that isn't actually copying
it was 6 like last week wasn't it
This was pastes.dev
copy from the url bar
i think pastes.dev is so far the best but it's certainly not perfect unfortunately
Assuming that the "Shell Container" object is un-rotated, this rotation is weird. The enemy tank is rotated towards the player by more than 4 degrees
Yep, and that is evident from it moving in the wrong direction (via Translate) anyway
public class Tank_controller : MonoBehaviour
{
// ------------- Variables -----------------
[Header("General Variables")]
i'm suspicious of this line
turret.rotation = Quaternion.RotateTowards(transform.rotation, target.rotation, rotation_step);
This is starting with the tank's rotation and trying to align it with the target's rotation, then using that to set the turret's rotation. That doesn't smoothly rotate the turret at all (it's just going to make the turret align with the tank, with a slight bias based on the target's own rotation)
However, the tank can't fire without first calling turret.LookAt(target);
Ah yeah that was trying to figure out why LookAt wasn't working and look for other possible solutions online
Oh I see I was looking at the commented out code
That one is supposed to be the tank I must've used the wrong rotation when setting up the navmesh
Yeah that was it...
The NavMeshAgent is going to be setting the rotation of its own Transform constantly
I must've replaced the wrong variable at some point as originally the turret wasn't being used
but that's impossible! the turret gets pointed directly at the player afterwards, and you the instantiate a bullet in the same function; there is no time for anything else to interfere
Attack being called in two different places seems off to me
Oh, duh
I didn't see Attack there
yep, that's the issue
turret gets rotated weirdly, Attack is called
Yeah because it can't attack for a short while again
and then the turret gets rotated correectly immediately
Almost this ๐
Thanks a lot!
I've had similar issues (on a larger scale) while dealing with interactions between IK, ragdolls, physics, ...
So it was updating rotation with navmesh, attacking, then because I set it up to have a delay before it can attack again, the actual turret turning attack didn't get called
Yeah, the Attack() call after the turret rotation could only succeed if the enemy could not see the player
but, if the player isn't visible, that can't be reached anyway
Black dots are units, red lines are the path, green is the formation they are commanded to enter into. I am not smart enough to rely on my own knowledge. Does anyone know what i could tell an AI or at least what math formulas would fix this multi agent path finding for me.
could probably weigh for the closest position that isn't taken?
Hello, Looking for a Level Designer / Environment Artist
Hi everyone! Iโm currently developing my own game and Iโm looking for a talented level designer to create a custom map for me. I have a reference map layout and a specific vision in mind (similar to Ranch Simulator style).
If youโre interested or can recommend a platform/artist, please let me know or DM me. Iโd love to see your portfolio and discuss the details!
would be a naive approach thay would probably be ok-ish
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โข ** Collaboration & Jobs**
Already tried that and it was so scuffed. Its on a grid and units cannot be on the same space at the same time. I still dont get how its a problem if the agents are aware of each other's path so they dont clash movement
Ur right, it just wasnt smooth enough for me to be happy
is movement on a grid?
my mistake i already described it in here before idk why i assumed people knew that
If I'm planning to use raycastall for mouse position (Sort of like onmouseover but for everything the mouse is over), is it best to have it be a singleton and just grab that array from other methods when needed? I'm assuming yes?
do they have some kind of central manager or do they have to figure this out themselves as emergent behavior?
"best" has many meanings. better for perf, maybe, depending on if you cast unconditionally or not. better for spaghetti code, potentially, depending on how it's set up
figure out the system design you want to have, how it'll interface with other systems. draw on paper or in diagram tools if it helps
i was trying to overall say "impossible to say what's 'best'" but i did that poorly. mb.
no worries! I'm worried specifically about performance here
It's kind of a silly/simple question but I was just checking since I am newish to raycast stuff and want to make sure there's not like common knowledge I'm missing here
Sounds like you're asking if you ought to use a Singleton to share data. The physics raycast method can be called from anywhere.
Its a deterministic system so central is basically a requirement. they are requesting pre-calculated routes from the system that understands the 8 tile grid that surrounds them. (Frankly i dont even know how an emergent system would work, seems to be a bunch of float numbers i think). The units move mostly by throttling and path budgeting
I basically want a replacement for OnMouseOver, since it's kind of picky about overlapping colliders and such, I want an OnMouseOver for anything the mouse is over, and I'm trying to find the most efficient and easy way to achieve that.
A few Ideas I have for that is having like an interface for anything that may have behavior when the mouse is hovering over, and calls the functions in that if it has that property. Another would be having a raycastall on all of the scripts that may need it but that seems pretty bad/inefficient, and I feel there is probably a more elegant solution
I'd worry about efficiency later. This looks like micro optimization in the grand scheme of things. Just use whatever works for you.
Ah okay, thank you!
"emergent systems" just mean systems where complex behavior of a system emerges from simple behaviors of individuals without central management, like ant colonies
what about figuring out which positions are closest to which units, starting with the position that's farthest from all units?
oh, this might be quite inefficient
Just as a good reminder, you can make thousands of raycasts per frame and be fine. Consider not having to allocate a new array every time though as GC will be expensive.
i guess i could try something like that ive just been trying to limit those kinds of things as much as possible because of lag
ideally it'd be O(n^2), what i'm suggesting would be O(n^3)
it'd something like this
while remaining positions:
for each position:
find nearest unit
"targetPosition" = find position with farthest "nearest unit"
"targetUnit" = targetPosition's nearest unit
targetUnit goto targetPosition
remove targetPosition & targetUnit from pool of consideration
you could cache the "find nearest unit" part if the previous nearest unit was not removed from the pool
while remaining positions:
for each position:
if position's nearest unit == null or isn't in pool
find nearest unit
"targetPosition" = find position with farthest "nearest unit"
"targetUnit" = targetPosition's nearest unit
targetUnit goto targetPosition
remove targetPosition & targetUnit from pool of consideration
```(null check for the first loop)
presumably using nonalloc, right? Would I do something like,
(ignore the bad pseudocode)
if(RaycastNonAlloc() != 0) ourRaycasts = RaycastAll();
I'm not sure how I would make sure it doesn't allocate a new array, but maybe I'm misunderstanding.
Would it be allocating a new array if my script had a variable like 'hits', and the code would be 'hits = raycastall' ?
NonAlloc doesn't allocate new arrays because it will use an array (or list) that you supply
(read the docs/signatures)
i have nothing to lose at this point, ill try to implement something like this and see what it does
thank you both, I'll do some more reading and play around with it a bit
if NonAlloc would allocate a new array everytime it would defeat the purpose of nonalloc xD
anything that returns results more than 1, always opt in for NonAlloc versions
I guess I'm a bit confused on how I would use it, since it's returning an int of how many hits there are, right? I'd still need to allocate an array if I want to access those hits, wouldn't I?
You need the intial array to contain then , then yes use the amount of hits returned by nonalloc in the loop
eg
myarray[i].collider
i comes from the hits
Why wouldn't you use myarray.length?
because its a fixed size
You may iterate over missing items
so in a nutshel
RaycastHit[] storageArray = new RaycastHit[maxResults]; // i think some want a Collider[] depends on which cast
int hits = RaycastThingNonAlloc(etc.
for (int i = 0; i < hits; i++){
var itemToCheck = storageArray[i].collider // etc.```
I believe they're referring to how you're to use the returned integer. For example:cs int count = Physics... for (int i = 0; i < count; i++) ...where i may be some value less than the length of the array by design so you shouldn't simply iterate every element of the array as they may not have been used.
raycast hit 2 things but array 8 long, bad times if you check all 8
good times checking just 2
I keep getting null ref exceptions in the second loop when I'm near a wall...
When the first loop should take care of those.
//Get all nearby colliders in the wall layer
int numCollidersHit = Physics.OverlapSphereNonAlloc(transform.position, wallCheckDist, nearbyColliders, whatIsWall);
//Exclude walls that are below the player
List<Collider> nearbyWalls = nearbyWalls = new List<Collider>();
if (numCollidersHit > 0)
{
//Turn the array into a list for easier resizing
nearbyWalls = nearbyColliders.ToList();
//Check each collider in nearby wall colliders
for (int i = 0; i < numCollidersHit; i++)
{
//Get closest point
Vector3 closestPoint = nearbyWalls[i].ClosestPoint(transform.position);
//If the closest point on the collider is below the character controller then remove from list
if (closestPoint.y < transform.position.y - (controller.characterController.height / 2) || nearbyWalls[i] == null)
{
nearbyWalls.Remove(nearbyWalls[i]);
}
}
//Set num colliders hit. This keeps using num colliders hit so that if the player isn't near a wall they don't waste processing power on changing the array into a list.
numCollidersHit = nearbyWalls.Count;
}
//Check if there's still active walls after the cull of ones below the player
if (numCollidersHit > 0)
{
//The wall which is closest to the player
Vector3 closestWall = Vector3.zero;
//Find which wall is closest to the player
for (int i = 0; i < nearbyWalls.Count; i++)
{
Vector3 closestPoint = nearbyWalls[i].ClosestPoint(transform.position);
if(Vector3.Distance(transform.position, closestPoint) < Vector3.Distance(transform.position, closestWall))
closestWall = closestPoint;
}
//Get the normal of the closest wall
nearWallNormal = Vector3.Cross(closestWall - transform.position, transform.position - closestWall).normalized;
//Yes there is a wall near
wallNear = true;
} else
{
//No, there is not a wall near
wallNear = false;
}
Which line throws the nre?
the "Vector3 closestPoint = nearbyWalls[i].ClosestPoint(transform.position);" in the second loop
The fuck is this
List<Collider> nearbyWalls = nearbyWalls = new List<Collider>();
so nearbyWalls, nearbyWalls[i] or transform
transform definitely isn't it
do you have both a local field and a member named nearbyWalls
Oh I must have done a typo on that I'll remove that middle bit and see if it fixes anything *it didn't but glad someone pointed it out
nearbyWalls = nearbyColliders.ToList();
this is suspicious as well
nearbyColliders is from a NonAlloc query, it doesn't necessarily have all valid members
I have to point out there are better ways to check some array/list and pick the closest thing
i didn't know this was valid syntax!
it does check out, though
same!
you never use the variable before it's initialized
There is? How?
yeah assignments are expressions
sometimes handy for readability...
oh, I was specifically thinking about how you were using the declared variable in the expression that assigns into it
(that's not even a syntax matter)
that's just a semantics matter
oh yeah i didn't think so either
You ought to limit your iteration by numCollidersHit as well, as you're uncertain if elements are null or not - you've only checked for nulls relative to indices less than numCollidersHit.
Okay I think I see where I'm getting confused a little more.
private void Update()
{
HitsArray = Physics2D.RaycastAll(InputManager.instance.WorldPoint2d, transform.forward, 100.0f); // WorldPoint2d is the mouse position, and the object this is attached to would have no rotation.
}
In this circumstance, would RayCastAll return an array with the length of how many hits there are? It wouldn't return blank entries in that array, right?
Is this code chunk bad practice? Does it not overwrite the prior array essentially, or does it still keep that data handy/read only and cause issues?
Thank you also for your patience with me
You are re-assigning the HitsArray variable.
made up example
float closestThingDistance = 0f;
Collider closestThing = null;
foreach(var thing in things)
{
float distance = Vector3.Distance(us.position, thing.transform.position);
if(closestThing == null || distance < closestThingDistance)
{
closestThing = thing;
closestThingDistance = distance;
}
}
In this circumstance, would RayCastAll return an array with the length of how many hits there are? It wouldn't return blank entries in that array, right?
yes
Is this code chunk bad practice?
not necessarily. using the nonalloc form can be better for perf but it does require an assumption about how many entries you will receive.
Does it not overwrite the prior array essentially, or does it still keep that data handy/read only and cause issues?
yes, that's what assignment is
the data will be kept if there are other references to it, and if not, it will eventually be freed (garbage collection (GC))
Hmm I guess that it would be better to just check against a float instead of getting the float each time. And to use a for each. Thanks! ๐
@wicked stratus layer filtering might help a little but still if you call this everyframe its unecessary amount of GC for new array each time
Mmm true I'll try that.
The main takeaway is we check all things but only keep a reference to the object with the smallest distance. This concept applies to other scenarios too.
oh okay.
So to make sure I understand, say my HitsArray = [hit1, hit2, hit3]
but then on the update, the HitsArray = Physics2d.RaycastAll(...) which equals [hit4, hit5, hit6]
it doesn't get rid of the original hitsarray and that memory builds up, then? Is there a way to tell it to throw the original hitsarray away?
it won't get rid of it immediately, but it will eventually if nothing else uses it (GC)
The problem is not that the old memory is never disposed of (it is)
the issue is that you keep allocating more and more memory, which creates more work for the garbage collector
you may just want to look up a GC explainer so you have a little more context
a non-allocating method is like a whiteboard
you have to get a large enough whiteboard to hold all of the data
but you aren't creating any garbage when you put new stuff on it
allocating methods are like a printer; every time you get data, you're making garbage
on this point giving yourself a decent amount even doing 100+ items array will be less to worry about than a new one of 20 each frame
i thought this was gonna be like the alloc method taking out a permanent marker and giving you a new whiteboard every time
Note that none of this matters whatsoever unless you're doing it many times per frame
like, at all
it does not matterโข
I say this as someone who spends a ridiculous amount of time and effort minimizing allocations
fortunately, this is a situation where performance and readability aren't at odds
Use the second variant of the regular raycast.
https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
so I do like to use non-allocating methods by default when it's practical
it's not like you're making your code dramatically harder to understand for a minute gain
-# hey, it could matter if you had 1000fps but really shitty ram ๐
the usual trick of "make a static array and re-use it" works fantastically as long as it's impossible for two things to want to use the array at once
โ๐ผ โ๐ผโ๐ผ ok thank you
(or just make it a member instead of a local, doesn't need to be static)
(e.g. imagine you call a method when you detect an object, and that method also wants to do raycasts)
oh wait i may have misinterpreted "static"
It's possible I didn't use it correctly tbf ๐
(it was in fen's message)
Oh gotcha, I think it was in my original one too so if that caused confusion at some point I do apologize.
Nice I altered some stuff and it works, thanks for the advice!
You interpreted it correctly. A static array is valid as long as the method isn't going to be on the stack more than once at a time
(assuming single-threaded code, of course)
Is there anything like f3x (a plugin from roblox studio) in unity? Or any good youtube tutorial on how to properly use these horrendous default tools?
I learned about ctrl+shift on move tool for collision moving and holding v for vector aligning.
But I cannot find anything information on how to turn on collision when using the scale tool.
Like the option to turn on while using the scale tool for making the object you are scaling have collision with other objects. So scaling one object into another should stop it from going through it
Objects don't have collision when the game isn't running. There's no physics so no colliders
Assuming you're scaling the parent object of both physics and visuals, colliders should scale as well.
Sure that is fine, the objects I have do have box collider components.
I asking about if theres a way for the scale tool to stop when the object hits another
Or maybe a better way would be if theres a way to scale an object to an exact point like holding v? if thats possible
There's no tool that does this AFAIK. You might need to write a custom tool for that.
Oh ok. I was able to vibe code a scale tool that works like the one in roblox studio. It's just missing collision detection.
Physics queries should work in the editor too, so you should be able to implement it.
The physics scene does exist outside playmode so thats not an issue
So yeah it could technically be implemented
(I only vaguely know about this roblox tool since other people have brought it up before)
Does anyone know how to help to make this border match the width of this health bar slider? I can show any code that you need to see. Right now, the slider is at full health, but it doesn't get to the border. :/
I'm trying to test out a camera but I cant find the play button
I have to use crtl p and when I do it breaks it anyways
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
โข Input Manager (Old): Use the original Input settings.
โข Input System Package (New): Uses the new input system package.
โข Both: Use both systems.
as for the play mode button being gone, you can try resetting the layout to default
I tried but it still wont popup
Right click where they should be and select Play Mode Controls
okay now still the texture doesn't work and the camera is cutting of the model in the center
What does it look like in the scene view at the same time?
a static array could be a bit spaghetti if there are multiple instances, no? having it as an instance member seems easier to reason about for me.
hello people
I'm a kinda experienced programmer tryna learn unity 3d
can someone tell me how do I go by learning
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
check out unity learn ๐
only if more than one instance needs to use the array at once
which kinda makes assumptions doesn't it? i feel like it'd be easy to forget about if you add something where the results are, for example, used in different messages
just making it an instance member doesn't cost that much extra does it? ๐ค
in exchange for having better separation of concerns - each instance has its own storage
that would depend on a game that youre planning to make, but anyway, its good idea to get some general knowledge at least to basic level especially if you dont know what you want to make. Eventually just start focusing more on the stuff that you need specifically as nobody knows everything and knowing everything doesnt make sense
i personally suggest learning UI because imo its relatively easy and i can hardly imagine a game without UI, probably 99.9% games need it ๐คทโโ๏ธ
!code
๐ Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
๐ 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.
I wanna make something like nier or devil may cry
Basically those crazy hack n slash character action kinda games
Anyone run into the issue of being unable to drag anything from the Project tab to the world scene? Or actually, being unable to drag anything in the Project tab to anywhere else. Unity 2022.3.62f3
GTE-RP
Nevermind. Turns out it was a problem caused by Photoshop. Damn you Adobe
This is true if you're intending to keep using the contents of the array after the function that filled it returns
using a static array makes the method non-reentrant: you can't safely enter it again while it's already running
(and making the array an instance member doesn't actually help much there; it just prevents simultaneous invocations of the method on other instances from causing problems)
yes, that's what i'm trying to say is better
if you're writing this code in a message like Update or OnTriggerEnter, then it's actually pretty likely for a static array to be fine
this is what i'm trying to say, yes. it removes the required assumption that you don't
i phrased that poorly
you need this assumption to have it be static, you don't if it's an instance member
in that case, then yeah, you obviously need to make it an instance member
so what i'm trying to say is, having it be an instance member removes that assumption, at relatively extra little cost
i'm not saying the static array doesn't work, but i feel like it being an instance member just makes it harder to accidentally shoot yourself in the foot 2 months from now
perhaps, but you're also potentially wasting a lot of memory (and, ironically, creating lots of GC churn if these are short-lived instances)
I do see the benefit of defualting to something that's safer
i guess that, in most of the places where i'd use a non-allocating method, it's extremely obvious that the data is only relevant until the function quits
e.g. i have no use for a RaycastHit down the road
the hit is only meaningful in the instant that it was produced
that's fair
it'd be nice if i could prove that i'm not going to try to hang onto that array
It wouldn't be that hard to abstract all of this
you'd have a static array that gets used first, and if it's already used, you fall back to allocating
uhh read that ๐ as "/s"
ah, I know: volatile
the keyword that does โจ something โจ
i've read the C# specification and I still can't clearly articulate what it does
damnit i guessed wrong ๐
there's a few modifiers like this in java and i just guessed which one c# probably had lol
the using keyword is close to what you're thinking of
it lets you automatically dispose of something when its scope ends
for transient? no?
it apparently removes optimizations too so probably not that one ๐
oh, that's a serialization thing, interesting
i'm surprised that gets to be a keyword
yeah
the main thing volatile does is prevent read/write reordering
i hate that i know what that means now.
(people incorrectly assume that this also provides some kind of "locking" for the field)
everyone can help me my trees are pink
not a code issue, #1390346776804069396
sry where i can ask?
i told you where already
You were told where
If you are gonna ask questions you should probably read replies
I could have known that you can press on it
tip: text highlighted in blue is often a link
If I make a loot you can pick up and it get destroyed, but it also have an expiration timer in which it gets destroyed, will I get an error if those two Destroy calls happen at the same time? Is that a problem?
Anyone have recommend method to reconnect SerializedField or public reference to object after go to another scene and comeback? Sorry for bad ENG.
Destroyis safe to call on objects that might already be destroyed or null. If the object is already destroyed before the scheduled time, no error is thrown when the timer expires. Unityโs internal system tracks the object's state and won't attempt to destroy it again.
you should check docs first https://docs.unity3d.com/6000.4/Documentation/ScriptReference/Object.Destroy.html
sounds like an x/y problem , could you elaborate on the setup here? it sounds like you should change the set up so you don't have to reconnect it to begin with
I swear I had error but I probably mixing up destroying a GameObject and a component or something like that, not sure
Thank you, but i just found solution second ago, it just wrong hierarchy setup.
is there a way for USS to apply to mulitple selectors like in CSS?
for example:
.class1 .class2, .class3 .class4
right now I have to create .class1 .class2 and .class3 .class4 selectors separately
that sounds like a selector list, which USS supports
I guess I have to edit USS in text editor then?
ah I tried using list selector but when I opened it in UI builder it just splits into 2 selectors automatically
makes sense (yet still annoying!)
I wonder if you can write the USS separately (so that it's never interacted with in the UI)
probably, but once I include it in UXML and open it in UI builder then it's going to blow it up again ๐ฅฒ
I guess this is to support the dragging and dropping of class into UI ๐ญ but I'll trade that for list selector lol
a workaround: just delete and dupe rule each time I make change to something in the list. not perfect but..
unity pls
How do i run a script?
depends on the kind of script, but typically its assigned as a component on a game object
broo im actually overthinking so hard
๐ญ why is it so painful to bind non scriptable object to ListView in UI ToolKit/Builder. I've been trying to do it for the past hour
I added item source and bind the class that contains the list to it and it's still not working for some reason
Does anyone have advice for how to use less if statements? I know this many nested if statements are bad but I'm not really sure how to do it better and with less.
First, share code properly:
!code
๐ Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
๐ 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.
First, you can use && in the if statements to group several conditions together.
Second, you can move the condition checks outside the if statements and only have one if statement for the whole thing.
Third, finite state machine or similar patterns can help organize code flow.
Lastly, your code is not particularly bad in terms of if statements. It's still pretty much readable. And that's the thing that matters.
One helpful technique is to negate your condition and do an early return
if (!punchCharging) return;
// The rest```
Thanks for the advice!
is HLSL obsolete anyhow? or can i still use it for my projects
No. It's not obsolete. What makes you think so?
the "don't allow charge to exceed max" can be simplified to reduce repetition by changing thr steps a bit
in place of the if/else, you could have something like this: (pseudocode)
currentCharge += rate*deltaTime;
// either:
if (currentCharge > maxCharge) currentCharge = maxCharge
// or:
currentCharge = min(currentCharge, maxCharge)
btw if you use the guard clause like praetor mentioned, you may want to extract this logic into a separate method (or use a normal condition to call said method) since you might want to do other stuff in Update afterwards
Oh I didn't know about the min function that's pretty useful 
Yeah I ended up doing that since I also had to implement some spherecasting logic for actually hitting things while rocket punching.
You can still write hlsl and use it with Custom function node in shader graph if thats what you mean
Also compute shaders and some other features are hlsl
yeah i guess i was following some really old tutorial because the syntax in it was not matching up with .shader files
it seems its fine now that im reading current documentation
That was probably CG. That one did get obsolete. To a degree.
probably yeah
Good day, I have a small issue with coyote time, it still does a doble jump even after putting the the counter to 0
the code goes as follows:
//coyote time vars
public float _coyoteTime = 0.2f;
private float _coyoteTimeCounter;
//ground check inside update
private void Update() {
GrounCheck();
}
//ground check
void GrounCheck()
{
Collider2D[] _collider2Ds = Physics2D.OverlapCircleAll(PlayerController.Instance._checkCollider.position, _checkRadius, _GroudLy);
if (_collider2Ds.Length > 0) //while grounded
{
_state.Add(ActorStateFlags.Grounded);
_state.Remove(ActorStateFlags.Airborne);
_coyoteTimeCounter = _coyoteTime;
}
else //while falling
{
_state.Add(ActorStateFlags.Airborne);
_state.Remove(ActorStateFlags.Grounded);
_coyoteTimeCounter -= Time.deltaTime;
}
}
//DoJump func
public void DoJump()
{
if (_coyoteTimeCounter > 0f)
{
Jump();
_coyoteTimeCounter = 0f;
}
}
//Jump func
private void Jump()
{
_playerCtrl.AnimationStateUpdate(EntityState.Jump);
_playerCtrl.Rigidbody2D.AddForce(new Vector2(0, _playerCtrl.State.HasAny(ActorStateFlags.AntiGravity) ? -_jumpForce : _jumpForce), ForceMode2D.Impulse);
}
theres a case where you are jumping and the groundcheck still does the check to reset the coyote time
where exactly?
should I remove the _coyoteTimeCounter = _coyoteTime; when it is true?
i'm guessing that your "is grounded" check is too generous
so that, even though you appear to have walked off the edge (and thus started your coyote-time counter), you're actually still grounded
you then perform a normal jump
and then your ground check starts failing
so coyote time starts
hmm well, let me check that out then
are these channels also related to .shader code or just c# scripts?
#1390346776804069396 is appropriate for shader questions
this is intended for scripting
k thank you
You dont have anything to stop it from doing a double jump, you can jump as many times as you want between the coyote time, and 0.
the DoJump method does that
one fix would be to make the player non-grounded whenever they're moving upwards
Or just use a canJump bool, cause as i said there's nothing to stop the continous jumping, and that should only be reset to true when the player is grounded
public void DoJump()
{
if (_coyoteTimeCounter > 0f)
{
Jump();
_coyoteTimeCounter = 0f;
}
}
This right here only stops jumping after the coyoteTimeCounter is less than or equal to 0, while its bigger than 0 they can jump as many times as they want.
it then immediately sets the time counter to zero.
Right but the input can happen multiple times before its actually gets set
Im not sure, but i typically set something like that above a action, cause fast spam input causes issues within the engine
It is impossible.
One sec i shall demenstrate
Even if you immediately call DoJump again after the method returns, the counter will have already been reset.
The only possible way for this to happen would be if the Jump method called DoJump
which it obviously doesn't
Yes this is true, but like you were going on about the collider, the physics system refreshes the coyote time allow more inputs to be passed through, thats why i said theres nothing to stop it. The only time coyote time should be refreshed is when the player isn't currently jumping & grounded
right, and that is, indeed, the issue
Question, if I made Script A, and in Script A, I had 2 GameObjects: playerPrefab and enemyPrefab, and then in Script B, I wanted to have a GameObject variable, but instead of assigning it manually, I want it to take the one assigned as playerPrefab in Script A, how can I do that?
Script B needs a way to find Script A.
Depending on the relationship between these two components, the exact solution will vary
- Spawn the player
- Spawn the enemy
- Pass a reference to the spawned player to the spawned enemy
You can use a Singleton if you'd like for other scripts to find another easier
example:
public Player playerPrefab;
public Enemy enemyPrefab;
void SpawnPlayerAndEnemy() {
Player player = Instantiate(playerPrefab);
Enemy enemy = Instantiate(enemyPrefab);
// Give the player reference to the enemy so it knows who to chase:
enemy.Target = player;
}```
@crystal agate
I already have the BattleSystem script doing this, the problem is that currently the BattleSystem script handles everything including what happens when I click each of the buttons, since I'm trying to make an RPG, I want to make it customizable what each button does
That's a separate issue than the one you asked though
my current issue is that I'm trying to have a separate script for handling what each button does, but the IEnumerator commands in BattleSystem are working off references to the player unit, enemy unit, and their stats, while if I move them to a different script they don't have those references
YOu'd have to share the specific code at play - but essentially it's just a matter of passing the references around to wherever you need them
Or making them available in some other way such as via a singleton
public class scriptA : Monobehavior
{
public static scriptA singleton;
// As long as something is public it will be accessible
public GameOject playerPrefab;
public void Awake()
{
if (singleton == null) singleton = this;
}
}
public class scriptB : Monobehavior
{
GameObject referencePlayerPrefab;
public void Start
{
referencePlayerPrefab = scriptA.singleton.playerPrefab;
}
}
The prefabs are probably not the references that are needed
it's too long for discord ๐ญ
!code
๐ Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
๐ 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.
essentially instead of having IEnumerator PlayerAttack(), I'm trying to make it run the IEnumerator of an Ability script
You can pass the references in as parameters to the coroutine
or you could pass them as params when you create the Ability object
Or you could have the ability access the references from the BattleSystem, which could be either passed to the Ability when it's created or accessed as a singleton
There are many ways to do this
I could try one, unless there's one specifically tidier way than the others
Abilities are always a fun can of worms
especially once you start thinking about how they "target" things
if your not using scriptableobjects already i would highly advise it
Question, I mistakenly set dialogueText as Text earlier when it should've been string, but after I corrected it and saved the script, editor still thinks it's Text, how do I fix this?
That means Unity hasn't recompiled yet.
I'm guessing you have a compile error caused by changing the type of that variable
look at the Unity Console (or see if your IDE is displaying errors)
oh yeah there we go there were some compiler errors, thank you
let's just say I want the string to be "You attack " + [enemy name] + " for " + [damage] + " damage!", how do I write it in editor?
assuming the quotations change
or do I actually have to hard change it in the script
Three options, unity localisation, string.Format() or string interpolation.
how's those work?
Unity localisation smart strings https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/Smart/SmartStrings.html
links above
I have a game where the player talks to npcs and they can enter a sorta rpg battle sequence after in a seperate scene. I need to count how many npcs have been defeated. I also want to mark the npc with a โdefeatedโ status so that the next time the player talks to the npc, the dialogue wonโt allow for them to do the battle again if they already defeated the npc. What would be the best way to keep track of that across scenes? Iโm thinking i make some sorta progression manager?
Are you self-dev in Unity 3d?
im working on a class project
Which part of the backend(C#) and the frontend(Javascript) do you wanna implement that function in your project?
im using C#. Just a windows download. If thatโs what yr asking
Elseif, do you have your own private or public repository for the current project?
feels like very odd very forward questions
I mean github
especially since you arent saying why
oh nvm i see
but i dont think we need to see your repo to give you the answer here lol
You would use a singleton
your idea for the progression manager is there
If you want the quickest dirtiest solution, just create a script with data you need to save, put it into "dont destroy on load", make a singleton out of that, the access it however you want
make it ddol
is that the quickest and dirtiest solution or is it just not "the solution" lol
as for the npcs, have each npc have a unique ID of some kind which you can keep track off inside of the singleton
Well, the "correct" solution would be to save it to a save file if needed, manage the singleton properly
thats a seperate issue
saving it externally vs tracking stuff like that at runtime are 2 seperate parts here
alr iโll do that thanks
And all the stuff i want to keep track, like adding to the number of npcs defeated and setting the status, will just stay constant betweenthe scenes. Like none of the data will be lost
You can also just keep some data in a static variable, not everything needs to be a monobehaviour
But I get it's easier to just work with components as a beginner
As long as you do not reset the game itself or reset it yourself by accident, it will stay
So if you have like a main menu -> go to the game -> do sth -> back to main menu -> back to the game, it will keep everything you put there, but if you reset the play mode or restart the game, it will be lost
and ensure that you do proper static management if you are doing it on statics, this can get hectic quickly
is it just me or the unity asset third person controller is super jank. i have issues jumping where its delayed, or not jumped at all log gave more then 4 times per input and sometimes just Ignores ground checks
void Update()
{
if (InputSystem.actions.FindAction("Click").IsPressed())
{
Vector3 mousePos = Mouse.current.position.ReadValue();
Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
Rigidbody2D rb = GetComponentInParent<Rigidbody2D>();
rb.AddForce(new Vector3(worldPos.x - transform.position.x, worldPos.y - transform.position.y) / 2);
float distance = Vector3.Distance(transform.position, worldPos);
Debug.Log(distance.ToString()); //Prints an object
}
}
}
Hi. The first few lines are working as it should. Im trying to use the Distance method and then print out the distance but it prints "(object)", not the float. And ofc I want the number. Please help if possible!
are you sure you're looking at the correct log ๐ค You should really add more info in your logs
eg Debug.Log($"Distance : {distance}");
also if you add a second parameter with the gameObject or this component it highlights in hierarchy which object called the log
its the only thing going into my console if thats what you mean
hmm yes lets find the action each frame ๐ (thats bad plz change)
make sure you saved / you don't have compile errors
๐คทโโ๏ธ I saw there was one better for physics but I didnt care to change it yet
no they mean you should at very least cache your action
oh well alright I could do that
Alright thanks. i figured out the problem lmao. I just dont know how to read logs yet
you can also serialize it, use inspector like ```cs
[SerializedField] InputActionReference clickAction;
...
if(clickAction.action.IsPressed()){
alright, heard about that, thanks...
in unity netcode does the lobby system automatically pick a new host when the host disconnects? i have heard conflicting things
perhaps ask #1390346492019212368
I believe in Unity 6 its does, with there Distributed Authority mode
whats distributed authority mode
Its just what they call it, it was originally single host authority
ohhh
But this isn't really new host assigned though, its handled by Unity Cloud Game state service, so it's technically just a server
so thats not when a player is ahost?
im trying to set up host migration with relay by making all clients check if there is a host id change on the lobby periodically. is this a good idea? would this work if player is a host?
No technically that something you would have to build yourself, so when the host disconnects, on the callback from that you need a select someone to be host load the server up on there game and migrate the other people that were in the original host's game
how do u detect when the host disconnects? would my method not work?
in peer-hosted multiplayer, is it a bad idea to have host migration? is it better to just end the match?
Simply just the OnClientDisconnect, and you can also check for OnTransportFailure
No host migration is fine, but handling transfer the data of the current session will be a task for sure
Of course that depends on the complexity of the game
but wouldn't that put too much trust on the client because they could hack and pretend that the host is gone when they are not gone and make themselves host
what happens to the data when start host and start client is ran again?
Well you would do a check to see who has disconnected, only the host/server will be the ones able to even execute the callbacks
but the whole point of this is that the host has left ๐
so ig theres no way of making it safe then#
would it just be better to end the game if the host leaves
I don't think you quite get it hold on ill write a deep explanation
ok thank you
Host Migration System:
So all data is stored on each client's game. Object positions, player positions and so on. This is very typical of a game this is why ESP is technically impossible to stop and games use anti cheat 3rd party softwares.
Now when the host disconnects
|
v
OnClientDisconnectedCallback <- This will be triggered, same for if someone else leave's | Now this will only be triggered by either server only execution or host only execution.
Now because it will also be called when other client's disconnect you will need to make sure if it's the host or not.
example:
if (IsHost)
{
// Do something here
return;
}
// Do something here for clients
Now if it is the host obviously your gonna have to pick a new one. Now keep in mind because the host is gone doesn't mean the data is gone. Using this before completely exiting the session you can pick the new host | After picking the host you will need to start client migration, by changing there address and port route, and have them try to connect every few seconds -> force the host to load the server / world, When the host successfully loads the server the clients well then naturally connect again. then when server/world load is done all the data you wanted to keep like players positions and rotations ect can then be loaded from there.
thank you for the response
Hopefully that helps you out, i may have forgot some things, but thats the general concept
Oh yeah anything thats a network object should be cached as those get removed when the host leaves, so keep that in mind
why do these sub values persist when the game closes?
You mean the instantiate GameObjects?
Did they not exist before you entered play mode? Because it's not clear from the gif.
they did not, no
How are you instantiating them?
public void AddElement(string buttonText, Action onClick)
{
var element = Instantiate(buttonToAdd.gameObject, content).GetComponent<PopulatableDropdownContent>();
element.SetAction(onClick);
element.SetText(buttonText);
ArrangeSelectables();
}
really dont have any idea whats happening here
Hmm... And where are they parented to the "Content" GO?
its in the instantiate line
content is the second parameter
Ah, I see now. And content is a reference to the gameobject in the scene? Could it possibly be a prefab reference?
this might be it?
on the bottom right
I think it's fine. ๐ค
I know there's an editor preference setting for disabling scene reload on play, but I don't think there's something like that for exiting play mode...๐ค
So, I'd assume it's either a bug or something weird in your project/env.
zamn
where can I check this?
Maybe try recreating the issue in a new empty project. If it doesn't happen there, you can at least be sure it's something in your project. Then start investigating it.
Checking the console(or even logs) for any warnings/errors around exiting play mode might be useful too.
I just noticed, but you have some ui saying "hot reload" at the bottom right in the gif. What's that? I don't think there's a built-in hot reload feature in unity. And it's possible that it's related to the issue.
its an asset on the asset store, but i dont have it enabled currentlyt
I see. Even if it's not enabled, there's a slight chance it's messing something up. I'd start with testing in an empty project to see if the issue is reproducible there. If it's not, this asset is the first thing I'd doubt.
okay this is ridiculous
but yeah youre right i
will do that
i might be stupid this is literally the intended behaviour ๐ญ
but the destroy part is still bugged
@teal viper not sure whats causing it, but it appears Start is also being called when I exit playmode. I just added this if statement to stop the unwanted behaviour, but its very strange
protected override void Start()
{
if (!Application.isPlaying) return;
print("DROPDOWN CONTAINER STARTED");
foreach (Resolution resolution in Screen.resolutions)
{
dropdown.AddElement($"{resolution.width}x{resolution.height} ", () => {});
}
}
Is the script marked as run in editor/run always? Or maybe a base class is(since this one is overriding Start of a base class)?
Otherwise it could be called from somewhere else. I'd add a debug log and check it's callstack to make sure.
running into a slight tricky problem with the input system, wondering if it's common and if so, what good solutions for it are: if the player is using a controller, they can aim using the second joystick. if they aren't using a controller at all, I feel it's a safe assumption that calling vector2 aim = playerInput.actions["Aim"]; will return (0,0) if no controller is being used (but also, if no movement on the second joystick occurs, problematic for me sort of). Alternatively, if they are using a mouse, the aim is just wherever the cursor is, and not mapped to my input system aim action. I do not know how to tell if a player is using a controller and just not aiming, vs when a player is using a mouse. is there a way to determine whether a controller is being used, or if a mouse is being used?
About a year ago i made a game called frictionless, i stopped working on it due to school and stress but recently picked it back up agin. or so i hoped. all i had left of it was the built game, not the project, i tried version control but it was a blank scene. i used asset ripper to try and turn it into a project. it somewhat worked, but, the scene is completely flat gray and the game veiw is black. i also dont think the file structure is the same or correct at all. Please help. i need to get this game back.
We canโt help with that on this server
Your project is probably gone
please do not crosspost.
hey guys
how do i make it so that my character in a top down project rotates where the mouse goes and not the movement?
When do they start
I have a Question, related to the Overlapping Sphere Function. ``` void SearchForTelegrapfen()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, SearchRadius);
foreach (var colliderfound in colliders)
{
if (colliderfound.gameObject.tag == "Telegrapf")
{
TelegrapfenScript teleScr = colliderfound.gameObject.GetComponent<TelegrapfenScript>();
if (teleScr ==null) { Debug.LogError("TeleScript Null"); return;}
if (teleScr == this) { Debug.LogError("Telescript This");return;}
if (teleScr.TelegrapfPlaced)
{
Debug.Log("Telegrapfen found");
ConnectionManager.Instance.SetUpConnection(this, teleScr);
ReachableTelegrapfen.Add(teleScr);
teleScr.NewTelegrapfPlacedInReach(this);
}
}
}
} ```This funtion gets called when a new Object is placed, however Sometimes the function does not find all objects. I made a short video so it's more understandable what i mean. I checked in the Inspector, whenever a line is not appearing, the object is not detected by the function properly
Youโll wanna ask this in #๐ปโcode-beginner
It would probably help if you did some debugging visually instead of with the console. Turn on the collider visualization in physics debugger, and maybe set up a system that highlights the objects that are in range while you're moving the mouse
Although now that I look at it, the code stops as soon as it hits itself (if (teleScr == this) { return; }). If it's not the last in the array then it won't process the rest of the objects. Those returns should be continues instead
can somebody help me with this?
I don't know what you mean by "not the movement" but if you google for "unity 2d rotate towards mouse" there's plenty of guides
they use the older input system though
and i have no idea
how to convert it to the newer one
in the code
Then look up how to get the mouse cursor position in the new input system
doesnt show anything
What doesn't show anything?
I have no idea what you're talking about
have you checked google
i did
is your problem resolved
no
I have explored all 3 of these avenues but unfortunately nothing has helped
its resolved now
hello familiar face
Well, I can't really suggest anything without knowing the results of all these things.
oh hey lmao
new to unity?
pretty much
lol, me2. i recently finished the Unity Essentials pathway from Unity Learn Pathways, now i'm going to be doing programmer pathway
huh
what and where is that
okay
then select pathways
is it paid or?
free
I did a debug log as you suggested but it literally just said "Start" was the root call, so I didn't see much there. There aren't any attributes that make it run in the editor either, Unless there is some checkmark in the script settings in the editor I can enable
but either way it shouldn't be a problem with this guard rail, and it won't be a problem in the game build either I imagine
Did you confirm this actually fixes the issue?
Is the log actually being printed on exiting play mode?
with the guard rail it is not being printed and the extra children are not being created. from what I gather, the children WERE being destroyed in expected behaviour, but the start was being fired again so it looked as if they weren't.
As a temporary fix sure, but you are avoiding the issue which is start being called when exiting playmode
Unity should not be doing this but adding a breakpoint will let you detect this happening with ease
Unless something is creating this component on play mode exit? OR this is the scene being re created and its ExecuteAlways
who knows
adding a breakpoint will let you detect this happening with ease
i thought the editor console already shows you where its being called from, thats new
It does but the logs could get cleared thus a breakpoint is "more reliable" as it pauses execution and includes the callstack
Id rather use a debugger than add a log to meerly check when something is called
Hey everyone,
Iโm working on a pirate game project, but Iโm having a lot of trouble fixing player jitter while standing or walking on the ship in the ocean.
Right now, the character feels like itโs constantly shaking a little, and walking around on the ship feels pretty unstable. It gets even harder because the game is multiplayer, and Iโm using FishNet for networking.
How would you approach this kind of system? What would be a good way to make walking on a moving ship feel smoother and more stable for all players?
Iโm mainly looking for ideas or implementation approaches to reduce jitter and make the movement feel cleaner.
Perhaps when on a ship player positions should be relative to that? I remember seeing something about some other game with how it handled this but i forget where
I tried to create a template (and upload it to GitHub) but it got stuck in the second stage
I think it was due to lack of space, it's over now
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/MessagingSystem.html I don't understand what's the point of this system (using it to send custom messages)
If it requires a reference to the target anyway, way not just call the function directly instead of going through this message middleman?
The point is that the target may have zero, one, or more components that can receive the message, and the message sender doesn't need to know about them. It can just broadcast the message and not care if there's something there that wants to do something with it
The SendMessage system requires reflection to find the target method by name
(You should probably just call the method directly still, though)
If you have a situation where you want to call a specific method
I don't understand the if statement. The if and else block have the same code . . .
oh yeah dont worry about it , that's for later , but is allocating variables inside this IEnumerator something wrong ?
Code?
!code
๐ Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
๐ 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.
ty
No problem. It's definitely much easier to look at . . .
uh i have some problem it dont copy the link ๐ญ
save, copy generated link and paste
if you want accurate physics don't use Translate
it is gonna be a game object that will be far from the player so i dont think it is a big issue for now
is it that bad ?
Fun fact: the SphereCollider has access (inherited properties) to the attached Rigidbody and the Transform. You don't need to use GetComponent for each of them. You can access everything from the SphereCollider variable . . .
when using a Rigidbody ? defeats the whole purpose of rigidbody
you're essentially teleporting it bypassing physics, occasionally it might catchup to do something but mostly inaccurate
oh okay good things to know
yes i'am using this just to make a small movement when instantiate but i wont use it for other movements
And they are right. It doesn't make sense to have access to or use a Rigidbody variable if you're moving the object with Translate. That method will override any physics applied to the game object . . .
okay thank you guys i will be changing that !
fun fact . if you declare InitialBallPrefab as Rigidbody you can spawn it directly as rigidbody instead of doing GetComponent
InitialBallRigid = Instantaite(InitialBallPrefab, etc..
use AddForce or Velocity in most cases
i'd also be careful calling StartCoroutine in Update without more safeguards..
yeah i'am planning on doing some modification.
for loop i guess
So, currently I have this script that decides through random numbers which attack an enemy will use. However, it seems that it only rolls a number the first time around, and will keep using that move forever. How do I make it roll for a new number every time?
Random.Range(0, 1) will always return 0. If you want either 0 or 1 it has to be Random.Range(0, 2)
Also whenever you have numbered variables, it would probably be better to use an array
(and then you can simply do Random.Range(0, abilityArray.Length))
absolutely! With Fen's suggestion you can cut your code in half here
how do I make it flexible actually? like if I want enemy A to have 2 abilities and enemy B to have 4, how do I have a single script that can handle both?
With a list or an array and what Fen said
currently if I have 4 ability slots and only fill 2 it just gives me a null reference exception
use a list
Does your character have a fixed number of slots or something?
and do they have to be contiguous or is it possible to have:
[ability] [empty] [ability] [empty]
I'd say it would be possible yeah
arrays let you store a flexible number of objects
if you have four distinct variables, then you have to write code for each of those variables
importantly, this suggests that each of those four variables is "distinct" in some way (after all, you're writing unique code for each one)
here's the simple example with a List, not allowing empty slots:
List<Ability> myAbilities = new();
// make sure you populate the list
void DoRandomAbility() {
int randIndex = Random.Range(0, myAbilities.Count);
Ability ability = myAbilities[randIndex];
dialogueTeext.text = ability.buttonName;
if (ability.target == SingleEnemy) {
ability.useAbility(playerUnit);
}
// etc.
}```
it also implies that enemies must have exactly four abilities
yeah I probably don't need it that complex for enemies, this was a carryover from the player since the player needs to map each ability to a different button
even then โ does each player ability need totally unique handling?
if not, then you can at least do something like this
If you can have empty slots it's a little more complicated, but if the number is only up like 4 you can do something like this and it will be just fine
int GetAbilityCount() {
int count = 0;
for(int i = 0; i < myAbilities.Length; i++) {
if (myAbilities[i] != null) count++;
}
return count;
}
int GetAbilityAtIndex(int index) {
int count = 0;
for(int i = 0; i < myAbilities.Length; i++) {
if (myAbilities[i] != null) {
if (count == index) return myAbilities[index];
count++;
}
}
throw new IndexOutOfRangeException();
}```
Then you can proceed as in my above example but use these two instead of .Count and the indexer
public Ability mainAbility;
public Ability secondaryAbility;
...
void OnMainInput() {
UseAbility(mainAbility);
}
void OnSecondaryInput() {
UseAbility(secondaryAbility);
}
you only write unique code for the unique parts
I hav e something like this currently
void Button(int n) {
if (state != BattleState.PLAYERTURN) return;
StartCoroutine(UseButton(n));
}```
highly recommend this
arrayify or listify all of ti
so you only need to write code once
Thank you!
even when i added [SerializeField] to the public movement it doesn't show in inspector\ (pieceMovement is a plain C#)
does it have any fields that can be serialized? the screenshot only shows a method, which obviously wouldn't appear in the inspector
i want to refrence the script by serializing it in the refrence container
it's not a component so what exactly are you expecting to drag in?
i can't drag plain c#?
what would you drag in that case?
an instance of a plain c# class doesn't exist as a draggable object anywhere in the editor
that only works for things that inherit from UnityEngine.Object because those typically exist as objects you can interact with in the editor
oh ok so i should just make it a monobeahviour?
if it needs to be a component in the scene, yes make it a monobehaviour. otherwise you might want to consider a scriptableobject
it will hold a function i need to access
is it just the one method? because it doesn't appear to have any instance data so the method could just be static
but also from what i see of the method in the screenshot above, this seems like a poor way of handling the movement in the first place
If its for like a strategy pattern then have some factory or just do new PieceMovement() for now ๐คทโโ๏ธ
what would you suggest?
i'm a beginner so it shouldn't be too complicated of course
not shoving all of the different movement types into a single method, but rather use a base abstract class (that inherits ScriptableObject if you want to drag things in the inspector), then inherit from that for each individual type of movement
i might even allow multiple movement types to be set on a single object too so that you aren't duplicating code for things that share movement types (like the queen shares movement with rook and bishop, so it would have the two movement types that are associated with those on it instead of one single queen movement type)
yeah that is def a better architucture
the queen is the only piece that shares movement with other pieces and i did handle that
really you just need 3 movement types, diagonal, horizontal/vertical, and knight where the first two specify the distance along each axis is permitted. plus any special moves (castle, en passant, etc)
ok thx for help
Can i modify this function, so that the object is spawn on the surface of the collider. public void MoveCurrentPlaceableObejectToMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, layerMask)) //Mouse hit Collider
{
currentPlaceableObject.transform.position = hitInfo.point;
currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up,hitInfo.normal);
}
}
currently it's the middle point on mouse point
well yeah its using the pivot, all you need to do is add some offset. Do it w/ the normal multiply it by an offset amount
Vector3 offset = hitInfo.normal * groundOffset;
you're better off using bounds though, so its more flexible and not a fixed value
From where should I actually start learning?
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
I'd like some advice on how to structure something if possible 
I've got a few core movement mechanics, (slide, jump, and wall run) and they all have variations for if you combine them, (for example if you slide and wall run you wall slide, and if you jump while wall sliding then you get a special directionally boosted jump).
I want to have things like sliding and wall running be more modular and exist in different scripts, however I'm not really sure how i should structure the way the main script chooses which movement mode to use. I could do like a massive amount of if/else statements for like
if(wallRunning.wallRunCheck() && inputManager.slideInput.action.IsPressed() && inputManager.jumpInput.action.WasPressedThisFrame())
else if (wallRunning.wallRunCheck() && inputManager.slideInput.action.IsPressed())
Else Etc, etc...
But that seems like it would create a pretty massive and unwieldy series of checks. Anyone have advice for how to do that better?
i dont think these kind of things should live on different scripts in my opinion
a single centralized "playercontroller" is enough
how can we possibly tell that if you show nothing of the code / setup ?
it also looks like its consistently jittery
and seeing the edge of the wall just makes it clear how jittery it actually is
oh huh. I thought it was considered good practice to split that up into different scripts. If not that does make things easier.
theres some things you want to keep in seperate scripts... but for movement its overkill
!code
๐ Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
๐ 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.
also first thing obvious is that you're multiplying mouse input with DeltaTime which should not be done at all
mouseInput is already the delta (change) between frames
specifically: mouse input tells you how far the mouse moved; it's not how fast the mouse is moving
those sorts of inputs need to be multiplied by deltaTime
In case I get 2 collider requests at the exact same time, how can I do to accept only one?
What's a "collider request"?
Nothing happens at the exact same time, one will always happen before the other.
So if you don't care which it is, it's already handled. Otherwise, have the collider pass itself up to a controller to notify it's been hit.
I mean when the object collides with 2 other different objects at the same time
That's rare enough it shouldn't be a huge concern isn't it?
You'll just get one after the other
If you really want to disambiguate you can store data about the hit in OCE and then process it in the next FixedUpdate
e.g. make a list or set of Hit datas, and process them later
nvm I think i found the issue
also
i think im the dumbest person to ever touch unity
importantly, they won't actually happen simultaneously
one message will be sent before the other
then how do I separate these 2?
Hey guys, i am currently working on my Character customizer and i have an problem with the Eyelids of the character. I wanted to make an slider to lower and higher it but the Rotation changes not only X axis and now i have no clue how to make an slider that controlls that 
(Pls ping me)
Would be very nice if anyone would help me 
again, I tried using bool, thinking its a casual race condition, but it didn't work
Don't cross-post. And this is a code channel.
What did you actually do, though?
notably, I don't see any boolean variables in that code
Sorry didnt knew that 
also I want to point out that Blue: 1 means that the episode ended instantly (a new episode to be specific)
because the boolean variable didn't help so I got rid of it
well, i can't tell you what was wrong if you deleted it!
ok, Ill readd it
also this might be helpful
it looks like you instantly call GameOver, which, in turns, resets the ball
however, unity isn't going to stop processing the collision messages just because the ball got moved
so the second message gets sent, and RaceCondition is once again false
one option would be to reset RaceCondition inside of the FixedUpdate method
https://docs.unity3d.com/6000.2/Documentation/Manual/execution-order.html
FixedUpdate runs immediately before collision messages are sent
ok, that solves it
also is it better to use [SerializeField] than getting the objects using GetComponentsInChildren/GetComponentInParent?
like, is it faster?
SerializeField since it won't need to search for the component it will just have the reference to the correct one(s)
it's faster, but more importantly, it's more reliable
Performance is to be considered but more importantly, explicitness. With reference via serialization, you're certain that the field would have been set from the inspector. Component checking is fine but it's more automated and has some runtime uncertainty.
guys im having a issue in the unity engine where my chracter is constantly moving to the right i thibk its from a ghost controller? can some one help me
If you think it might be from a ghost controller, try turning off all controllers on your character and see if the moving stops, if not then its possible the movement is coming from the physics engine and not your scripts, but in both cases it depends on how your character is setup
guys how do i make game
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hello,
I am currently making a drag and select system in my game, I am making my UnitSelectionManager a singleton as I only want to allow one of these per game instance. However, because of this code I am getting an error saying it is null, because the Awake function in SelectableUnit is running before UnitSelectionManager has chance the set the current Instance. What can I do about this?
NullReferenceException: Object reference not set to an instance of an object
SelectableUnit.Awake () (at Assets/Code/SelectableUnit.cs:10)
UnitSelectionManager.cs
public class UnitSelectionManager : MonoBehaviour
{
public HashSet<SelectableUnit> AllUnits = new();
public static UnitSelectionManager Instance;
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
}
SelectableUnit.cs
public class SelectableUnit : MonoBehaviour
{
[SerializeField]
private GameObject SelectedUnitIndicator;
private void Awake()
{
UnitSelectionManager.Instance.AllUnits.Add(this);
}
You could change the execution order so Singletons run before the other scripts you have
https://docs.unity3d.com/6000.0/Documentation/Manual/script-execution-order.html
Assign the singleton in a getter
i found out it was my racing sim steering wheel....
phone pseudo but eg.
public static UnitSelectionManager Instance
{
get
{
if (instance == null)
instance = UnityEngine.Object.GetAnyObjectByType<UnitSelectionManager>();
return (instance)
}
}
thanks guys, will take a look into those solutions ๐
Why is my unit not moving? I have baked the navmesh and applied a navmesh surface to the ground plane, and added an agent to my unit. ๐ค
private void HandleMovementInput()
{
if (!Mouse.current.rightButton.IsPressed()) return;
Vector2 mousePosition = Mouse.current.position.ReadValue();
foreach (SelectableUnit unit in SelectedUnits)
{
if (unit == null) continue;
unit.MoveTo(mousePosition);
}
}
the function that runs moveto is running, the code is being reached.
i making a 2d map that basically wraps around to the opposite side when the player gets to the edge. i did this by splitting the map into chunks and then teleporting each chunk to the other side once its too far away from the player. i did this teleportation by just setting the transform.position of everything within that chunk, including the map, enemies with rigidbodies and colliders, etc. would this create any problems or desyncs physics wise? since im setting transform.position it should essentially just be a teleport and the physics wont break on me right?
oh and also should i put the teleport code in update or fixed update?
i also cant really try it and see since if theres any desync it would resolve itself really fast, the desync would only be problematic (and noticable) in edge cases
basically what im asking is is it ok to set the transform.position or do i need to set rb.position as well? or something else entirely?
Hey everyone, howโs it going?
Iโm trying to figure out the best way to handle player movement on a moving ship, so I decided to ask for some advice here.
Iโm making a third-person pirate game, and I need the player to smoothly follow the shipโs movement while still being able to walk around on it normally.
You can think of how player movement works on ships in Sea of Thieves, for example. Thatโs the kind of feeling Iโm trying to achieve: stable, smooth movement on a moving boat without jitter or weird sliding.
How would you approach this system? Would you use parenting, velocity compensation, custom character movement, or something else?
Thanks in advance for any help!
Quickie: how do I debug what is the mouse currently hovering over? I'm trying to find what is stealing my clicks.
Select the event system object in your scene, it'll have some debug information included what's bring clicked.
(unless you are using new input system cus its been broken there for ages)
Is "null" = 0 ?
depends on what you mean by = specifically, but in c# or with references you generally would not think of it that way
i mean like its the same with 0 ?
no
it is not, no
null = nothing
I mean 0 is actually nothing but in programming it means parameter has no value.
i dont think so, null is like "nothing", no numbers, no value. and 0 is... 0
The real explanation is in c/c++ we say a pointer with a value of 0 is a "null pointer"
This applies to reference types, if they "point" to nothing they are null
best not to go into it more it will just confuse beginners
hi
im learning input system
what does this error mean
object reference not set to an instance of an object
like i left a field empty somewhere?
or maybe how i tried to create a function
Something on that line is null but you're trying to do stuff to it anyway
thats a classic NullReferenceException error, youre probably trying to use input system variables that werent initiated correctly. heres whats happening:
in the Start() method, you tried to search the actions:
moveFwd = InputSystem.actions.FindAction("MoveFwd");
moveBack = InputSystem.actions.FindAction("MoveBack");
the issue is in line 28 (in VerticalInput), because one of these variables (moveFwd or moveBack) is null. im not sure how to fix it but hope it helps!
so one of those lines didn't find the corresponding action?
Try logging them to find out which is null
probably
are you sure thats the right input action asset?
you might have saved a new one
i have no idea how to save them
i copied it and saved it as a text file in case it happens again
im really not sure of anything right now tho
my controller does this silly thing where when i release it, it doesnt go back to 0
it's like 0.35
You should confirm that it is indeed happening at the level of input and not something caused by your code. If you confirm that then you can introduce a dead zone for the sticks
E.g. if input axis is <= 0.4 it just counts as 0
this is how im checking it right now
read value for button
i have lots of things going wrong im figuring out lol
why the hell does it not turn around there?
I might have a ghost-in-my-machine type issue here, but just for clarity, Unity doesn't do some kind of magic with Monobehaviors where it automatically instantiates member variable lists and such, right?
I have a declaration: List<Vector2> currentPath;
And in "Awake" that currentPath is already listed as a list with count=0
currentPath is private so nothing else can touch it
for serialized fields, it's instantiated
it may be that it was previously serialized so the serialized version still has a list that gets injected
It isn't serialized... Or shouldn't be, anyway
try checking the raw yaml for the specific instance you're seeing
How do I check the raw yaml?
locate the file in question and open it in your ide rather than in unity
you may need to configure what files are hidden/shown
i'd need more context to give more specific instructions
someone lmk whats wrong here i just want to finish this supposedly simple idle movement and take a break
The cs file for the monobehavior is open in Visual Studio, but I'm not sure how to get the potentially stored serialized data from Unity
it's not serialized inside the source file, it'd be serialized in a scene (.unity) or a prefab (.asset)
So open the scene file in Visual studio and look around for the object that may have serialized the data
it'll have a lot of stuff, so you wouldn't really "look around" lol
could try searching for other members of that monobehavior that you know are serialized, or the component id from the script's meta file, or via the GO's name and then going through its transform then components
unity serializes private members for the sake of the debug inspector
i don't believe it will actually write anything into the file on disk
- have you tried debugging your
forwardBlockedand such checks? - could you show the level geometry there?
(also, it wouldn't matter if there was data for the currentPath property in the file โ unity will ignore anything that it's not explicitly told to serialize)
this can be very annoying! use [NonSerialized] to prevent this
Wait, so this means it will actually instantiate lists?
Because it automatically serializes them?
i just double-checked this, because it did sound plausible
private int x; doesn't get populated even if the serialized data includes a value for x
There is no visual "currentPath" in the inspector, yet at that "awake" call "currentPath" is not null
So something is definitely instantiating between those two points
just as a sanity check
Right. It still gets serialized, though, for the debug inspector
I created a MonoBehaviour with a serialized field, saved a prefab with it, then removed [SerializedField] and logged its value in Awake
It doesn't matter that it does not appear in the inspector!
i meant how Blue checked that it wasn't null
ah
Unity is still serializing the field (strictly for the sake of showing it in the debug inspector, afaik)
I reproduced the behavior on my own
(blue asked this btw, you mightve missed this? #๐ปโcode-beginner message)
public class Foo : MonoBehaviour
{
private List<int> items;
void Awake()
{
Debug.Log(items);
}
}
well, its not recognizing the ground, im not sure exactly what to debug more, this highlighted area has a non-trigger composite collider 2d which is used by tilemap collider 2d
This caused me a huge headache at one point. I was getting garbage InputActionReference data
annotating the field with [NonSerialized] makes this behave the way you'd expect
I don't fully understand this "half-serialized" behavior โ e.g. i don't know what happens in a built game
it scares me
Just with a breakpoint in Awake
Uh, ignore the Rem I guess
try debugging what hitForward hit, might not be the object you expect
you should probably put in a layermask there to filter for what to hit
arguably obstacles could be a layer rather than a component as well
I have been having this same headache for a good hour or two now
i noticed that you're not getting debug visualizations for the forward raycast, but you are getting them for the downward raycast. Are they just getting covered up by other gizmos?
oh, i see; they're on the top of the square
btw you don't need to put a ternary on direction, you could also just do Vector2.right * direction
A 2D raycast will ignore any collider that it starts inside of by default. I wonder if you're skipping over the wall completely
u just realized its hitting its wn collider
i thought so too
added bunch of debugs
result
What happens if you breakpoint in here when it should collide?
"TestEnemyV2(Clone)" is name of the enemy
yeah you should put in a layermask for the raycast
thing is i cant make obstacles their own layer becuase some obstacles are "ground" also
If you breakpoint in the hitForward.Collider != null bracket, you should be able to tell if you hit anything at all
i suppose i could still change them to that, and then change ground dependant logic to also account for obstacles that should count as ground
I suspect you're hitting something else that's blocking your ray
And that object isn't an obstacle or ground.
yes i figured it out its the enemies own collider
use a layermask that doesn't include whatever layer its own collider is on
but the enemy isn't an obstacle nor the ground, is it
yes, i do have an enemy layer but i had a whole thing with it i had planned to use it in some way specific i think so i also was looking for other solutions, i settled with moving the start point by 0.01 forward so we dont start by grazing the enemies own collider, and it works
You can layermask so you search against multiple layers at once.
So you could layermask so you only collide with "obstacles" or "ground"
how do i access this value in another script
check out https://unity.huh.how/references!
thank you !
im stuck on this bit
i dont think i can just treat that as a uhh
child of the vehicle
or
if vehicle is the target
i guess i put it under the main camera somewhere
like the tutorial had me do earlier
but i dont know if i can access the vehicle script's variables from the camera script
i don't understand what you're showing here
you've boxed a single property of the Player Controller component
you aren't referencing that
you are referencing the entire Player Controller
you need to store a reference to the vehicle's script, you can't reference a float
given access to the player controller, you can read its "speed" field
Where is the make game button that makes the game for mw
player is a GameObject variable, you can call GetComponent on it to get the PlayerController component, or you should just reference the PlayerController component directly rather than using a GameObject variable
in fact, making that variable a PlayerController won't even change the existing code at all
does it share the same transform
yes
oh okay
the transform property is just a reference to the Transform component on the gameobject. all GameObjects and components will have a reference to the Transform component that they are attached to. so all components on that same object will all point to that same Transform component
it's equivalent to writing whatever.GetComponent<Transform>()
Unity used to have a bunch of these properties, like light and rigidbody, but those were removed
the only other component guaranteed to be on an object is the Transform
got it
im trying to make the camera that follows my truck get closer or farther depending on the absolute value of the speed
partial success
what is the very first error in the console
the referenced script (unknown) on this behavior is missing
that's the warning
everything else is this lol
i just made the formula wacky
well then whatever your formula was, the output wasn't valid
NaN, Inf, and -Inf, the trifecta of nonfinite values lmao
had no idea it would be that wacky
i forgot absolute value
and i swapped a couple terms
it couldve been (0, <some positive value>, <some negative value>) / 0
can someone help me? How to I flip a 2d character using the new input manager? everywhere I look online it just shows ways with the old one
that task isn't related to how you receive input
changing input systems just changes the part of receiving input, the flipping part will be the same
what's that math.abs from ๐คจ
from the mathematics library?
i guess so
typically you'd use Mathf from unity
oh okay
yea i just guess how things work
looks like it auto imported the math library
that's nice
๐ค is this supposed to be applying extra offset or lag when the player goes a certain speed?
i'm confused what's going on there. speed shouldn't be negative to begin with, and for this calculation i feel like using the signed vector velocity would make more sense
vector1
no, that's not what i'm talking about
typically, "speed" should not be negative
if it can be negative to indicate direction, that's velocity
eh, "forward speed" is often implied by "speed"
in which case it's fine to say the speed is negative when you're going backwards
you're getting a crazy result because you're dividing by zero
that would be incorrect them, since speed is just speed, not directional
i noticed that the Max Speed property of the player controller was zero back here
where
when dealing with physics, using non-typical definitions can very easily get very confusing ime
when i declare the variable
that does not matter!
you should set stuff in the inspector
the field initializer is only used when creating a new component or when resetting it
Unity will overwrite whatever the defaults are
(based on the values shown in the inspector)
those values aren't used
they're only defaults when you create the component
the value in the inspector is what matters - hence, you should use the inspector to set this stuff
it doesn't matter that the default value of maxSpeed is 70; Unity is setting it to zero because that's what you put in the inspector
(or, more accurately, it's what showed up by default in the inspector, since you must have added that component before putting the field initializers in)
without seeing the rest of the script i can't say much
yeah it stays at 70
ill set it in the inspector though
that way it doesnt need to re-compile every time i change something
ah, you had them set to zero on a specific instance of the prefab
notice the blue lines on the left side
the Input.GetAxisRaw("Horizontal") doesn't work
the original prefab had the values you wanted
yes, because that's the old input system
but, again, as Chris said: flipping the character has nothing to do with how you get input
well that's how I've seen people do to check which direction the character is moving
this doesn't have anything to do with flipping the character though. from that you'd get a float, and then you'd use that float to decide to flip the character or whatever
changing input systems only changes how you get the float
think about what that actually means
you don't flip the character because Input.GetAxisRaw("Horizontal") is a negative number
you flip the character because the player is trying to move left
I think I worded that wrong
that's how people get which direction the player inputted, the check is later.
how do I check which side the character is facing? I know you flip it with the flipX
you can store it yourself, or you can read back what flipX currently is
(this part doesn't change when you switch input systems)
oh geez, how do I make the check of which way the character is moving? Like, how do I check if the character is moving left or if it's moving right? That's what I mean
that's the part that I found to be input method dependent
it isn't
Are you able to move the character at all right now?
yes