#💻┃code-beginner
1 messages · Page 670 of 1
You can Destroy any GameObject in your scene
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Object.Destroy.html
If you're using a particle system, there is also a stop property on the component which you can set to destroy so it'll handle it itself once the system is complete.
I'm using VFX graph, does unity allow manipulation of the playrate of the instantiated slash?
I have a config like this:
(
vfx_slash,
position: castCenter,
rotation: slashDirectionQuaternion
);
Destroy(vfx_slash, 8);
SuspendSlashes();```
anyone from india
Lots
I destroyed the game object, but not the clone, why?
Instantiate returns the cloned GameObject. you never assign the return value to a variable . . .
You destroy the prefab used to create the clone . . .
how do I do that
Sure, checkout the docs for Instantiate. They have an example of cloning an instance . . .
can anyone tell me why my player is not available as a game object
got it, thanks
now my problem is making the particle spawn properly relative to the player
most likely your player is an empty game object
ur in prefab mode..
its only showing the gameobjects in the prefab
no worries
thank you soooo muchhhh!!!
i meant to ping @viscid needle
yea, u can manipulate cinemachine variables at runtime... (the way u do it varies tho) especially since the updated blue cinemachine
vs the red cinemachine
trial and error for me when i do
do you know how to manipulate them? cant find anything in the documentation
keep in mind tho.. that prefabs can't really reference things within the scene unless they are already in teh scene..
say u instantiate a prefab... unless the thing thats referenced is inside the prefab... the reference will be broken..
u need to do things like that after the instantiation..
still does not work
say an enemy needs to know bout the player..
- spawn the enemy
- reference the enemy..
- tell it to assign the player (cuz now they both exist in the scene)
- ur still in prefab mode
- #💻┃code-beginner message
it works in the scene view but why not in prefab ?
Which of these objects is the player
Dont know how code will fix my bullets being too fast for the engine to register, but its worth a shot i suppose
none it is a single prefab containing a healthbar
Then you cannot set it as a reference in the editor here
A prefab cannot refer to objects in scenes. You will need to set the variable after spawning this object in code
var castCameraLocation = playerCamera.transform.position;
var castCenter = playerCamera.transform.TransformPoint(castCenterOffset);
var vector3HalfExtents = new Vector3(1.25f, 1f, 1.25f);
var slashDirection = castCenter - cameraTarget.position;
var slashDirectionQuaternion = Quaternion.Euler(slashDirection);
// spawning game object doesn't seem to align with direction
GameObject slashvfxinstance = Instantiate
(
vfx_slash,
position: castCenter,
rotation: slashDirectionQuaternion
);```
I'm trying to spawn the particle gameObject at the end of the white line (`Debug.DrawLine(cameraTarget.position, castCenter)`) with the direction of the particle pointing at the same direction, but somehow it doesn't work. Object is spawning in just fine, but for some reason I can't see the VFX except at certain positions at certain angles, did I instantiate incorrectly?
Do you want to refer to the player prefab, or the one in the scene that is doing things
theres 2 main ways of doing this
- the thing u spawn has logic that "grabs" the player reference when it becomes into existence (in the scene)...
something like this.. but be cautious of usingFindmethods...
the 2nd way is:
- the spawner... (that spawns the prefab).. uses its opportunity to cache the object..
and tell it to assign the player immediately after instantiating it
#💻┃code-beginner message - #💻┃code-beginner message
you can also use somewhat of a shortcut.. and just Instantiate it using the script instead..
(it still instantiates the prefab object).. & you have the luxury of already having the reference to the script you need..
@viscid needle
one question how would i take a gameobject rotation and rotate it at a slope angle???
use the normal of that surface and simply set its transform.up = that
not working
i have already tried it
Hey guys! i have a problem that i dont know how to solve. I have script that handles all my inputs
onFoot.UseItem.performed += ctx => { if (!playerUI.isInventoryOpen) useSelectedItem.UseItemInHand(); };
like this, when i press lmb it calls function from another script
{
ItemSO itemSO = inventoryManager.GetSelectedItem(false);//what item is selected
if(itemSO == null)
{
Debug.Log("No item selected to use.");
return;
}
ItemSO selectedItem = inventoryManager.GetSelectedItem(itemSO.isUsable);//this reduces item quantity on use
if (selectedItem is IItemUse usableItem)
{
usableItem.UseItem();
}
}```
and from scriptable object script it gets UseItem of that SO
```public void UseItem()
{
// Implement the logic for using the seed item here
Debug.Log("used");
} ```
ill try to be as clear as i can, i need to check in UseItem for canPlant bool from my plantingmanager script, so if i can plant than i will use the item, but i cant get a reference in my SO to plantingmanager, if i will do it in my UseItemInHand, then every object even if its not a seed will have a check on canPlant which i dont want because i will have items other than seeds. i propably could just use old unput system and in every item use script i would wait for lmb input, but i wanna do it with new input system. I hope i was clear enough and at least someone can understand what im saying.
theres something more going on in that code..
log ur hits..
it seems to be spamming between different hits.. (maybe when ur stuff rotates)...
u need to ignore the collider of the thing ur moving too ofc..
either with physics query logic things ( i forget what they're called) or a layermask
so its only hitting certain things
btw the ground is a terrain
i think ur mixing up what normals are..
normals are perpendicular to the surface.. so for a surface thats flat.. (horizontal) the normal will be Vertical...
in ur case ur using slopeDir which is a forward vector along the slope plane... or "Parallel"
i think u can fix the code u have now with some type of normalization but im not totally sure
projections i kinda just fiddle with until i get to work. 😄
i do simple raycasts w/o the projectonplane.. so that bit was what threw me off a bit
hit.point is just the position has nothign to do with rotations /direction
idk
That wasn't a question it was a statement. I have no idea what "idk" is supposed to mean in response to this
Vector3 slopeDir = Vector3.ProjectOnPlane(, hit.normal); that i dont know if the first argument should be a position or not
The direction you want to actually project
im confused
what should be the direction aka vector
when im trying to rotate the game object around the slope angle
Setting transform.up to the hit normal should work, as spawn suggested
so ur doing something like this?
I DID IT
Maybe your raycast is hitting the object itself?
like 20 secs ago
Vector3 slopeDir = Vector3.ProjectOnPlane(transform.up, hit.normal);
transform.forward = slopeDir;
once its rotated it should be just along the lines of rotating it along its local Y axis or w/e it is
like this
nope
its just floating
a little bit
like the character
but im gonna repair it
thx
np, 🍀 good luck
i mean there is one
the model is shaking
like left and right
all of the time
probably a situation where ur moving it one method..and rotating it another method..
or vice versa.. some kind of sync/ rigidbody jitter perhaps
some movement logic in Update()
other logic in FixedUpdate() or relying on physics calculations(just speculations)
Can anyone help with linking Firebase to Unity? I have an InitializeFirebase() method called in Awake(), but it never seems to finish initializing. When I try to save data to the Realtime Database, it fails because Firebase is still not ready. What could be the issue?
Show code
but i have a problem i want the enemy to look at the player but transform.up = hit.normal; doesnt allow me too bc its rotating on all of the axis uk
is there a way to fix that????
for me i typically break up my objects into "container" objects
say the Outer wrapper (root container) is rotated by one script..
and then my Inner container is rotating inside that outter container..
i was thinking about that bc the model has bones
so i am able to do it
like for example my AA gun here
the base rotates (rotating the cannon with it).. but for the cannon rotation i rotate just teh cannon (inside the base)
Which of the logs do you get?
keeping them seperate.. its ususally the only way i can get some of the things i want to work to work
plus rotations and quaternions break my brain most times
(its also how my player camera works) my player rotates his body left and right (camera just follows) and then the camera only rotates up and down.. but u combine those together.. and u get a full 360 range in all directions
mhm
but thats all the info i really got.. you'll have to probably share ur entire script.. type out what u want to happen.. how u want it to happen and all that stuff..
and then someone thats a wizard with rotations will step in and can tell u the correct Rotation methods to use.. (as there seems to be dozens of em)
Debug.Log("Inicializando Firebase..."); on initializeFirebase method
the first line
Looks correct to me, sorry. You might want to browse the bug reports if someone has had the same issue: https://github.com/firebase/firebase-unity-sdk/issues?q=is%3Aissue CheckAndFixDependenciesAsync
what is the difference between an animatorstate and a childanimatorstate?
You won't need childanimatorstate unless you are doing editor scripting with the animator
Looks like it just references the state and its GUI position inside the state machine
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Animations.ChildAnimatorState.html
I have a dodge roll animation setup for my player that uses root motion.
I have a few issues
- The roll animation does not seem to finish fully when pressing the roll key
- my camera does not seem to follow the player when dodge rolling ( can show relevent scripts for that)
- the player returns to the starting roll position when the dodge roll ends
When doing the dodge roll, it doesnt seem to be moving my character controller?
root motion will only move the object the animator is attached to... (or that it has keyframes for)
if ur CC is on that Player gameobject.. yet the animator is on the KnightPlayer child gameobject i wouldnt expect the Player to move along with it at all..
with the CC?
last i recall CC's dont like to be moved or animated.. thats why when u teleport one of them you have to disable the CC, then teleport it transform.position = teleportPosition; .. and then re-enable it
Character controllers dont like to be moved?
but i can't say with any certainty how it reacts with RootMotion animations
not outside its Move() and SimpleMove() functions no
A tool for sharing your source code with the world!
Mb
what about the deltaPosition
i havent ever done root motion so idk.. u may have to force the CC to update to the rolll position
https://www.youtube.com/watch?v=mNxEetKzc04 is the vid referenced
Hmm, but im using character controller.move, shouldnt that move it?
ya, it'll move it however u tell it to move depending on whats inside the ()
but.. if ur animator is whats moving it.. idk
Could it be because my animation type is generic, not humanoid? but that wouldnt make sense because all my other animations are generic, they work 100% fine
ya, i seen some mention of that in a thread as well
something about the avatar
Alright, so id switch the whole avatar to humanoid then right?
then the animations too
im just looking thru threads and google searches.. cuz i dont do root motion ll
dont get me lying ¯_(ツ)_/¯
Okay thank you so much, this has been bothering me for so long, would be amaizng to get thsi working
ChatGPT making me lose my mind...
you can also debug ur CC position over the duration of the rolll
see if it updates at all past the point u initatiate it
Okay, well, i can clearly see it doesnt move anyway, in the viewport
ahh.. so it stops in its tracks
Yeah
as soon as u trigger the anim
okay.. well that seems like useful information
then the mesh snaps back to where the CC stopped?
Yes
ahh okay.. now i got the full picture.. still no solution tho lol
are any of the clips mixed? like some being root motion and others not being root motion
ya, seems to me like ur gonna need to update the cc or the mesh. or whichever manually or theres something i dont know about with RootMotion. which is a very strong possibility
Yes, so all my other animations are non root motion, essentially only the dodge is root motion
And im enabling root motion as soon as the player rolls, then disabling it after
ya, something about that peaks my interest..
like if the last animation u were transitioning from is not.. root motion.. and then once the roll is complete it also transitions to a clip thats not root motion..
seems like that may matter.. but it also doesn't seem uncommon of something to do or try so im out of ideas
ya totally
very common in soulslike games
well im not meaning the mechanic being common.. just the method ur replicating it
also seems like it would be common
I dont think its my code thats wrong though, did you see the animator?
unless* the souls-like also uses root motion for the simple walk -> movement
u could always run a coroutine when u dashroll.. moving the player (x distance / second or w/e) towards the stopping location..
(do it manually)
Yeah I made a dodging in place animation just in case
So ill do that as a last resort
that would be my only solution lol
I want to at least TRY fix this
Maybe I should take this into the advanced code channel
it can find the root gameobject fine, but is struggling to send a message for some reason
hey! maybe the animation finished before u get to set rootmotion back to false
so it snaps it back?
last guess.. im out of ideas 🍀
ew why are you using SendMessage? but also the error is pretty clear, you're calling GetChild and passing an index that is not between 0 and the number of children of that gameobject (or it just simply has no children)
i was going to recommend #🏃┃animation but they're likely to send u back to a code channel once they see its a CC / Anim problem.. could possibly try general or advanced since we've discussed it a bit more thoroughly u got some good details to add
i think the non-root to root to non-root + ur code is likely the issue
Hm, not sure about that, actually have the opposite problem lol, the animation doesnt finish
are there any alternatives to send message that i should know about? and I thought i was calling transform.root, i use GetChild in other scripts but not in this one. i dont know why it mentions GetChild here
well, how about that lol
you should get a direct reference to the component you want to call a method on and just call that method instead of relying on SendMessage.
and you are looking at the wrong place for the error, look in the stack trace and you'll see where you are calling GetChild at
Yeah the delta position just returns 0,0,0
with the animator.deltaPosition
ah, forgot you could do both those things
https://pastecode.io/s/rht78g61
Anyone can help again? my Firebase was not initializing because it starts before dependencies load, now i have used CehckAndFixDependenciesAsync and it gives me a null reference
reference = FirebaseDatabase.GetInstance(app).RootReference; <- NULL
ok ty not pinging since its an old question
actually if my dontdestroyonload exists when im in scene and im then supposed to use onsceneloaded im assuming i make a function for the scene i open (read my question if yall havent seen it its above the reply i got that i just responded to above this comment) that registers it is opened with onsceneloaded but inside of the scene i have to go back to so it can ideally let me add a visual of like a check box for each one, and then after all four are done i can show the voting system ? should this script i make be inside the canvas for the ui i add or something else
I think i have found my error but doesnt know how to fix it...
if I start firebase without the FirebaseApp.CheckAndFixDependenciesAsync method it starts fine but without the dependencies loaded then it does not let me upload data to the RealtimeDatabase, but if I use it and wait for them to load the method never finishes, so I understand that it does not find them or it is not loading them for some reason.
Has it happened to anyone?
also in 3d worlds with unity toggles how do i move them as i do not get arrows like buttons do in unity
heyy guys! Just Trying to figure out wether ot not u can check how much force an object has after u apply it in a script
Objects don't "have" force
Force causes changes in velocity
but there's no way to go back from velocity to the amount of force used and when it was applied
can you check if the velocity meets a certain speed in a script to then do something?
I need to check if the velocity is higer that 10 to rotate my object
How Would i acheive that in a script
With >, most likely
But velocity isn't a number, it's a vector
It has direction
depends on what you actually want
something like
x velocity only? y velocity only? z velocity only? overall horizontal velocity? overall velocity?
if ( rb.velocity =< 10)
yeah that doesn't make sense - again, velocity is a vector
rb.velocity is a vector. It has a direction.
It's got X, Y, and Z components
You would need to get a numeric property of it like .x or .magnitude or something
Whichever one you want
so would it be something like if ( rb.velocity.x ?
you'd have to actually check it against something
Yeah!
If you want to check if the X velocity is greater than 10, that'd be a good way to do it
Yeah.. im really new
I want to give a list of "goals" to the enemies in my game (the goals determine how the enemy state machine's states function in order to reach said goal), but I'm coming across an issue where Unity does not want to serialize abstract classes. Seems like inheritance is not something you can do if you want to serialize a class.
I did start using scriptable objects and now I can have an abstract base class that the other goals inherit from (while the base class inherits from scriptable object), but there's another issue. I wanted to expose some variables in the editor in my list, but since I'm working with scriptable objects now all my goals are references to assets in my project; I can't change any variables (like patrol range or how much health they'll retreat at) in the GoalManager class's list, I have to do it on the scriptable object meaning I need slight variations in similarly functioning scriptable object "goals" if I want different enemies to, for example, patrol with slightly different parameters.
Am I making this too convoluted or is there a better way to do this? Or are scriptable objects the best option here?
Appreciate any help or feedback. Thank you.
With >
how would you deserialize an abstract class? you can't construct it
it's not the inheritance that's the issue, it's the abstract being an issue
i undersand what the less than or more than keys work yet im struggling to find wha it would actually look like in a script
see the pinned resources
where's that😭

if(condition)
{
// execute
}``` where condition would be something like `rb.velocity.x > 10` or `rb.velocity.x > someVariable`
Well, you know how to get the number you want.
And you know how to use less than or greater than.
So what do you still need to know?
Yeah, you're right. My bad. I think my implementation of my idea is just flawed and I don't understand how I'm going to what I want yet.
Im not sure why its red?
this is why that happens: https://unity.huh.how/compiler-errors/cs1612
but also this is important because that line would be wrong anyway: https://unity.huh.how/quaternions/members
- you can't set an individual component of a property on the same line you get it
- Rotation is a quaternion and you very very should not be editing an individual component of it
arent quaternions 4 dimensional?
yeah, what about it?
to be a little pedantic, point 1 is only true for properties that are value types
i feel like a 4 dimentional aspects of unity would be a lil to hard for me to understand at the point im at along with my age
this isn't a unity 4d thing, this is just a math thing - quaternions are necessary to accurately represent and manipulate on 3d rotations
don't worry about understanding quaternions, just treat them as a black box. don't modify them, don't try to interpret their internal values unless you really want to get deep into the math
Okay, Thanks
Yes, which is very why you shouldn't be setting one component of it
If you're ever modifying an individual component of a quaternion, don't
Oh Okay
also iirc rotation quaternions are normalized, so modifying a component would directly make it invalid
Thanks A Bunch
ill try adding some of the stuff you guys have suggested and see if it helps me with my problem!
I cannot figure out how to change the "front direction" of a Unity prefab and get it to work with my script. I have this "Arrow" prefab (a fork. This is a college project and we're supposed to use free assets) and put it as a child in the Vehicle object so that it's automatically in a fixed position over the car. My script works when I pass in the Arrow child object and it always faces the nearest Waypoint, except the "front" of the object is not the prongs of the fork (or whatever they're called). I asked about this problem before and the answer I received was the same as the internet. So, I put the fork in an empty GameObject and rotated what I wanted to be the "front" of the fork to match the Z axis of the GameObject. I put the GO as a child of the Vehicle and then attached it to my script instead of attaching the fork itself like I did previously. Now the fork doesn't rotate and instead moves all over the place whenever the car moves. I checked the Inspector and saw that the GameObject itself is rotating, while its child, the fork, doesn't rotate at all. The script I attached is just the Arrow rotation part. It's apart of the WaypointSpawnManager, which is a bad idea, but the project just needs to work and I need to submit it already as well. So, ignore that part, since the Arrow just needs information from the Waypoints in the list and is unaffected by the spawning script I didn't include https://hastebin.com/share/ruqolujuko.java
The second image shows the rotation of the fork. The Move Gizmos are the empty GameObject, not the fork
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Is the Fork object at position 0,0,0 relative to the EmptyGOArrow?
I'm not sure, but both objects' coordinates are different from each other
neither are at 0,0,0
You can just look in the inspector.
the values showed there are local space
is the fork at position 0,0,0?
oh ok, then no
I see that it says it's around 18, 27, -60
how should I get it to 0,0,0 relative to the EmptyGOArrow?
I'm still very confused with how Unity works
By setting it to 0,0,0
oh
The inspector shows the object's position relative to its parent
Putting it at 0,0,0 means it's at the parent's location
So when you rotate the parent, it'll spin this object about its center
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, 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.
hi i know i was told to us OnSceneLoaded in order to verify that a scene was opened but do i do that in my script that allows me to open the scene and also how on earth does this apply in my main script that verified if each scene loaded loaded
here's the bin in which i want to apply it
https://paste.mod.gg/zlqlsalokijc/0
inside the switches' cases like a code that fires that this specific scene loaded and sends back info to the other script ill code into
A tool for sharing your source code with the world!
omg it works, thank you so much!
OnSceneLoaded is how you'd register a function to run whenever any scene is loaded. If you just want to know that every scene was loaded, you could just make this script a DDOL singleton and set a boolean flag whenever you change scenes. Then you can do something when all of them have been visited.
https://gamedevbeginner.com/singletons-in-unity-the-right-way/
i cant figure out how to do what you've guys told me so i just given up
i still thank you guys for trying but its just too frustrating
should i set up the singleton inside my script that checks for when all four scenes are loaded and my bool there as well
Probably
ill try that out first see what happens and report back
did you read this page https://unity.huh.how/quaternions/members
wait so if i put a boolean in my inputhandler script section that opens my scenes i do inside the script checking singletons
void Start()
if(OnsceneLoaded.booleenname)
{
//run the singleton?
}
``` or is this wrong cus it also would mean the singleton loads per scene and since its a singleton it destroys itself if it runs more than once so then is the boolean made inside the singleton and i run the singleton in the script that loads my scenes?
i feel like maybe im supposed to run the boolean and define it by the singleton somehow like boolean only true when all four scenes are opened? confused i am
also i need to define my singleton how so?
damm we still on this scene counting thing lol
You were linked to it here #💻┃code-beginner message
you can also check out https://unity.huh.how/references/singletons gets right to the thing
i read that but just realized theres more in the site lmao
his tutorial gave an example of setting a float variable to a singleton but i want to define the singleton so i can have it not show an error
top one goes more in depth with explanations, usecases etc.. the second link is more straight to the point and example of use (also imo has a good outline of how to make other classes share this pattern with 1 script)
what error are you getting?
& wdym "define the singleton"
it says the name of my singleton can not be found
this doesn't help lol
screenshot the actual error or somethin
What is ScenesAccessed
also configure your IDE https://code.visualstudio.com/docs/other/unity
that is supposed to be the name of the singleton is singleton always supposed to be called Singleton?
It's supposed to be the type you're trying to make a variable of
no..thats not a name, that is a type. the name comes after
Right now, it's a variable of type ScenesAccessed, do you have a script named ScenesAccessed?
instance = this would error because you're trying to assign EnableVote as ScenesAccessed, whatever that is..
no so i would essentially name it to the script im coding it in and put the singleton name inside that public static
If you want the variable to store something of this object's type, you'd use that type
enablevote is the scripts name
so ScenesAccessed is some made up class?
So, if you want your variable to hold one of those, you'd use that
the whole point is so you can access whatever is in EnableVote(methods, public fields etc.) through instance since its static and easy to access from other scripts
ohh ok that clarifies what i call the singleton lol
so should i put this singleton i made in the script i want to fire the singleton in instead since itll just fire the script with the name it uses
if you made a public method inside EnableVote and its called Foo()
from another script you can call EnableVote.instance.Foo()
because its always going to hit that specific EnableVote through instance
the singleton pattern just makes it so its only 1 that exists, is just there so you can easily access it from any other scripts static makes it belong to class itself , hence no need for a field reference / link through inspector
oh so it opens enablevote because its a singleton since singletons are what uses instance to call whatever is inside of it?
and ofc runs the method im using like foo
singleton is a pattern, just a fancy word "make only 1 of this " ideally
A "Singleton" is just a name given to the sort of pattern of having a static variable that holds a single instance of a class
Since there is always exactly one instance of it ever, you know you can always access it
would be easier to understand if you learned plain c# first lol
knowing what instances are etc.
ohh ok but then when u mentioned the boolean digiholic what would i actually use that for in combo with the singleton
is that inside it?
You would give this class a variable
yeah i think so lol
then you could set and check that variable in some other script
And if this object is a DontDestroyOnLoad it'll keep its variables across multiple scenes
Unity kinda forces you to catapult into something like this because yeah between scenes is the easiest option believe it or not
since a DontDestroyOnLoad gameobject will be in a scene literally called DontDestroyOnLoad that does not get unloaded until you end the game/simulation
if you're making a bool in EnableVote just make sure its public, anything you must access through the singletons instance must be public (regardless of a singleton, this is a common thing to do if you want to access anything between scripts)
also do configure your VSCode. Its part of the requirement here and plus it will benefit your coding..
You should be seeing suggestions like this and red underlines especially the error you currently had should've been underlined red..
it says i need .dot and i already have unity installed on vs and i think i need nuget or sum likethat just notified me to be fixed as well
yes you probably are missing the .NET SDK . you should install that then restart pc it should be good to go after (assuming you already got the Unity extension and C# DevKit)
https://dotnet.microsoft.com/en-us/download NET sdk 9 is fine
is this by micrsoft safe for dev kit https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit so i can have net and unity work properly
yes thats the correct extension . if you're confused double check these steps, esp the experiencing issues part
https://unity.huh.how/ide-configuration/visual-studio-code
My player gets stuck between tiles for some reason, and I don't know why, even my skeleton, I used capsule colidor and it didn't fix it
Are you using a Tilemap? If so make sure you're using it with a CompositeCollider2D
Thank you so much
how can i update variables set in another script? the readyToAttack variable here is from a different script
Reference the instance of the other script-component and access the field from that instance
For example: cs public Player player; ... player.readyToAttack = false;
so Player here would be the script im wanting to access?
Yes
does the variable you change here have to be public?
No, unless you are needing to assign the member during runtime.
[SerializeField] private Player player;```would suffice if references can be made in the hierarchy-scene outside of runtime.
with my singleton function set up how do i fix it so the red line under EnableVote.Instance.Example; goes away
case "TedBearClick":
Debug.Log("Loading Slide...");
SceneManager.LoadScene("TR");
EnableVote.Instance.Example;
break;
Step 1. read the error message
Step 2. resolve whatever it's complaining about.
you'd need to do something with Example - assuming the error isn't something else since we haven't seen it.
this is the error im looking up issue debug rn
So yeah it's terlling you the problem
you have a line of code there that does nothing
so it's not valid
ohh ok
Imagine you have a line of code that just says "Apple"
well.. why did you write that? What do you want to do with the Apple?
it needs to be either an assignment (using =), a method call (MyMethod();), an increment or decrement (++ or --) or a call to some classes' constructor (new xxx())
my question is though if that is what defines a singleton occured 'Instance' and is what is undefined but is used as the way to define a singleton and should call a singleton in my code why is it that i need to define instance?
like it doesnt error in singleton code section and i thought u use instance to refer to the singleton
mg nvm i fixed it
so I am assigning during runtime so i made it public
(it's to disable attacking during dialogue)
but i am getting the object reference not set to an instance of an object error
You likely haven't assigned anything to your player variable/field yet.
Show where you've assigned your public field (via Editor-Inspector or in code etc)
So, you've got to assign sword an instance reference before using sword
alright so that's what the error said but im not really sure how to do that
drag and drop the gameobject that has that component on it
Since the reference variable is public, it will show up in the inspector when you click on a game object that has that script
And then do what nav said
wat?
Just vibe checking because googles are suprisingly not providing a great answer,
Bounds contain checking is like dirt cheap right?
"cheap" is a relative term in performance context. What are your alternatives?
Fair, I think it's the best option for what I'm doing but just curious if it's comparable to something like distance checking or raycasting cost wise.
With some simple caching i'd be doing 1 bounds check per update on say a dozen objects
On certain frames it would be like 20-50ish bounds check on one of those previously dozen objects
I can probably find more ways to avoid certain checks but if it's cheap enough it's probably fine. I'd profile it but for reasons i can't go into im not in an environment where that's as easy
You. Could "console profile".
Aside from that, raycasts are potentially the heaviest of the mentioned. Distance check would depend on when and how you calculate it(and whether you're using squared magnitude). It could potentially be the fastest. Bounds checks are pretty fast, probably on par with a distance check(though the latter can be quite faster).
Though, again, if we're talking 50 bounds checks vs 1 raycast, it's more nuanced
A raycast could be faster depending on the context
Yes it is cheap. Remember, AABB-anything is the driving force of games like Quake, and those ran on a piece of toast just fine.
hi
ty, this answers the question
ideally i'd do this sort of things via triggers and such but unfortunately not in the position to do so
Just for clarity, the Singleton pattern makes use of a static member called Instance (defined in the class) which sets a restriction for the class to be limited to a single instance and additionally allows us to access the property from anywhere we'd have access to the class-type. You'd still have to create and reference a single instance.
https://unity.huh.how/references/singletons
pretty sure the first part of raycasts are a broadphase cast against the AABBs
so bounds checking in a sense is sort of a lower bound on the performance of a raycast
Hey all, I made a new beginner script that uses the new input system and I'm wondering if I can improve my code organization anywhere. Currently, the script just has basic actions like Move, Jump, and Look for now. Happy to take any criticism as I want to write code that doesn't make other devs yank their eyes out...
https://gist.github.com/NullSimLabs/a054fc38f3780c23c485e46f823cdd24
Doesn't unity use some kind of quad tree based spatial search algorithm in this cases?
yeah and the things partitioned by the quad tree are the AABBs
Indeed, but it might be way less checks than they would do manually
oh certainly it's not checking every AABB
hello everyone i had a problem my friend export the scene and send me to import when i import that scene that will show all line error like show all unity methord underline in redcolor but that will run correctly but this is show in visual studio community what i do but other project didnot show that what is the problem i want to know please anyone tell about this , i already take actions 1) uninstall and reinstall visual studio community , 2) regenerate file , 3) uninstall and reinstall the vs community pakage in unity . any other thing i want to change please anyone tell about this
Looks like VS isn't properly setup to tie into Unity, because it doesn't recognize any of Unity's classes
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Pretty sure the info is in one of those links, but it's been a while since I've done it myself
ok bro thanks for your help i will try that
can I see your imports
using xyz
at the top of your file
what bro i did understand
if your problem isn't solved show me the first few lines of code you have
what are the errors telling you?
unity methord underlined in red color in visual studio community that is the error
the red underline is showing you where the error is
you're supposed to actually read the errors
mouse over one to read it
also double check if the errors are also in Unity's console and not just in VS.
that would seem improbable
@wintry quarry
ok bro but i when i type the code in visual studio community that is suggest the code and when ever i use unity methord that is look like methords it only looks like text
what error is it giving you bro
Why are you saying this instead of sharing what your errors actually say
hello everyone i had a problem my friend export the scene and send me to import when i import that scene that will show all line error like show all unity methord underline in redcolor but that will run correctly but this is show in visual studio community what i do but other project didnot show that what is the problem i want to know please anyone tell about this , i already take actions 1) uninstall and reinstall visual studio community , 2) regenerate file , 3) uninstall and reinstall the vs community pakage in unity . any other thing i want to change please anyone tell about this
Are you a bot?
sorry my mistake you ask explain your problem so i send this again
Might be some language barrier tbf 
No I asked you to read one of your errors in VS and share it with us
@tiny musk what language do you speak
tamil
அது என்ன பிழைன்னு உனக்குச் சொல்லுது?
when i use unity methords like Transform and Gameobject this kind of methord there this red underline show that the issue i am facing
When you have a red underline, put your mouse over it to see the message.
whoof
system objects is not defined or imported bro
definitely some kind of bad VS install or something
Those steps mentioned above are absolutely what I would have recommended to fix it though
So if they haven't fixed it, idk really.
@spare mountain already try so many time bro
so i try those thing so many times bro
Which version of VS Community are you using?
"Close the visual studio. Delete the .vs folder and restart visual studio."
VS Community 2022 bro
ok i will try that now
@tiny musk try reinstalling the unity plugin too
ok bro i will try
very thanks bro it is working
yay
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class Get : MonoBehaviour
{
public GameObject Gun;
// Start is called before the first frame update
void Start()
{
Gun.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player"))
{
if (Input.GetKeyDown(KeyCode.E))
{
this.gameObject.SetActive(false);
Gun.SetActive(true);
}
}
}
}
Whenever I click E when my camera is pointed at the object it still wont wont Activate the one that is suppose to activate
1 - Pointing your camera at an object won't run OnTriggerStay
2- Doing Input.GetKeyDown in a physics callback like OnTriggerStay or FixedUpdate is a bad idea. Those methods don't run every frame so you will often get skipped input
3- Get is a very confusing and vague name for a script
Oh.
What is the intention of this script? Which object is it attached to? What's it supposed to do?
What are you trying to accomplish
It's attatched to a game object that has no parent which when your camera is on it and you click E it should Activate another game object and disable that one
Ok well I don't see anything in the code that would do any of that.
OnTriggerStay is for physics objects that are touching each other when one has a trigger collider
nothing to do with cameras
I'm just trying to learn more but I must've ran into a terrible tutorial.
What you're describing sounds like something you would do with a raycast
Isn't raycast like from camera to world
or something
raycast is from wherever the hell you want to wherever the hell you want
You can write code that does anything.
I haven't really hard much of it
and I don't know how to actually make it do something in a script.
That is true. This is my 3rd or 4th day of learning so I guess.
Thank you though!
you're at the very beginning of your journey
Got any suggestions?
find a better tutorial 😛
How do I know which one is better?
Find one that uses a raycast
i am trying to make my character (2d) not slide down any slopes in my scene, i am using a character controller i got from online
i tried making some changes to it i.e. making my character velocity 0 when standing straight which did nothing
so what should i do now?
this is the part
when i add a navmesh surface why does this weird image appear at the object position
how to send you guys my code?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, 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.
thanks
this is my game setup.. my player is not taking damage at all
enemyAttackScript: https://paste.ofcode.org/kHQ2bXzj6YiuqFNykC6YsH
player Health Script: https://paste.ofcode.org/Wim2rFfSg4MA9zK6vqAAAN
health bar script: https://paste.ofcode.org/gshK4RYZDU5944VSfDe4zp
enemy Script: https://paste.ofcode.org/FcsYemAR74NPbDmGKVAbQd
pls helppp
What debugging steps have you taken?
i tried to debug.log to check if functions are happening
so... are they?
but the takedammage function is not bieng called i think
What about OnTriggerStay2D
let's start there
also why do you "think"? If you used Debug.Log you should know for sure if it is or isn't.
i would know if the function was bieng called
i added a log there well the trigger function is working
ie. it is able to detect whenever the player enters the collider
ok, and what else do you see in the logs?
just that
- DO you see errors?
- Do you see "Player taking damage"?
no
ok then clearly there is an issue with your conditions in OnTriggerEnter2D
yeah i think so too
if (other.CompareTag("Player") && Time.time >= nextAttackTime)
So keep debugging
you need to now log these things
As well as this: if (playerHealth != null)
i did not understand
Add more logs
print out the values of those variables and expressions
then you will find out why the if statement is failing to enter and call your takeDamage function
ok ig thnks
When my colliders are trigger, no problem but when isnt,my player just flies everywhere. I tried to exclude all layers for collision but it still did the same thing when it isnt trigger.What can I try?
is this an acceptable way to only invoke a C# event once without having to use flags:
public void Update() {
if (player.health <= 0) {
onPlayerDie?.Invoke();
onPlayerDie = null;
}
}
Alternatively with a wrapper like TriggerEventOnce(onPlayerDie);
Or you can do it in wherever you're reducing the health.
note i'm only like 3 months into doing unity and just a little longer with C#, but i've done coding for like 6 years, but anyways take this with a grain of salt (i just decided right now to start involving myself in this chat to help others out and in the process become better myself), but this is itself a flag if you think about it, your flag is just the null check of your event
If you want it to invoke once, then just invoke it once and leave it alone
Use a boolean to check if it invoked, don't unassign the variable
he wanted to not use flags
i.e. booleans
Why would you do this? If the point is making sure a player doesn't emit its death multiple times, then keep a state represented by an enum to specify if a player is alive or death
You are practically omitting the issue by doing this, and it will introduce unnecessary complexity
Better to just implement the missing feature
I'd invoke the event wherever the health is reduced, instead of update.
i would argue it's actually a clean solution as long as you are not "expecting" to see flags in your code, it might be harder if you are collaborating with experienced Unity devs used to flags
And have a flag there as well(in case objects bellow 0 health can be damaged)
you are effectively using flags while omitting an extra variable
This is anything but clean, because now your code unexpectetly removes events from the code just because one instance doesn't want it to emit multiple times.
That specific instance should better handle its use case, being that the player should only actually die once.
Only specific instances should subscribe/unsubscribe itself, it is not up to the invoking code to do this
so you are saying that the event should be executed even when dead?
but then handle the "already-dead"-case in the event code?
that has to be more inefficient
No, I am specifically saying that you should manage the player's state properly and prevent it from getting to this point in the first place
Which by itself would be more efficient
imo for it to even remotely clean it would have to be some class wrapping around the event, like a SingleFireEvent. I don't ever expect event refs to be null
Player reaches 0 health, you set the state to dead, you run the event.
right, i agree
Next time the method is called, you see the player's state is dead, you end the method with no logic being invoked
Even this is unnecessary if you just manage a state properly. There is no way to determine if the player is dead here apart from assuming he is because the events ar eno longer subscribed? That's silly
Just add a state lol
i guess i just assumed that there could be weird glitches or bugs where the player may die more than once and then this solution could be a decent catch for it
but of course removing the possibility of those bugs in the first place is ofc the cleaner solution
You can always refactor extra variables later. You can't refactor an event being unset when everything now relies on that
So is setting a state
I'd argue it's even better because you can implement a way for it to be an atomic operation
sure, i agree
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, 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.
hey guys can anyone pls help me
my player is not taking any damage
here is the code
playerHealth: https://paste.ofcode.org/z8sG3e8au62VQhkGCWFPYt
enemyAttack: https://paste.ofcode.org/t5tcCQvAVRbuqe936rMEUy
Did you add these logs inside just to tease us? If not, then provide some info on the debugging progress.
Seems odd, maybe just a school exercise
only the enemy is able to detect when it touches the player @teal viper
nothing else
Do you know what if (other.CompareTag("Player") ) does?
It would help a lot more if you were to share a screenshot of your console with the messages.
For future reference, the debug log Damaging player! you added would not show. This would have meant that the if statement failed, suggesting the tag is incorrect. Next time you can log the current tag being returned to quickly find out it is wrong
oh sry would keep in mind from next time
for now my bug is solved thanks tho

true. i only learned about events recently, so i'm currently refactoring my code to not check everything every single frame
that is a good point
more intuitive clarity
but then
Also very reusable. You definitely need to know a player's state later on anyway
Like movement, you can't move when dead. Stuff like that
Should I use a boolean? Or should I use an enum with two states? Or maybe a full-on state system with other things too?
oh, i just have it go lockControls = true, but maybe that's not the best way
I generally vouch for an enum even if it's just two states, for clarity. Who knows you might also want to extend the state to allow for a spectating state, for example
No, you're right. Ideally you would separate the logic and have the input lock using a separate system. It's just that for the sake of simplicity you might want to track the enum for now instead
Otherwise you have a lot of instances where you might have to lock or unlock the controls, risking a case where you forget it
so would this be something like
public enum LivingState {
Alive,
Dead,
}
Pretty much
You can also make a property IsAlive that checks against this if you don't want to explicitly check the num constantly
Though generally I'd just check the enum. Otherwise you might wonder in a month what IsAlive actually does as the logic is moved elsewhere
like
public bool IsAlive {
get => livingState == LivingState.Alive;
}
is that a property
Close
public bool IsAlive => livingState == LivingState.Alive;
This is the same thing. You don't need to explicitly specify the accessor if you just use the getter
Both work
and this prevents setting right
yes
Yes, you can only mutate livingState when you have access to it
yes, since there's no set accessor
ok, something that's actually been on my mind for a while:
is it at all common practice to also have an IsDead as opposed to checking !IsAlive?
Yes and as such you can specify how it's used. The individual get and set accessors can also not be added, or you can for example make them private (private set;)
Not really
You know it's all extra code and generally complications. That's why I suggest you just check the enum unless there ar emultiple things to check
Like not just the enum here, but also another variable. Then I would put it in a property.
ah, i see
and in that case using a property could be good future-proofing too i suppose
Also because state == LivingState.Alive is very informative and you can't really make a mistake here
That would only be the case if IsAlive as a property ends up actually doing more than just checking this state enum
But even then I would be careful, maybe an instance that uses this property doesn't want to check another variable and strictly check the state instead. This would end up causing undefined behaviour
@visual oasis why not handle it wherever you take damage? is health public or something?
So that's why I would still suggest to just set the variable and check that instead. ONLY use a property if you want to change the accessibillity
_livingState would be private, but you'd have a public property to access it (but not set it)
it is for the sake of HUD
is the health bar retrieving the health, rather than the player controller setting the health?
anyways that aside - how do you deal damage?
the health bar retrieves the health, yes
and...
my game's a 1D (forward and backward movement only) tower defence
so when an entity attacks, it triggers a DealDamage() function in the GameplayManager instance which then checks what's in range and deals damage to entities that are indeed in range
or if it's single-hit attacks like arrows, it checks what's closest
This doesn't use events at all, and I'll be looking at how I can refactor it to use them instead
well it doesn't have to necessarily use events
// class GameplayManager
public void DealDamage(string entityId) {
GameplayEntity entity = entities[entityId];
foreach (GameplayEntity enemy in entities.Values) {
if (enemy == null || enemy.allegiance == entity.allegiance || enemy.currentState == GameplayEntity.State.Die)
continue;
if (entity.IsInMeleeRange(enemy.xPos + 0.2f * enemy.direction))
entity.MeleeHit(enemy);
}
}
my point is, if you put dealing damage and the death trigger together, it becomes much easier
yeah, I do now plan on doing that
you aren't actually dealing damage here though...?
where are you actually dealing damage? as in, updating the health variable
entity.MeleeHit(enemy)
public override void MeleeHit(GameplayEntity target, float damage) {
target.Damage(damage);
meleeWeapon.data.PlayHit();
}
that's still not it
public virtual void Damage(float damage) {
health -= damage;
}
yes
so you could just..
public virtual void Damage(float damage) {
+ if (health <= 0) return;
health -= damage;
+ if (health <= 0) onPlayerDie?.Invoke();
}
instead of doing it in Update
yeah, i'll do that
this was the first thing suggested (by dlich) lmao
well, i did say
i'm also wondering how i can optimise the enemies-in-range checking system, but that's a question for another time
probably overlapshere or smth
like, a physical sphere?
it's my first time using a 3D game engine, so all my collisions are done with pure math and code rn
no collision boxes
the physics engine
is it faster though
in my mind it'd be slower because it's a whole engine vs a simple calculation in code
probably not. it's not gonna be slow enough to matter though
they're tried and tested systems
but is it faster 
probably not
i mean, i guess it depends on the context/scale
your thing scales by how many enemies there are overall
using the physics system, i'd expect it to ignore very far things, but im not sure how it really works internally.
i'd expect some kind of optimization there, at least
but there probably is some overhead for the system as a whole, yeah
but we're talking on the scale of microseconds here, it's not gonna matter
hmm hmm
that means i need to add a collider to all my objects though, right?
the entities
yeah
if you had an entity prefab you would just add it to that prefab
well, i have a prefab for each entity
individual
oh i see what you mean
err entity type yeah
so farmers vs sword warriors vs spear warriors etc.
each with their own different meshes and whatnot
yeah ok that makes sense
are they just individual prefabs completely, or are they variants (with a common base)?
completely individual
is anyone able to help me i got an assignment due tomorrow and i just need to figure out this one bit of code for then i can show the teacher tomrrow? anyone?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
especially that last point - noone can help if we don't know what you need help with
what if i add the collider in code
yuh
wouldn't you be able to just multiselect all the prefabs and add a meshcollider to all of them at once?
or i guess capsulecollider if you want a simpler view
Adding components at runtime will likely be slower. I wouldn't bother with the physics engine just for distance checking if you can manage it yourself.
not sure about any possible caveats with a meshcollider vs a primitive collider - i usually work in 2d
So my goal is to call a function once all the dialogue is completed that will then display a button for the player to press, the spot to which the dialogue is finished is in the first image and then i want it to enable the button
srry if that dosent make sense just tell me
the gameplay logic might be 1d, but everything else is gonna be 2d or 3d
what's the part you're having issues with?
i cant find anything online about what code to put their
Your !ide does not appear to be configured as it lacks basic syntax highlighting. Please configure it before asking for help.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
to do what, call a function?
uhh vs code
ok click the button labelled vscode
i already have vs code setup tho
it's not configured, follow the steps provided there
im not sure myself, im just learning all this and my teacher dosent even know anything about it its stupid, but i want after the else statment that it enables the button
alright will do
so you would call SetActive(true) on the gameobject you want to make active, pretty straightforward
but the code is set to the dialogue box and the button is in a differnet place
Yes, but judging from the screenshot it is not fully configured. Generally I do advice you use Jetbrains or Visual Studio as the setup is much easier there, but VSCode also works.
alright
btw everything in the link you sent me i already did
seems to have not worked. have you been presented with the "install .net sdk" window?
not sure i downloaded unity a few months ago where can i check if thats done
I personally am unfamiliar with VSCode. Unfortunately I can't help with that. If you use Visual Studio I could provide the steps some more
srry its a bit late and i really just wana get this thing figured out
thank you tho
check the output window in vscode
it should be beside the terminal - if you don't have that open, i think the default keybind is ctrl+`
here
thats what my output looks like
hold on i do get errors when i open the app
is it anything to do with this
yeah you haven't installed the .net sdk
now reload the window and see if it loads colors now
better?
im on mac if that makes a difference
try going to unity > preferences > external tools > regenerate project files
and make sure the external script editor is set to vscode
i cant find the answers to my questions but just finished my first game and singleton and bool ty everyone for helping 🙂
aight ima go to bed now its like 1 am for me if u figure it out please dm me or ping me same thing with my original problem thanks for the help.
wait like this?
yeah there you go
now about this - are you familiar with using the inspector to set variables at all
no mind explaining please?
i apperciate your patience btw
my spelling 💀
fields that are public or marked [SerializeField] will be shown in the inspector
you can use a field typed GameObject to get the button so you can call SetActive on it
these are pretty basic unity concepts so...
oh yes i have used that before but only on tutorials i dont really have a understanding of it let me give it a go
What question?
is there any way to call component of the prefab? I'm trying to control play state of the particle graph
if you set vfx_slash to the desired component, you get that type back from Instantiate
it was from last night in regards to singletons and booleans i really just wanted anyone who helped to see that so they know it resolved itself
instance.GetComponents<VisualEffect>.playRate = 0.05f; doesn't work, how do I let it recognise I have a Visual Effect that can be manipulated?
(I passed argument GameObject instance into SuspendSlashes)
working i appreciate everything
well, that's not what i said to do, is it
I'm sorry I'm not too sure how to do it in the first place lol
you can pass types other than GameObject to Instantiate, and you'll get the same type back as a reference to that component on the newly created gameobject
so you could type vfx_slash and slashvfxinstance as VisualEffect instead
(and then use slashvfxinstance.gameObject in the Destroy call)
also about this - then say so lmao, don't just ignore it
hi im pretty new to programming and tried to follow a tut for my assignment. and i cant seem to drag the script to the inspector. i dont get what class is it refering to because i already checked and it is already the same as how the tut provided
I thought I was trying something genuinely related to your suggestion lol
i'm happy to explain if you need clarification, but im not gonna preemptively explain every single thing, i don't know what you already do or don't understand
Make sure there are no compile errors and that the file name and class name match.
it matched. i already checked
and what about the other thing?
https://www.youtube.com/watch?v=hdpIvye87Wo&t=531s
im stuck here at 11:40
🔔Get Quiz Game Asset :
➡️ https://grafikgames.com/unity-quiz-game-template
In this unity quiz game tutorial for beginners, you will learn how to create a Quiz Game in Unity. Follow along as we go step by step to make a Quiz Game with 4 Replies in your Unity game. From setting up the project to implementing game mechanics, you'll gain v...
ok... and do you have compile errors
yeah
then that's why
It says to ensure there are no compile errors AND that the file name and class name match. Everything in the message must be fixed to add the component . . .
okayy i'll try to check it again
What if you copied your code from your original QuestionManager and pasted it in a new monobehavior script?
Ahh nvm, you already said there were compile errors
If you're still having issues please share code 🙂
I have a coroutine trying to listen to a variable in a singleton timestopTriggered but when I try to do yield return new WaitUntil(() => !GameManager.Instance.timestopTriggered); within the coroutine, nothing happens, why?
{
visualEffect.playRate = 0.05f;
yield return new WaitUntil(() => !GameManager.Instance.timestopTriggered);
visualEffect.playRate = 1f;
}```
You need to show us the error and the code with the error so we can see what is wrong . . .
Does the coroutine run? Place a log before and after the yield to check . . .
You beat me to it lol ^^
not triggered, but have this error instead
context:
{
var hit = Physics.BoxCast(
center: castCenter,
halfExtents: vector3HalfExtents,
direction: slashDirection
);
VisualEffect slashvfxinstance = Instantiate
(
vfx_slash,
position: castCenter,
rotation: slashDirectionQuaternion,
parent: root
);
Destroy(slashvfxinstance.gameObject, 1);
}
else
{
var hit = Physics.BoxCast(
center: castCenter,
halfExtents: vector3HalfExtents,
direction: slashDirection
);
VisualEffect slashvfxinstance = Instantiate
(
vfx_slash,
position: castCenter,
rotation: slashDirectionQuaternion
);
SuspendSlashes(slashvfxinstance);
Destroy(slashvfxinstance.gameObject, 8);
}
```
and which line throws the error?
check the value you've set in the inspector, make sure it actually has a VisualEffect component
might have to redrag the prefab in to get the right component? don't remember how it internally works
didn't say which one, I only know that its probably instancate error (as seen in the error text)
Do I need to attach the visual effect component?
it does say though, PlayerCharacter.cs:745
(
vfx_slash,
position: castCenter,
rotation: slashDirectionQuaternion
);```specifically, in the else part of the if...else
when I instanciate it's not valid
regardless of if the code is running if or else
And what type is vfx_slash?
Visual Effect
see this
try clearing the slot and dragging vfx_slash back in, i guess?
it worked lmfao
doesn't fix that the coroutine doesn't run tho
oh lol oops
any recomended site or literature to study the latest unity6 urp shader program library?
Thanks a lot, it works perfectly now
hey, when i update the values of the values of the code of an actor/prefab, how i can update the actor to have them as well?
what do you mean by actor exactly?
Hi everyone! I’m working solo on a Unity project inspired by Black Emperor — it’s a fast-paced 2D side-view motorcycle game where the player glides up and down a winding road, trying to stay alive by keeping the bike on-screen and on-road. I've attached a video and screenshot of the code.
Core Mechanics:
The road scrolls from right to left (bike stays mostly centered).
Player can move the bike up/down and accelerate.
If the bike goes off-road, it slows down.
If it falls off the back or front of the screen (too slow or too fast), it's game over.
I'm using trigger-based detection to see if the player is on-road or off-road using tags like "Road" and "Game Over".
The Issue:
I’m using multiple modular road segments, each with a BoxCollider2D marked as Is Trigger.
I check for OnTriggerEnter2D to set bikerIsOnRoad = true and OnTriggerExit2D to flag off-road and apply slowdown + dust FX.
But when the player moves from one segment to the next, the OnTriggerExit2D from the old segment fires before OnTriggerEnter2D on the new one — so it wrongly triggers my “off-road” effect, even though they’re still on the road.
I’ve tried a buffer system (like checking for a short delay) and also using a roadContactCount to track how many road colliders the player is in. Still not quite right.
Has anyone faced this before? What’s a clean, Unity-friendly way to handle overlapping/adjacent trigger zones in a scrolling tile-style system like this?
Bonus Question:
Would you recommend designing the full road in something like Photoshop and slicing it, or building it directly in Unity using tilemaps or road segment prefabs?
My gut says Unity would be easier for adjusting difficulty and randomness later, but I’m curious how others approach this — especially for curving, procedural-ish 2D tracks.
Any advice or references welcome — thanks in advance!
I would redesign this. Rather than the road having a collider, you should have colliders on the edges/boundaries of the road to detect when the player exits the road. THen it's very straightforward to detect when the player leaves the road.
Would you recommend designing the full road in something like Photoshop and slicing it, or building it directly in Unity using tilemaps or road segment prefabs?
You probably want to look at SpriteShape: https://docs.unity3d.com/Packages/com.unity.2d.spriteshape@3.0/manual/index.html
Hi everyone! I imported a Unity project from a zip file and everything works fine. Now I want to use Unity Recorder to create a 3-minute video from my scene. I'm using Unity 2022.3.5f1c1 and Unity Hub 3.3.3.
Can someone guide me on the best Recorder settings or check if I'm missing anything?
Thanks in advance! 🙏
Not a code question
I did consider this when I first started designing it - I don't know why I decided to go with the road being the collider. I guess I was hoping I could make the whole track and then just asign the whole shape as a collider but that seems to not be possible. I'll have a go at that now!
I Did It!
Made It Rotate by 15 if you press a or d
Hey there! Not entirely sure if this is the correct place for this, but it seems like an easy enough (or should be easy enough) thing to work around.
I'm using an Event Trigger on an object I instantiate on runtime. I've checked that I have an event system running, and other Event Triggers on objects in the UI seem to be working quite well. For whatever reason though, the method I am calling here in the Event Trigger isn't getting called.
The *below screenshot is during Play mode.
Could this be some weird UI Image Layering issue? The crafting menu uses Event Triggers for when the mouse hovers over it, and I'm wondering if maybe that is getting in the way or if it's something else
Using a Debug.Log() to check if the method was called has shown me that the method just isn't getting called whatsoever
I also figured it may have been something to do with the sprite mesh, but the Image component is not using the sprite mesh, so the entire square area used by the object should be active and responsive for such a task
What other components are on the object?
Also are you definitely doing a full click-and-release sequence while keeping the mouse over the object?
Just the UI Image component, the Recipe script as mentioned in the Event Trigger, and the Event Trigger itself
I'm 100% sure
"Raycast Target" or "Blocks Raycast" is enabled on the Image?
Raycast Target is enabled on the image
Ok the most likely thing here then is some other object is blocking it
try disabling other UI elements in your scene until it starts working
the most likely culprits are:
- separate canvases
- any other UI that is lower in the hierarchy than this object
I only have one canvas, and I have disabled every object outside of the parents of such object and it is still unfortunately not working
what about the child objects of ItemTemplate(Clone)?
Oh-- it's just a TextMeshPro obj
Can you try disabling that?
It won't let me for some reason while I'm paused in the game view
I will say though that it only covers beneath the ui image, so it shouldn't be getting in the way whatsoever
Another thing to check is try pulling it out of the scrollrect/mask situation
alright bet lets see
Yup, that did it
The event trigger is triggering when it's not a child of the containers and such
Further update: Even when setting the parent objects to the Ignore Raycast layer (which raycasts are what I'm assuming the event trigger uses), the child object-- still set to the UI layer-- is still not receiving any of my clicks, and so I cannot get the event/method to trigger
Yeah I fr cannot figure out why this is happening
I can't really afford to take it outside of the scrollrect/mask with how I'm setting this up
Is it normal to have a OnLookPerformed and OnLookCanceled for a Look action in my action map? Or should I just do something like Mouse.current.delta.x.ReadValue() in void Update? a I'm having an issue where my view keeps spinning without touching the mouse about 20-30seconds into playtime.
// Action: Look
[SerializeField] Transform cameraTransform;
[SerializeField] float mouseSensitivity = 1f;
float xRotation = 0f;
Vector2 mouseInput;
void OnEnable()
{
// Enable action map and actions
playerInputActions.Player_OnLand.Look.performed += OnLookPerformed;
playerInputActions.Player_OnLand.Look.canceled += OnLookCanceled;
playerInputActions.Player_OnLand.Enable();
// Lock cursor
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
// Get raw look input (mouse delta)
float mouseX = mouseInput.x * mouseSensitivity;
float mouseY = mouseInput.y * mouseSensitivity;
// Clamp vertical camera rotation (pitch)
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
// Apply vertical rotation to the camera
cameraTransform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
// Apply horizontal rotation to the player (yaw)
transform.Rotate(Vector3.up * mouseX);
mouseInput = Vector2.zero;
}
// ===[Look Input Action Callbacks]===
void OnLookPerformed(InputAction.CallbackContext ctx)
{
mouseInput = ctx.ReadValue<Vector2>();
}
void OnLookCanceled(InputAction.CallbackContext ctx)
{
mouseInput = Vector2.zero;
}
It would be way simpler to just read it directly in update and skip the events
For continuous style inputs, this is often the case
void Update() {
Vector2 lookInput = playerInputActions.Player_OnLand.Look.ReadValue<Vector2>();
// the rest of your code
}```
just one line of code instead of like 5 + variable + two functions
That's what I was starting to think but I like the structure of having a method(s) for each action😂 Is it common to not have methods for actions?
The other option here is to set this action as a pass-through
then you only need to subscribe to performed
because the pass-through only takes continuous input and never sees a .canceled?
Passthrough simply fires off performed for any change in the actuation of the control.
Value has a bunch of logic deciding if any given change in actuation should fire off started, canceled or performed depending on the interactions (or default interaction) on the action
I also cannot seem to find a workaround with buttons either.
Thanks again for the Update method suggestion. Just tested things and mouse bug is gone. Now time to figure out why I can only open my interact/open my door on the door hinge. Maybe I might just cheese it and extend the colider around the child door object to see if that makes the interact box bigger
Any more wisdom to add on to this? I'm trying to keep everything within the scrollrect, and I cannot find a workaround using Buttons, Scriptable PointerClick events, etc.
most likely to do with the settings on the scrollrect/mask/viewport etc
Would the Event Trigger on the Container for all of the scrolling elements possibly be interfering?
absolutely yes
EventTrigger is unfortunately kind of a sledgehammer
It subscribes to ALL of the UI events, and then silently ignores the ones you don't have listeners for
it's less intrusive if you make a custom script with only the ones you care about, e.g. cs public class MyClickListener : MonoBehaviour, IPointerClickHandler
Actually the mouse issue is back lol. For some reason whenever I open this door and leave, the mouse starts to spin. Maybe my interact script is messing with things?:
void Update()
{
Vector2 mouseInput = playerInputActions.Player_OnLand.Look.ReadValue<Vector2>();
// Get raw look input (mouse delta)
float mouseX = mouseInput.x * mouseSensitivity;
float mouseY = mouseInput.y * mouseSensitivity;
// Clamp vertical camera rotation (pitch)
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
// Apply vertical rotation to the camera
cameraTransform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
// Apply horizontal rotation to the player (yaw)
transform.Rotate(Vector3.up * mouseX);
}
{
// Example: Raycast from the camera to interact with objects in front of the player
Ray ray = new Ray(cameraTransform.position, cameraTransform.forward);
RaycastHit hit;
float interactDistance = 3f; // Adjust as needed
if (Physics.Raycast(ray, out hit, interactDistance))
{
// Check if the hit object has an interactable component
var interactable = hit.collider.GetComponent<IInteractable>();
if (interactable != null)
{
interactable.Interact();
}
}
}```
Mouse movement issue
Even though when I standstill, the Vector2 debugging as (0.00, 0.00) but the rotation.y keeps incrementing(potentially 1unit per frame). I've tested in game-view multiple times and it seems like the rotation.y is always positively going up when it's bugging out. I'm not seeing the rotation.y decrease in value. I'm starting to think that if the Vector2 input has a x,y value greater than 90 or less than -90, it bugs out the mouse input
I think I have a fix that probably isn't the best solution. If I enable the xyz contraints on the player, the player mouse movement doesn't bug out and slowly rotate at times. So I think that means something in my physics is causing the slight turn
void FixedUpdate()
{
if (moveDirection != Vector3.zero)
{
float runSpeed = isSprinting ? MoveSpeed * sprintMultiplier : MoveSpeed;
Vector3 direction = transform.right * moveDirection.x + transform.forward * moveDirection.z;
Vector3 movement = direction * runSpeed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + movement);
}
}
what differences exist between
rb2D.linearVelocity and rb2D.MovePosition
The latter is meant for kinematic rbs also by default ignores colliding into other walls / colliders
Is this a good idea for keeping the project organized? I have a door that I created in unity (not fancy, just using primitve shapes and basic material) and this is how I organized the animaitions, materials, and scripts. Is this a good organization strategy for objects that have an animation, material, and script?
So if i want to move anything with a Rigidbody2D
(Enemies, friends, etc). It must be linearvelocity
Its really up to you, as long as you keep it consistent.
Some go with your style, some go with having master root folders for animation, meshes, materials, etc.
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rigidbody2D.html
you can use MovePositon, you can use AddForce, you can Set the velocity manually.. always multiple ways to do things
Making a door open one way is easy. Making it open both ways is a whole nother level lol
Learn how to implement doors in Unity! In this video you'll learn how to make:
⚫ Rotating Usable Doors
⚫ Rotating Automatically Opening/Closing Doors
⚫ Sliding Usable Doors
⚫ Sliding Automatically Opening/Closing Doors
You'll also learn how to make the rotating doors open AWAY from the player, instead of always opening only one directio...
basicly you get the player position and rotate the door based on player position.
hi has anyone experience with VR controllers? i have bit hardtime with them as i have no idea how their inout works
i also have a problem where i cant see my raycast line for some reason i have tweiked the range a bit and also i cheecked the gizmo it is there but i cant see it
maybe #🥽┃virtual-reality for the question about vr controllers. As for the raycast, raycasts dont draw anything to screen. Are you drawing it with like gizmos? Show code if so
ah i use debug.log Debug.DrawRay(shootPoint.position, shootPoint.forward * rayRange, Color.red, 100f);
can you show a screenshot of the game view? it should show up in the game view if the gizmos button is enabled.
or are you sure the code is running, and the position is where u think it is?
do you see it in the scene view? it should always appear there at least
nope
wich is annoying bc in other projects i can see it using the same emthod
for some reason ihave only this problem when i use the VR built
well then the first thing id do is make sure the code is even running, maybe log the position while you're at it
then check if you see it in the scene view. you can put the game view side and scene view side by side
Am I on the right track here? I'm trying to make a door that can always open away from the player
using UnityEngine;
public class SingleDoorControl : MonoBehaviour, IInteractable
{
private Animator animator;
private bool isOpen = false;
private bool openedForward = false;
[SerializeField] private Transform playerTransform;
[SerializeField] private Transform doorForwardReference;
void Awake()
{
animator = GetComponent<Animator>();
}
public void Interact()
{
if (!isOpen)
{
Vector3 toPlayer = (playerTransform.position - transform.position).normalized;
float dot = Vector3.Dot(doorForwardReference.forward, toPlayer);
if (dot >= 0)
{
animator.Play("SingleDoorOpen_Backward");
openedForward = false;
}
else
{
animator.Play("SingleDoorOpen_Forward");
openedForward = true;
}
isOpen = true;
}
else
{
if (openedForward)
animator.Play("SingleDoorClose_Forward");
else
animator.Play("SingleDoorClose_Backward");
isOpen = false;
}
}
}
just a glance seems ur on the right path..
either ur on this side -> positive
or that side <- neg
then just swap out the conditional as needed if u happen to get it backwards 😄
trying to make a top down shooter, but I can't figure out how to make the character shoot, the tutorials I'm finding use the legacy input system and I can't get my head around the new one
well do u want to get ur head around the new one.. or are u just concerned bout finding a way to use the old one?
b/c u can swap.. and/or use both even its just a setting
tbh, I have no idea how to do it for either, I never actually used the input systems for myself, I've just been watching tutorials and have no idea how they work
well its worth learning the new one..
I will, is there a resource for me to do so?
if u dont.. or would rather wait.. u can always swap it to the new one later when u feel mor comfortable.
i use Both in the project settings so i can learn as i go
its not completely deprecated yet 😄
as for resources.. i dont really know of any off-hand.. b/c theres soo many ways to do inputs so theres soo many different resources
Aye this works. It wasn't at first because the Door Controller animator didn't update with the new animations and then some of them still had the look property enabled
also, how come people use [SerializeField] instead of Public? I get that the former doesn't let scripts access others, but why is that important?
I've only been learning unity for a little less than a month now and the new inputsystem takes a long time to understand. For basics, I believe your action would be something like:
Action: Shoot
|-> Left-Click (Action Type = button)
Then something like:
using UnityEngine;
using UnityEngine.InputSystem;
public class Shooter : MonoBehaviour
{
private PlayerInputActions inputActions;
void Awake()
{
inputActions = new PlayerInputActions();
}
void OnEnable()
{
playerInputActions.[YourActionMapName].Shoot.performed += OnShootPerformed;
}
void OnDisable()
{
playerInputActions.[YourActionMapName].Shoot.performed += OnShootPerformed;
}
void Shoot()
{
Debug.Log("Bang!");
// Add shooting logic here (instantiate bullet, play sound, etc.)
}
}
In software systems, encapsulation refers to the bundling of data with the mechanisms or methods that operate on the data. It may also refer to the limiting of direct access to some of that data, such as an object's components. Essentially, encapsulation prevents external code from being concerned with the internal workings of an object.
Encaps...
use [SerializeField] when you want your variable to be editable within the inspector but still private. Public allows the variable to be used outside the class and should be used only be used when needed because you can only have 1 public variable with that name. So if you had a public speed variable, now you can't declare another variable with the name speed.
I wanted to make sure I added as much info as possible so I sent your question to copilot as well. Here's that response:
Why use [SerializeField] private instead of public?
Encapsulation:
Keeping fields private means only the script itself can change them. This protects your data from being accidentally changed by other scripts, which helps prevent bugs and makes your code easier to maintain.
Inspector Visibility:
[SerializeField] lets you edit the value in the Unity Inspector, just like a public field, but keeps it hidden from other scripts.
Cleaner API:
Other scripts only see what you intentionally expose (via public properties or methods), making your codebase easier to understand and use.
Best Practice:
It’s a core principle of object-oriented programming to hide internal details and only expose what’s necessary.
Summary:
[SerializeField] private gives you the best of both worlds:
Editable in the Inspector
Protected from outside scripts
Cleaner, safer code
Use public only when you want other scripts to access or modify the field directly.
that makes sense, thnx for the help
To save you from yourself
lol
If it's not supposed to be edited from another script the best way to ensure you don't do it out of lazyness is to make it impossible
Reminder that regardless of accessor, you're only limited to one specific name per class member.
also if you don't specifically declare the variable as private, the default access modifier is private so the variable will still be private. Same thing for methods.
private void Shoot(){}
is the same as
void Shoot(){}
Did you get your shooting working?
not really, getting a bunch of errors, not sure what they mean either
#📖┃code-of-conduct dont post AI answers. also "So if you had a public speed variable, now you can't declare another variable with the name speed." is just wrong
oh the bracket is your input action name is the name of your action map
some of this stuff, it's saying, does not exist
Hey I marked it by saying it was from copilot. And you're right, I should have said you can't have another public speed variable
most likely it can't understand your code because of the syntax issues
you have extra closing braces and the random [] in the middle of your script
the [YourActionMapName] thing isn't valid. you're supposed to put your action map name there, without the brackets
this will be the name of the input system you created then create a field (I usually do the same name as the inputsystem but with camelcase) to store an instance of your input actions
oh, I thought that was meant to be a string, like "..."
isn't that supposed to be the generated class
I think there's some miscommunication here. Regardless of accessor, you aren't allowed to have more than one variable with a specific name. cs private float speed; private float speed;//illegal
i see what you're trying to say now - "the input system you created" is really not the right way to describe it lol
im gonna have enemies that deal damage on attack and collision, some only via attack, some only via collision, the thing is, if i enable a hitbox that is a child of the enemy as the attack, that still just counts as one and the same type of collision as if you walked into the enemy. to distinguish between those two attacks, im thinking ill have two physics layers, one for enemy body and one for enemy attacks, for enemy body, it has ontriggerstay2d logic with a cool down, and for the hitbox, that one can be triggerenter, is this a good solution or am i wasting a physics layer here?
there are 32 available layers, that'll be fine
but like... is it not a slippery slope
what else are you gonna have
yea thats the only solution that came to mind, i mean, i could use tags but i feel like thats a little messy
you wouldn't separate fire type attacks from water type attacks, you'd have a separate, more flexible system for that
Agreed! I should have clarified more 😁
no, i mean, what other layers are you gonna have
was vague mb
Yeah the new input system somewhat clicked today for me so now I'm just dealing with saying the right lingo going forward lol
its might be a big project, there is a lot of concepts that i wanna add that i havent broken down to unity implementations yet, so i cant say for sure how many ill need, im careful with my use of layers, so probably not many, and considering enemies are like very central, i dont usppose two layers for them is a waste. currently i only have ground, and GroundBound layer and player layer
the technically right way would probably be "input actions asset" but "action map" "input map" "input actions" would all work - just not the entire system
think about interactions that are core to the actual world or universe of the game - those would be layers
more specific, flexible systems would be their own systems that you write yourself
Let me send you my player controlls that uses the new input system for reference. Go through each one of my actions from the variables to the methods to help you understand the flow of things. DM'd you, didn't want to "clear the chat"
thnx
regarding this specifically though - you could use layers to distinguish, but since these aren't actually different interactions, another approach would be to let the damage dealer - the projectile/enemy - handle the attacking. that way each thing knows how it deals damage, whether continuously or one-shot
can't stop you from DM'ing, but fyi, it's generally not recommended. community servers exist for a reason, so that multiple people can help or check answers
yea i think enemies could use two layers, its just, scary sometimes to decide stuff as a new and solo dev.
i could potentially give the attack hitbox its own script, where i can also give it different variabels that define the type of attack it is, this script can then also be attached to enemy projecttiles.
like for melee attacks, dont destroy gameobject on collision, etc
True, I was being lazy and didn't want to make a GIST of the player controls but here it is:
https://gist.github.com/NullSimLabs/a054fc38f3780c23c485e46f823cdd24
helloo, quick question, i was following this brackeys tut and he did not use a refrence object like he always did but used the findobjectoftype thing because he said that when tho playerobject was reset the refrence would be lost. Then to reset the scene and the object he used this built in method that saved the refrences, now im wondering why did he use the findobjectbytype and not create a refrence object in the first place?
Its hard to actually understand from your message but perhaps it was to be more beginner friendly?
Finding by type isn't too bad if done sparingly to init a scene or some object.
He did that to make the tutorial simpler, that's all.