#π»βcode-beginner
1 messages Β· Page 656 of 1
Whats a good way to learn C#. without unity learn. And Youtube Videos that are discontinued. And is there any way to practice unity C# code without having Unity installed?
The intro to C# link (that's currently under maintanence for me) that's pinned to this channel
You need to have Unity installed to program with Unity. But there's nothing stopping you from learning C# without Unity.
Hey does anyone know how I might be able to fix this chain?It's a bunch of hinge joints connected to each other and then the player, But it's going all over the place
i want it to not change so much either pull the player in the direction of the box, or the player pull the box
it's doing that because:
- the adjacent bodies in the chain are overlapping each other
- collision between the connected bodies are presumably enabled.
when objects physically overlap each other, the physics engine tries very hard to disentangle them
Okk
So If I add some distance between them ? and disable collisions? will it fix it?
Tried changing the mass of each chain to 2 now it seems to be working
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
does anyone know why the videos all say No compatible source was found for this media.?
presumably because someone on the Unity Learn team screwed up.
Looks like all the videos on Learn are like that. I would just try again tomorrow
no doubt someone will fix it soon
I'm using UI Toolkit to make 2 menus, each is parented to a GO which get enabled/disabled
And I ran into an issue that the first menu works, but the second doesn't trigger any clicked events (hovers work)
I could not find what is causing it so right now second menu is literal copy of the working one, and this did not change anything.
OnEnable runs fine, OnDisable unsubscribes the listeners, there are no missing references, but click events never trigger
this is killing me what am i missing?? π
Why did i get the Addcomponent asking for invalid type while the "Draganddropscript." exist and also how do AddComponent works?
- Why are you doing it like this and not just using the normal generic method?
- GetType doesn't allow random full stops
there is the full stop in my scriptname.
No there isn't
What do you mean normal generic method?
ComponentType myComponent = otherGameObject.GetComponent<ComponentType>()
Hello, sorry for my question but I'm new there. I have a display bug in the hierarchy tab when I want to hide/display a gameobject, the eye icon is locked and I can't display again my gameobject. Do you know the bug?
To fix it I have to delete manually the file "SceneVisibilityState.asset"
But it's an annoying workaround
this isnt a code question. provide screenshots of what you mean in #π»βunity-talk
What the heck. I have a serialized variable here in a monobehaviour. Nothing is setting the variable except for me, in the editor. But no matter what, it's reading as the default value
(happens on Start)
this reads as 0 no matter what the slotnum is
SlotPosition is not the same as SlotNum? π€
omfg, accidentally added two variables for the same thing
.... pls ignore
Got confused because slotNum was serialized while slotposition wasn't (forgot the [field: Serializefield]). So my brain conflated them. Everything works now
error on getcomponent any ideas?
this.gameObject.GetComponent().material.color = Color.cyan;
what add for?private void Start
That is not at all how you use it, that's why
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GameObject.GetComponent.html
thanks!
You should make it not have that
Hi! I need help setting up damage functions for my area of damage BoxCollider2d, but its not working for me from the tutorials I've watched. Im completely new to Unity and have never programmed before this current project
Show code, and be a bit more specific about what isn't working about them
alr 2 sec
hi... i add this for my cube on screen, for other cube for change material and still not working :/
public Material mat;
public GameObject gameobject1;
void OnMouseDown()
{
gameobject1.GetComponent<Renderer>().material = mat;
}
Show the inspector of this object
Also if gameobject1 exists solely to get it's renderer, you should just make the variable of type Renderer instead
and i add difrent color for this
Where is the script
is on other cube
That's the inspector I asked for
This one is irrelevant
i click cube and still not change color
after start scene
i testing, and trying find solution
Put a log in the function and see if it's running at all
It has a collider, isn't on a canvas, and has all its variables set so it should be running the function
nothink after start
its should work but not its working
no error or anythink after click
on log
So, you added a log to the function, and don't get the log when you click on this object?
Then there is probably something else in front of this object that is receiving the click instead
finally i found solution
just delete cube and add
same cube
okey
that was a glith or somethink difrent
thanks for help!!!
if i have a async void, then if i want to make it return something i have to make it a Task<T> right?
or Awaitable<T> if you are on unity 6+
which one will be better? is task using GC or something like that cause i quite cant remember really
on your needs and what you are actually doing. and if you are concerned about performance then use the profiler
https://docs.unity3d.com/6000.0/Documentation/Manual/async-awaitable-introduction.html
see Awaitable compared to .NET Task
I am UniTask 's no 1 fan so ofc I recommend that
Yo I'm just trying to figure out movement right now and was wondering if I need to download an external app to write code because I can't figure out how to do it in Unity?
!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
yes you do , see βοΈ
thanks for showing me, i just got it working π π
Hello, I'm just wondering why my sprite is changing location when I'm running a different animation? I have an idle animatino clip, and a running animation clip. The sprite is offset upwards when I run the running animation clip, why is this? I don't think I encoded any positional data in the animation clip
Is there a setting I can modify to manually change the offset to none
not a code question, but sounds like the pivot point is wrong
Oh ok my bad
yes you're right! Wrong channel but the pivot point was off center by default for my running animatinos
ty)
any idea why im getting a error on ChangeState saying it doesnt exist
does ChangeState exist
tutorial i followed the guy just adds it without additional code lol
Show code, show error
solved it, me being a dumbo
i swear everytime i ask a question in here, i not long after figure it out
hellos! I'm working on a game with a cutscene that triggers upon the player colliding with a trigger. currently, the animation plays on loop immediately upon the start of the scene, and the script doesn't even come into effect. how do i fix this?
What does the Animator Controller look like?
lemme grab that real quick
public class CutsceneScript : MonoBehaviour
{
[Tooltip("Animator component that controls the cutscene animation.")]
public Animator cutsceneAnimator;
[Tooltip("Name of the animation trigger in the Animator.")]
public string animationTriggerName = "PlayCutscene";
[Tooltip("Duration of the cutscene in seconds.")]
public float cutsceneDuration = 5f;
private bool hasPlayed = false;
private void OnTriggerEnter(Collider other)
{
if (!hasPlayed && other.CompareTag("Player"))
{
if (cutsceneAnimator != null)
{
cutsceneAnimator.SetTrigger(animationTriggerName);
hasPlayed = true;
// Disable player movement
FirstPersonController movementScript = other.GetComponent<FirstPersonController>();
if (movementScript != null)
movementScript.enabled = false;
// Re-enable movement after cutscene
StartCoroutine(ReEnableMovement(other.gameObject, cutsceneDuration));
}
else
{
Debug.LogWarning("CutsceneScript: No Animator assigned!");
}
}
}
private System.Collections.IEnumerator ReEnableMovement(GameObject player, float delay)
{
yield return new WaitForSeconds(delay);
FirstPersonController = player.GetComponent<FirstPersonController>();
if (movementScript != null)
movementScript.enabled = true;
}
}
Okay, and what about the Animator Controller
Also,
Why
Why MonoBehaviour
that's going to match any component except Transform and Rigidbody
that is because i forgot to swap the word monobehavior after i took this code from my class
i have edited the message and the code itself
anyway here's the animator
it just pauses for a second and then rotates
That's the animation. What does the animator look like
well, it wouldn't match a lot of stuff, really
i dont know what that is then
Yeah there's other non-mono Behaviours but this was mostly hyperbole
The Animator Controller
Where you set up your animation states and transition conditions
well i get a feeling that im starting to see the problem then
for i do not have one of those ;-;
I can literally see your animator component in the screenshot
and it has a controller provided
how do i check it
Open it
So, upon entry, it will transition into New Animation
and nothing ever tells it to leave that state
yeah i need to add a thing there
well i dont need it to, i just need a trigger for it thats not starting the game
dang thats a LONG cutscene
oh yeah its like 3 seconds but i didnt wanna loop it so mu duct tape and super glue answer was MAKE IT LOOOONG
anyway, i have no idea how to operate this location
i want to add the cutscene script to it so it knows when to swap animations but i can only add a completely new script?
why not just.. set it to not loop though?
on the animation clip
set the animation clip to not loop
click the animation clip asset
look at the inspector tab
find the option labelled "loop time"
deselect it
thank yous :3
you may be interested in timeline for making cutscenes: https://docs.unity3d.com/Packages/com.unity.timeline@1.8/manual/index.html
i just need to understand what this is
or
i know what it is, i need to know how to use it
Its useful to animate things and play custom animations on animators (e.g. animate a character from some point to another and make them play a walk anim)
can also control other stuff or make custom clips+tracks
well yeah i know what but i need to add my script as a trigger for the animation and i just cant seem to do that
it says i need a new script
sorry im pretty new with API requests lol
where did i go wrong here?
WWWForm form = new();
form.AddField("karma", karma);
UnityWebRequest webRequest = UnityWebRequest.Post($"https://g-{Settings.server.gameId}.modapi.io/v1/games/{Settings.server.gameId}/mods/{ModID}/comments/{CommentID}/karma", form);
webRequest.SetRequestHeader("Authorization", $"Bearer {UserData.instance.oAuthToken}");
webRequest.SetRequestHeader("Accept", "application/json");
await webRequest.SendWebRequest();
yes its in a async, and i followed the same way as i did .Get, but just added a WWWForm
this is the doc for the API
https://docs.mod.io/restapiref/?shell#add-mod-comment-karma
Documentation for working with the mod.io REST API to download and install mods automatically in games.
should probably describe what is responding with
could be your token
yeah seems like you are not authenticated
its not cause i can do .Get
UnityWebRequest webRequest = UnityWebRequest.Get($"https://g-{Settings.server.gameId}.modapi.io/v1/me");
webRequest.SetRequestHeader("Authorization", $"Bearer {UserData.instance.oAuthToken}");
webRequest.SetRequestHeader("Accept", "application/json");
await webRequest.SendWebRequest();
This one works
Doesn't matter. It can have different permissions for get vs post
so what should i do?
even the website says you can do a Get without token
also on their site 403 Forbidden -- You do not have permission to perform the requested action.
the /me endpoint only requires authentication and the read scope, the endpoint you are getting the 403 on requires write scope
403 means you have a valid token you just don't have permission to do that
oh sorry yes its 403
You need to grant permission for that user to do that thing
Or get a token for a user that does have permission
Very little context here so it's hard to say more
gotta request a token with read+write scope
https://docs.mod.io/restapiref/?shell#authentication
hmm thats interesting, pretty sure the OAuth token gets set up already when logged in, so that prob isnt the issue
how did you authenticate
dont see anywhere where you can set up the write scope though
welp, guess you gotta find their support then since this isn't a unity issue at this point π€·ββοΈ
yeah i just thought it might be just me not doing the post right or just mispelling something
im gonna ask, thanks
could i get some info on this? i dont seem to have the option to do anything
which info ? you're in a code channel
i want to make it so there's a trigger for new animation
if anyone is wondering, it happened because i was trying to like/dislike my OWN comment π
so when the player touches a hitbox the animation plays
by making another account, commenting, i can like/dislike it, just not my own comments
suggest you follow the basics of animator, learn about parameters
thank yous :3
wait i read through it all
i still dont get it, i cant do anything with the parameters once i make them
i want to put a trigger parameter on the board between enter and new animation
you can't. Enter transitions immediately without conditions to the default state that is set. which you've set to New Animation
create an empty state for the default state and transition from that to New Animation (which really needs a better name)
also this is not a code issue. #πβanimation
ok I'm trying to disable movement if it's outside some bounds like this
Vector3 move = transform.position + moveDir * (speed * Time.fixedDeltaTime);
if (!bounds.Contains(move)) return;```
it seems to be falling through no matter what, I have some gizmos drawing what the bounds should be but the player appears to be able to exit them somehow so I think I'm using the Bounds class wrong
the code for applying movement is below that snippet
Hey yall, so I have this list of sprites meant for the UI, however they're currently stored in Resources, which I know is a big no-no, however what is the alternative and how would I implement it for something as simple as the following?:
Sprite newSprite = Resources.Load<Sprite>($"Graphics/UI/{lvl}");
if (newSprite != null)
currentRoom.transform.Find("WallNumber").GetComponent<SpriteRenderer>().sprite = newSprite;
else
Debug.Log("No image found");
What is lvl? Is it a name, a number, or some other kind of identifier?
it's an int variable from the same script
and every UI element is named after a number, so just "0", "1", etc.
Perfect, then you can make an array of Sprites and do .sprite = levelSprites[lvl]
Switching to this channel as it seems to be more of a code issue at this point
I have managed to get it so it's only affecting the emission of the object I want it to (not all lights in the scene of the same type)
But as you can see it is NOT flashing the emission at the correct time and seemingly random?
What do you mean the correct time, and seemingly random? Your code literally does it at random between two times
Yes but the emission change isnt in time with the light going off
If you watch the video the emission should be 'white' when the light is on
and black when it's off
Do you have many of these lights?
Yeah
but they are unaffected as it's object based
emissiveMaterial = objectToChange.GetComponent<Renderer>().material; objectToChange = null;
Your code just sets it to white when the timer ticks over
And sets it to black at all other times
You need to toggle it in the lower if based on the light's state
Yeah basically when light = off emission off so it looks normal
okay so by my logic, this new addition in update, if timer doesn't = 0 make it white
It doesnt show white at all just black the whole time
You haven't done what I said at all
Put the emission toggling code in the same if as the light code, and do it based on the state the light is in
that first if is pointless as it will go below 0 and then be given a new value above 0...
That's not in your if statement, it will be unnecessarily called every frame
A more streamlined version of your logic:
void Update()
{
timer -= Time.deltaTime;
if(timer <= 0f)
{
bool newState = !lightOB.enabled;
lightOB.enabled = newState;
emissiveMaterial.SetColor("_EmissionColor", newState ? Color.white : Color.black);
timer = Random.Range(minTime, maxTime);
}
}
Notice how we only change the emission color when we change the light state
#π»βcode-beginner message still got this problem, not entirely sure why
What is bounds the bounds of, and what does the rest of this function look like
[SerializeField] private Bounds bounds;
Just a serialized field in my player
private void FixedUpdate() {
waves.Value.positionList.Add(new(transform.position.x, transform.position.z));
fire.rotation = Quaternion.identity;
fire.localPosition = Vector3.zero;
if (movement.magnitude <= 0.1f) return;
Vector3 moveDir = movement.x * cam.right + movement.y * cam.forward;
Vector3 move = transform.position + moveDir * (speed * Time.fixedDeltaTime);
if (!bounds.Contains(move)) return;
fire.position = transform.position + moveDir;
transform.position = move;
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(moveDir), .25f);
transform.eulerAngles = new(0, transform.eulerAngles.y, 0);
}
this being the full function
So what is bounds set to?
Okay, so, after the return, try logging move and bounds.Contains(move)
See what those values match what you are expecting to happen
private void OnDrawGizmosSelected() {
Gizmos.DrawWireCube(bounds.center, bounds.extents);
}```
this is what I use to see my bounds
hey very new to this discord and I have no idea where to ask this question so sorry if im in the wrong place, anyone know how to deal with the CommandBuffer texture type 3 not found warning ?
first is expected, second should be false since it's below the bounds
the bounds end at 0 on -y
Why should it? 10 - 20 is -10. -7.50 is between 10 and -10
the center is set to y+10
The center is set to 10
meaning it should be checking for 0 to 20
whuh
https://docs.unity3d.com/ScriptReference/Bounds-extents.html
The extents of the Bounding Box. This is always half of the size of the Bounds.
so my gizmo code is gaslighting me lmao
https://docs.unity3d.com/ScriptReference/Gizmos.DrawWireCube.html
DrawWireCube takes a size, not an extents
Extents are the distance from the center point in each axis
oh weird ok
ight I timed the extent by 2 in the gizmo code that should be accurate now
ok now it stops correctly
ty
This is a quick issue: I have an object as a cursor for a simple game i'm making, and I want the block to go back to it's initial state, but instead makes a loop
Here's a string:
IEnumerator MoveCursor()
{
Vector3 startPosition = transform.position;
Vector3 targetPosition = new Vector3(startPosition.x, startPosition.y, -1.0f); // Cambiado a Z: -1.0
// Move to Z: -1.0
while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
yield return null;
}
// Move back to initial position
targetPosition = startPosition;
while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
yield return null;
}
}
}
Wdym by "makes a loop"?
When I click on the cursor, which serves as a bat, the Z movement I've programmed (with the help of AI, I admit and apologize in advance) does the movement, but goes from point A to point B nonstop.
So, it does not go from point B to point A?
Also, in both while loops, during the MoveTowards method, you use transform.position instead of startPosition . . .
nvm, the problem gets worse
good lesson on not letting "AI" let write code for you
when you don't understand how any of it works, and if it breaks ur stuck where you are
you mean, I have to swap every instance of "startPosition" with "transform.position"
(done)
yeah, not the ideal tool for beginners.
and nop, the problem persists.
When it goes from point A to Point B, the "bat" stays in the point B and now it can't follow my mouse
Add debug statements to all of your loops, should help u solve it
another proof why AI can't never be your ideal tool is because I specified them like 6 times to fix an action and it makes it worse
the action was that: after going to point B, the "bat" immediately goes back to point A and I can click on it all the times I want without looping. What the AI did was the same, but with the cost of the movementg never happening again after the second click
sorry for the late response, I was having dinner
I wouldn't be so categorical as to say "never".
AI output depends a lot on your ability to explain the problem and the desired outcome as well as providing the correct context.
Ironically, the better you are as a developer, the easier you can implement something, the easier it is to get a desirable output from an LLM.
But when the ai can finally sit at your chair and see the whole context of your project it would definitely be able to solve your problem and even more.
Remember that AI is more or less a storytelling engine. It's goal is to give you a good answer to your question, this can mean providing a objectively correct answer and sometimes this can mean providing an answer that may look correct but is completely wrong
AI does not know how to code, AI knows how to brute forcefully feed off other peoples work and discussions in an attempt to find enough relevant data to compose an answer that might answer your question
In my asteroid clone I'm using the following code to create and fire the ship's laser, and it works.
public GameObject bulletPrefab;
public Transform bulletOffset;
if (Input.GetKey(KeyCode.Space) && !bulletOnCooldown)
{
StartCoroutine(BulletCooldown());
Instantiate(bulletPrefab, bulletOffset);
}
But I'm using very similar logic to try and create smaller asteroids when a large asteroid is destroyed in the following code-
public GameObject medAsteroidPrefab;
public Transform medOffsetOne;
public Transform medOffsetTwo;
private void OnCollisionEnter2D(Collision2D col)
{
if (col.collider.CompareTag("laser"))
{
if (gameObject.CompareTag("bigAsteroid"))
{
Instantiate(medAsteroidPrefab, medOffsetOne);
Instantiate(medAsteroidPrefab, medOffsetTwo);
}
Destroy(gameObject);
}
}
but the smaller asteroids aren't being instantiated. I put debug.log's before each should be instantiated to make sure that if statement is actually being executed, and it is. It feels like I'm overlooking something simple?
show the code w/ the debug logs and show the inspector of whatever that second script is
!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/, https://scriptbin.xyz/
π 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.
https://paste.mod.gg/okslfisiggbl/0 there's the whole script on my asteroid prefabs
A tool for sharing your source code with the world!
This is not really correct. I think it's better not to misinform people.
But anyways, this is not the correct place to discuss how LLMs work.
the transforms for the offsets are pulled from children of the prefab
The only difference between the ship and the asteroids as far as I can tell is that the ship isn't a prefab, but I don't think that matters
Can someone check #π οΈβprobuilder ?
If it is being executed, then it is instantiated. It's likely being destroyed immediately, or maybe instantiated in the wrong place. You can confirm the former by adding a script with OnEnable and OnDisable in the prefab and printing something meaningful inside.
To check the latter, pause your game after they are supposed to be spawned and inspect the hierarchy(can use the search bar too).
If that's the case it must be that they're destroyed instantly, because they aren't ever in the hierarchy or visible. I wonder if it's possible that they're inheriting the collision and immediately destroying as if hit with a laser?
Perhaps. You should confirm it the way I suggested
It would also make it clear if they are instantiated in the first place.
yeah, they're being instantiated
gonna try to check if they're in a collision when they're created with OnCollisionStay2D
You can look at the on disable/destroy log callstack to see where they are destroyed from
Nope. I tried
print("Asteroid position:" + transform.position);
and it's giving correct positions too.
Can you elaborate on this actually? Or point me towards where I can read about this concept? I tried to figure out what you meant by this and I'm lost lol
What part of it?
Is a callstack just what's printed in the console?
Yes. Take a screenshot of your log message in the console
See that info below? That's very important. More important than the list of messages above.
It contains the path to the code line and the callstack that led to that line being called.
Now, I don't see any destroy messages. Did you print anything in on disable/destroy?
I didn't then, I was too busy trying to figure out what a callstack is lmao
but I did now, and nothing was printed after they were instantiated
but when I shot an asteroid that was spawned via the asteroid spawner which isn't bugged, it did print the message
so I don't think they're being destroyed?
Add a second parameter this to your logs. Debug.Log("small asteroid instantiated", this);. Then try clicking the message when it appears. This should select the object in the hierarchy.
Make sure to "uncollapse" you messages in the console.
I must have missed something, they're definitely being destroyed. All of these messages come from shooting one "big" asteroid.
Ok, so they are destroyed. Try logging in OnDisable too. There might be a callstack showing where it is being destroyed from
It doesn't say anything different unfortunately
I feel like when the big asteroid that instantiates the two medium ones executes the Destroy(gameObject) from its OnCollisionEnter2D it's also destroying the prefabs it instantiated
The medium asteroids it instantiates shouldn't be children of it though. But they get their transforms from empty objects that are children of it.
If it's a child of a child it still gets destroyed.
Don't spawn the medium asteroids as children of this object
oof. I didn't think referencing the transform of another object would make it parented to that but I tested with this-
if (transform.parent = null)
{
Debug.Log("No parents");
}
else
{
Debug.Log("parents");
}
and they for sure have parents. I guess I have to think of a different way to do that π
@teal viper thanks for going through that with me. I learned a lot about debugging!
Check the instantiate method documentation. It tells you exactly when and why it parents objects.
The fact that you pass it a parent object to your Instantiate method should have shown you that it had a parent
Yes I explicitly set one, of course it's going to have one
For some reason I thought that medOffset variables were vectors...π
lol! My thought process was that I was giving it the position of the medOffset objects transform. Like, this is your transform.position now. Not transform.parent. I know better now.
hello, this is a noob question and not really unity specific but I've only made simple learning projects so far, and haven't had too many objects on the screen. If I have say hundreds of object A on the screen, moving, and an object B always seeking the nearest object A, how should I go about this?
I want to say that I should make object A a prefab, and during instantiation, add them to some data structure to store them in, some kind of entity manager class? I want to use something basic, like a list, but looping through the entire map to find the closest thing seems bad. I want to separate my game into grid chunks, and maybe store a list of enemies in each chunk during each update frame, and simply search for the nearest enemy starting from object B's current cell, and expanding from there. Is this even worth doing if I'm only going to ever be searching through 100-200 things at a time? If I wanted to repeat this process for say, each object A, would that warrant doing some sort of spatial partition?
You should probably look into object pooling. I used one on about 500 objects, always looking for the closest, and it was fine
Just make sure to use a for loop for getting the closest instead of a Linq expression
With pooling implemented and a for loop, garbage collection would be at a minimum, and usually thats the thing that slows down the game the most
Okay thank you! I see the benefits of pooling now
So I kind of get the object pooling and implemented it for random Monster spawns (instead of instantiating it on the fly), but wouldn't it still be very costly to search the entire set of monsters in the world to maintain a collection of the n closest? Maybe I am understanding this line wrong
Depends on the amount of monsters but yes
For large amounts of monsters some sort of spatial partition structure should be used to get the n-closest
Can someone please help me stop my unity from crashing? it does it randomly in play mode for 1 project only...
If needed i can put my editor.log here
this prob isnt beginner sorry
Check the !logs
It's not code related either, but let's see what actually causes the crash first
do you want me to dm you the editor.log file? I dont want to put it here since its huge
You can use a paste site
!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/, https://scriptbin.xyz/
π 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.
There should also be a Crash!!! Section that is relevant
Ye ive found that
Then paste that
just a few lines above the "Crash!!!"
<RI> Initialized touch support.
Loaded scene 'Temp/__Backupscenes/0.backup'
Deserialize: 3.502 ms
Integration: 183.005 ms
Integration of assets: 0.002 ms
Thread Wait Time: 0.009 ms
Total Operation Time: 186.518 ms
TrimDiskCacheJob: Current cache size 0mb
Crash!!!
I've done alot if googleing
Hunch tells me you've got a loop somewhere that never exits and never yields
What is the stacktrace after the crash ?
========== OUTPUTTING STACK TRACE ==================
0x00007FFD59CF981D (nvwgf2umx) NVENCODEAPI_Thunk
0x00007FFD59F8803F (nvwgf2umx) SetDependencyInfo
0x00007FFD59F87F9F (nvwgf2umx) SetDependencyInfo
0x00007FFD59F7C87D (nvwgf2umx) SetDependencyInfo
0x00007FFD5A47034A (nvwgf2umx) NVDEV_Thunk
0x00007FFD5A90ECCA (nvwgf2umx) NVDEV_Thunk
0x00007FFD6D3CE8D7 (KERNEL32) BaseThreadInitThunk
0x00007FFD6F5314FC (ntdll) RtlUserThreadStart
========== END OF STACKTRACE ===========
Looks like the nvidia drivers are crashing. Try updating them
They are the latest version
Studio or game ready ?
No it doesn't π€ That trace tells you close to nothing.
And the fact that it happens in one specific project makes it unlikely to be some broader driver issue
@meager hinge Is it a large project? If you try to enter play mode in an empty scene, does it still crash? Can you disable half of the gameobjects in your hierarchy and see if one half or the other disabled stops the crash? (If we'd assume for a second that maybe the crash is caused by some script)
nvwgf2umx is definitely a nvidia dll
That I don't doubt
So why do you doubt my statement that the nvidia drivers are crashing when the crash happens from them ?
Because there's no sign that the drivers are "crashing". Some code in some dll is, I'm guessing, throwing an exceptionβ Likely due to the Editor becoming unresponsive (Because It crashed). It still tells us nothing of the cause of the crash
I'm not saying it can't possibly be some obscure nvidia driver issue. Just that that's not the first place I'd look.
No its not a large project and as far as ive seen no it dosent crash anywhere else
So an empty scene doesn't crash? That at least would rule out config issues in your project
I would probably just start disabling objects and scripts in the scene until you found the one causing the crash, and that would give you a place to start in terms of debugging.
oke
its a basic wip level editor scene so i think it has 2 different scripts rn
Oke ive it still crashed with the scripts disabled
i disabled the object with the script on it and then the canvas
seperatly
they crashed
π€ But if only this scene crashes, there must be some code executing there specifically causing it
Share more crash details
it dosent give me any, it just closes and opens the crash reporter window
Check the logs you shared earlier. It tells you about a crash report path in the bottom
Oh yeah i have that
text from crash.dmp
The thread tried to read from or write to a virtual address for which it does not have the appropriate access.
Share the file on a paste site
can i send it here? its a small enough file
Is it below like 10 lines?
You can yes
Press debug and have a look at the callstack.
And thread name
Though, I feel like it's not gonna show much info without debug symbols
Where is that?
Top right of your cut screenshot
You mean theese?
Yes
Hmmm... Does the crash happen in a new empty project? And when exactly does it happen in your project?
Never in a new project and it either happens when i stop the game or randomly during play mode
Possibly a bug with the current Nvidia drivers.
Do you have any custom rendering related features in the project? And what render pipeline are you using?
None yet its just the default 2d
Maybe try upgrading to URP and see if the issue persists.
actually i might take a break for awhile its getting late where i live
Hi,
I've been trying to perfect a kinematic Rigidbody-based movement system for an ant-style character that can crawl on any surface - walls, ceilings, trees, etc - while still responding to gravity when βreleased.β (fall of on commmand) Iβve tried averaging multiple downward raycasts for rotation to align both pitch and roll, but the model still sometimes flips into geometry or falls through. There is also a camera system where camera movement dictates yaw rotation (third person shooter like).
It's been forever and I can't seem to fix it
Any help would be greatly appreaciated!
The player movement script: https://pastebin.com/TuNdUTkY
The camera rotator script: https://pastebin.com/spgTaESs
A short video of the occurring problems: https://drive.google.com/file/d/1KoaRe_C3i-wWBSYOMuixJP1oIyIGfIZN/view?usp=sharing
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Google reports this lib is from windows nvidia drivers
Ideally we would have some unity code in the stack to better tell what went wrong
hi guysss, is htere a way to speed up unity? the compiling tooks too much time D:::: i saw some assembly definitions but idk how to use em hahahaha
I'm always struggeling with unityEvents. I don't know why this isn't working. I have 2 Scripts. One (theManager) holds the event and handels invoke. The other is a Prefab Object, that should one add himself as a listener. If i link the event to a funtion inside the Manager, it works. Only the funtion on the prefab don't get called ````
///Script One - Manager
//The Event
public UnityEvent<bool> QuestTypInNeedTEST;
//Test function to invoke event
[ContextMenu("TestEvent")]
public void TestEvent()
{
QuestTypInNeedTEST.Invoke(false);
}
//My test, if event works on manager ifself - yes it does
public void TESTFORTEST(bool da)
{
Debug.Log("INVOKE IN MANAGER ITSLEF WORKS");
}
//Link event
protected override void Awake()
{
base.Awake();
QuestTypInNeedTEST.AddListener(TESTFORTEST);
}
///Script Two Prefab
void Start()
{
QuestManager.Instance.QuestTypInNeedTEST.AddListener(TESTCHECK);
//prints out 0 - every time, even with 10 prefabs in the scene
Debug.Log(QuestManager.Instance.QuestTypInNeedTEST.GetPersistentEventCount());
}
//Dont't get called when event is invoked
public void TESTCHECK(bool needTEST)
{
Debug.Log(needTEST +" : "+ gameObject.name);
}
How are you debugging/investigating the issue?
Pretty sure persistent event count is only counting subscribers via the inspector, not via code.
As for why it's not getting called, is a good question. I'd try stepping through the code with a debugger.
Yep, subscribing via code isn't persistent
hi guys! is there away to speed up unity? the compiling is soooo slow D:::
When you compile, unity does a domain reload which can trigger a bunch of stuff. So it might not even be compilation taking that long
Profiling it can help find out the issue
Are you sure it's the compiler? I bet it's something else, like assembly reload.
Profiling + looking at the log files for a refresh/assembly reload report.
Yeah I also noticed that, seems like there isnβt a way to print unpersistent subscribers.
So my syntax seems right?
Yes.
Okay thank you. I will try my luck with a debugger then
The only thing I can assume is that the event you subscribe to is not the one that is being invoked.
Logging object names or IDs during subscription and event invocation could help confirm it. Or check it in the debugger.
anyone know a good way to get curved colliders for a ramp?? The polygon only gives me trouble and I tried downloading this custom collider pack but it doesnt work anymore its like 10 years old I think lol
Hello, do people typically use Enums for states? Or do you make actual state classes
This is a code channel
And you didnt specify 2d or 3d (i assume 2d?)
I personally use enums.
please don't ping specific people for help
dude I just tagged him back what does it change from pressing the "respond button"
public IEnumerator LinkEvents()
{
for (int i = 0; i < 5; i++)
{
yield return new WaitForEndOfFrame();
}
QuestManager.Instance.QuestTypInNeedTEST.AddListener(TESTCHECK);
}
``` Instead of linking the event in start, i start this coroutine now, and everything works. So it seems my maschine is just to slow
oh i misread the name lmao π
that doesn't exactly wait 5 frames. to wait a frame use yield return null;
I don't think that's the issue. It's likely a execution order issue, if it works with a coroutine.
So that would be current frame + 4 frames, right
Oh thats a fantasic, thank you!
Waiting for an arbitrary amount of frames seems shady though
it would wait 4 full frames and then wait until the 5th one has finished rendering instead, if im understanding it correctly
This is a channel for questions about code. Please delete your post from here and post into #πΌοΈβ2d-tools
ok sorry
Random Vector3 math question: Is the Vector3 ( 1, 0 , 0 ) already normalized since has a value of 1? Is Vector3 ( 1, 1 , 0 ) normalized?
(1, 0, 0) is normalized because the length of that vector is 1. (1, 1, 0) isn't normalized, because the length of that vector is not 1. If you plot the points on a graph, you'll see (1, 1, 0) is a longer line than (1, 0, 0).
so if normalized the second vector would be (0.5, 0.5, 0) right?
hmm acutally maybe not if I draw it on graph paper...
No look at the definition of the l2 norm
The length of a vector is calculated by taking the square root of the squares of each component combined. In code, that would look like this: Mathf.Sqrt(x*x + y*y + z*z)
So the length of (0.5, 0.5, 0) is Mathf.Sqrt(0.5*0.5 + 0.5*0.5 + 0*0) -> Mathf.Sqrt(0.25 + 0.25 + 0) -> Mathf.Sqrt(0.5) -> 0.707106
The length of (1, 1, 0) ends up being the square root of 2, which is 1.41421.
A normalized version of (1, 1, 0) can be calculated by dividing (1, 1, 0) with its length, 1.41421. That ends up being (0.707106, 0.707106, 0).
I get it now, thanks for the insight!
How expensive is Vector3.Normalize() to compute?
Normalizing a Vector3 is the same as calculating its length and then dividing by that length. Calculating its length is a square root, three multiplications and two additions. Compared to a multiply and addition operation, a square root and divide can be much slower. But this is all relative. A modern CPU blazes through all of this. It only starts to matter when you're talking about millions of these operations per frame.
Bit confused by trying to create a timer here, If somebody could help me understand the logic that would be awesome.
Basically, on on trigger enter, zombie pops up, timer starts at one second, and then when timer hits 0, zombie vanishes (jumpscare)
^ That's what I want to happen
nothing is subtracting time here
I was just about to say that yeah
you can do for example
if(timer > 0) {timer -= Time.deltaTime}
in my light flicker script I did something similar but the issue is this wont run on update
Or i dont want the timer to run as soon as the script starts
the timer -= Time.deltaTime isn't behind any condition ofcourse it will run right away
thats why you need a boolean condition , like exmaple I shown or you can create another bool
timer > 0
or
IsTimerReady == true
etc.
there are also coroutines you can use for these 1 off things
I think i'm getting somewhere?
Zombie seems to not appear though or vanishes in the blink of an eye i can't tell
You did a completely different thing here..
why did you change timer > 0 from if(timer <= 0)
Work through it in your head. One line at a time. You set the timer to 1, you enable the object, and set the bool to true.
Now, with those values in mind, walk through your update function. What happens, line by line?
(for the sake of math assume deltaTime is 0.1)
the whole idea was
if(isRunning)
timer -= TIme.deltaTime;
//only start timer when ready
if(timer <=0) // should go in the isRunning bool so it doesnt do something when starting with timer = 0 value
if timer has reached 0 //do the thing
Yep, good start. Then what?
void Update()
{
if (isrunning)
{
timer -= Time.deltaTime;
}
Then this to subtract from it
But like, you want to spawn something and make it dissapear soon after?
Why don't you just add a timer on the spawned item to destroy it?
Yep, that's good. Now, what conditions do you want to check for?
should be in the isRunning bool
because you start with 0
equals is tough. What if it's at 0.05 and you subtract 0.1? Then it'll skip right past 0
Ah equals or less than
And go into negatives
Bingo
hiding already hidden object is no big deal, but what if you added other logic to happen after ?. So its better you put hiding logic (time reaches 0 or under) also within timer running bool
Look at your previous if statement
that one's formatted correctly
I mean you already did all this before? you should know how to write lol
if (timer <= 0) {
}
I am just still wondering the "isrunning" part. What is running? do you really need that?
I dont know I think it's because i'm trying to follow 2 peoples approaches lol
well you dont want to be subtracting time when not needed / not ready to do so...
There are multiple ways to do this, but this is also a good way to demonstrate code flow so working with this solution is probably the most instructive

Sure, but in what case would you not want to be running the timer? Isn't this meant to just poop and vanish in a second?
^ Yeah
well going by the assumptions that we have no idea where this script is right now..
(it can be recycled to multiple objects/jumpscares for example)
It works also, But it's triggable multiple times, so i guess id need another bool like 'hashappened'
Its just a stationary jumpscare
well yeah each timer you enter trigger it will reset it
Attach the script to a collider that spawns the thing when entering on it, then spawn the zombie prefab with a timer on update that destroys it after a second. Destroy the spawner script in the same call that spawns the zombie
This is what I would do
how ? that if has happened is doing absolutely nothing but preventing timer to = 0.3
you could technically do if(hasHappened == true) return;
I mean, it will work, once
But once hasHappened is true, it'll activate the object without actually setting the timer
so it'll deactivate itself immediately
Yeah my bad
I find it so bizzare that an If will include the very next line but nothing else if not wrapped in curlys
I guess it's just something I gotta get used to
How do I decide when to put things in awake and start? If I have a state machine for enemy behavior, should I set the initial state in awake? in case I need it in start? Or should I put it in start and swap it to awake if I ever need it to be done first?
c# quirks
Awake = iniitlaizations
Start = Reference access
o ok ty
General rule of thumb: Reference yourself in Awake, reference other stuff in Start
ya makes sense, thanks!
How is that weird, you usually want A LOT of stuff to happen after the same if, would you declare the if on each of them separatedly? lol
So, a script getting a component from the object it's on? Awake. Getting a reference from a singleton? Start
also Awake runs always (unless gameobject is disabled) even script is disabled, Start does not run when is disabled until enabled again
Exactly, you dont really want one thing to happen, So why would 1 thing not require being enclosed
An if statement actually always only applies to the next line. It's just that if that line is a { then it treats that whole section as one "thing" until it hits }
Also, avoid getting components on awake if you can asign them manually, takes longer to go throught that "awaking" frame
yup especially if you have 10s or 100s of objects initializing
What? You mean one liners ifs? Those can still use the brackets, just that you can skip them
Also, also "hashappened" is already boolean, you don't need to compare it to a other boolean
You can just do "!hashappened"
Also, camelcase, but you can name it whatever the heck u want as long as you know what it is
control flow statements apply to a single substatement. in the case of block statements ({ }), that single block statement has multiple substatements of its own
also wanting only 1 thing to happen isn't all that uncommon tbh
could be something as simple as this
if (a) counta++;
if (b) countb++;
if (c) countc++;
```you wouldn't want `c` to also require `a` and `b`
I wanna make a railroad and make that train follow it with a throttle and brake
is there a question in this statement ?
Ok, continuing with my problem, the "bat" follows my mouse, but has the issue of "click to make a loop" with a combo of stop following my mouse when it loops.
here's the current string:
public class Test2 : MonoBehaviour
{
Vector3 pos;
public float offset = 3f;
public float moveSpeed = 5f; // Speed
Animator anim;
void Start()
{
anim = gameObject.GetComponent<Animator>();
}
void Update()
{
anim.enabled = false;
pos = Input.mousePosition;
pos.z = offset;
transform.position = Camera.main.ScreenToWorldPoint(pos);
if (Input.GetMouseButtonDown(0))
{
StartCoroutine(MoveCursor());
}
}
IEnumerator MoveCursor()
{
Vector3 startPosition = transform.position;
Vector3 targetPosition = new Vector3(startPosition.x, startPosition.y, -1.0f); // Cambiado a Z: -1.0
// Move to Z: -1.0
while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
{
transform.position = Vector3.MoveTowards(startPosition, targetPosition, moveSpeed * Time.deltaTime);
yield return null;
}
// Move back to initial position
targetPosition = startPosition;
while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
{
transform.position = Vector3.MoveTowards(startPosition, targetPosition, moveSpeed * Time.deltaTime);
yield return null;
}
}
}
I'm pretty sure this sequence of words doesn't make any sense but I would suggest combining your movement code so that your position changes in update and the coroutine won't overwrite each other
or I guess since update runs first, it's only the coroutine that will be doing overwriting. maybe that's fine but it seems fragile to me
if you also have an animator, it could be overwriting transform values as well
What I mean here is that I've made a 3D cursor that acts as the bat for a 3D piΓ±ata game I'm making. The problem is, when I click, the movement I've scripted (with the unfortune help with AI) repeats itself as a loop.
I've recently disabled Animator and no luck
This is wqrong:
transform.position = Vector3.MoveTowards(startPosition, targetPosition, moveSpeed * Time.deltaTime);
in both places where you used it.
it should be:
transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);```
it was because I was requested by an user to swap "transform.position" with "startPosition"
well it doesn't make sense there
now, I'll try to find the way for the cursor to come back to Point A
I mean this isn't really going to work at all
because you have transform.position = Camera.main.ScreenToWorldPoint(pos); in Update
so your transform.position = code in the coroutine is just going to compete with that
you would basically want to set a boolean variable to true while the coroutine is happening and make it so that normal Update movement doesn't happen while the coroutine is running
otherwise the two lines of code are just going to fight with each other @acoustic hawk
hm, so i was thinking about how to make a 3d rotating platform for a platformer game
the solutions ive seen involve reparenting to inherit transform, or applying velocity, but i dont think rotational velocity is feasible
but then i came across this
I vote for using this character controller which has moving platform support built in
any advice on how i could implement this? specifically in such a way that if you jumped while on said rotating platform, you'd keep the velocity you would have from jumping off of one
hmm, they didnt really showcase how it handles inheritance of rotational velocity
they launched off of a moving platform, but only horizontally
If I am about to modify the text of a bunch of texts on update, would you recommend me to store them on a list and call them by index or to make a variable for each of them and do it manually?
Not to stackoverflow you but why do you need to do this on Update? Forgive me if your already aware but itβs worth looking up how canvas dirtying works, where changes made to something within the canvas that frame causes the whole scope of the canvas to rebuild. Ideally you want UI stuff to change via event based logic in order to minimise these rebuilds
Even if the page doesnβt answer your question youβll probably get a lot out of checking out their implementation of things to get a general gist
I am aware, but I need to display the stats of stuff on real time
I could subscribe every single stat to a "onValueChanged", but that would kinda bloat it a lot and wouldn't really save much, cause basically that's going to be modified pretty frequently anyways
Fair, that would be ideal though.
Might be worth half implementing that approach and having your text stuff listen to an event but rather than do it on value change you just have some relevant manager/controller invoke it on update?
It would be fine updating it just once per second or something
It's fine if there is a small delay
But the question at hand, it's more efficient to have a list with like 10+ values and search on it or having a variable for all of those values?
is there anyway I can get help troubleshooting some animation / script issues? (im very new)
Donβt ask to ask, just ask π
LOL MY B
im not quite sure why but I made a attack / sword swing script and animations for it and they arent working
Hello, I'm having an issue with a spaceship movement-like code for a npc ship. The npc works with a state machine with a patrolling state. Right now the state machine detects a random waypoint and sets it as the travel direction of the object, however, after reaching the first point I can't get to "restart" (in some natural-looking way) the velocity of the ship, or make it turn around naturally to reach a new waypoint, because, after reaching the first waypoint, it seems that the velocity is too high so the npc just orbits around (usually in a big orbit) it's next waypoint.
This is the code:
public class NPCSpaceship_Controller : Spaceship_Controller
{
[SerializeField] Spaceship selectedShip;
public enum State
{
Travelling,
Chasing,
Attacking
}
[SerializeField] State currentState = State.Travelling;
[SerializeField] State previousState = State.Travelling;
[SerializeField] LayerMask targetMask;
[SerializeField] Transform targetTransform;
[SerializeField] float detectionRadius = 30f;
[SerializeField] float attackingRadius = 20f;
[SerializeField] float travellingRadius = 30f;
[SerializeField] Vector3 travelPoint;
[SerializeField] Vector3 travelDirection;
public override void Initialize(Spaceship spaceship)
{
base.Initialize(spaceship);
}
protected override void UpdateRotation()
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(travelDirection, transform.up), Time.deltaTime * 2f);
}
protected override void UpdateVelocity()
{
rb.AddForce(travelDirection * Ship.Stats.Acceleration * Time.deltaTime, ForceMode.Force);
}
private void GenerateNewWaypoint() //travelling
{
travelPoint = transform.position + Random.insideUnitSphere * travellingRadius;
}
private void UpdateTravelPoint() // chasing/attacking
{
travelPoint = targetTransform.position;
travelDirection = (travelPoint - transform.position).normalized;
}
private bool ReachedTravelPoint()
{
return Vector3.Distance(transform.position, travelPoint) < 2.5f;
}
}
I tried to summarize the methods working on what I think the problem is, since discord message limit doesn't allow me to paste everything
UpdateRotation and UpdateVelocity are being called on FixedUpdate and the TravelPoint methods on the Update and the methods of the state machine (Update)
Well you're adding the same linear acceleration from A to B, that will overshoot. If you want to use built in physics, then you need to plan for deceleration at some point.
I'm sure you can come up with a formula if you define a max deceleration rate. From there you can probably derive the distance at which deceleration begins and then apply counter force from there
more clearly, @zealous geode I think define deceleration = x, then compute the magnitude of the current velocity. Then (vMagnitude * vMagnitude) / (2f * deceleration) should return the distance at which deceleration should begin. Check if you're within that distance from your target, and if so, you can begin decelerating by adding the negated direction * deceleration * dt, instead of accelerating
this assumes your ship is going relatively straight
yo does any1 know where i can find a good sprinting script all the tuts ive found didnt help much
tutorials are there to help teach you concepts
they are not there to drop into your project as a working final production-ready solution
do the tutorial, learn how it works, then apply it to your game
Does it make sense to have a general number formating on a gameManager? Would u do that? Or it's weird?
What kind of number formating? What is it used for?
Like 100,000 = 100K and that kinda stuff
I'd put it in a static utility class
So... I make an static class? Do I need to place it on a object?
No. You can't put static classes on objects
You can't have instances of static classes
It's like unity's MathF or other similar API.
I don't think I have yet done anything that does not derive from MonoBehaviour
Well, then it's a good opportunity to start doing that.
So... like this?
Yes
Just wait till you get to extensions π
What does it even mean making the string static? Isn't it changing depending of what value you pass it?
static as in the logic inside the scope of the static does not require a living instance to function
if you don't need a living instance to use the code you don't need to reference a living instance to use it
The string is not static. The method is.
The return type is string
Seems kinda weird to grasp, I get the class being static, but the methods are always... static within the class for me?
public class HelperInstance
{
public string CombineTwoNumbers(int first, int second)
{
return (first.ToString() + second.ToString());
}
}
public class StaticHelperInstance
{
public static string CombineTwoNumbers(int first, int second)
{
return (first.ToString() + second.ToString());
}
}
public class UsingClass
{
public void Awake()
{
//Using the function implemented inside a instance context
HelperInstance instance = null;
Debug.Log(instance.CombineTwoNumbers(1, 2));
//Using the function implemented inside a static context
Debug.Log(StaticHelperInstance.CombineTwoNumbers(1, 2));
}
}
I dunno, I just understand it as I am not referencing the method within an object, but rather a class that has that method, but the method is not being touched, so it's static
But I am clearly wrong
Static means that there are no instances. The class itself is the only instance. Normal classes can have both static and non static methods, but static classes can only have static, because you can't create instances of them.
No you're correct. A reference to an object is a reference to an instance of a class.
sometimes this word is used in programming in other ways but another way to think about static is using the word global
A static class can only contain static members and cannot be instantiated
That's what static means for a class
What if I make a method static on a non-static class? Can I access that method without an instance?
Yep
thats what GameObject.Instansiate is π
It's Object.Instantiate
Whenever you use Vector3.SomeMethod(), it's a static method in a non static type.
There's no difference between a static method on a static class vs a non static class. Adding the static keyword to the class definition just prevents you from making non static members or instantiating the class
So I suppose I can only use static variables on a static method?
You can pass on anything you want as a parameter to a static method
But if it's not a parameter, then only statics can be accessed
I mean not as a parameter, but as like something external on the class, like a counter or something
Yes you can only access statics aside from the parameters
Worth noting of course in the context of gamedev that can usually include singletons that lead to instances
Yeah, an static feels kinda similar to a singleton
singletons use statics to operate yes
Like just one general class that hovers around
the reason why a singleton works and why only 1 can exist is because it relies on a static reference to the instance
and because it's static its just a singular reference that can only point to 1 thing
Singletons better than static classes for most cases as they can still be deloaded easily by changing scenes without having to make some deconstructor
Not to mention that methods and data is still tied to an instance, it's just that it's always a single one
So it's better to just ensure there is a single instance that you access instead of forcing everything so be one
This is a very normal feature in C#. Often your code might not rely on a specific instance and is just used generally. Your case despicts a method that is used as a utility, not relying on anything that might despict a state, or something. Everything you need is contained within the method, so therefore it's better to just make it static and not require the user to create an instance of a class to access it.
Interesting that you find static methods weird to grasp, though. If a class is static, that means everything inside must by default also be static. This is not the case the other way around, however.
TL;DR on the whole conversation, but considering singletons are mentioned I do want to stress that a singleton is completely pointless here and will lead to overcomplication for no reason. Still, singletons are also very common so I do suggest you also look into those. In this case it is very common you just keep your utility method static, maybe even as an extension if it's suited as a common solution under that type.
If I have a prefab, with a script attached to it that makes it move randomly every update frame, and I instantiate that prefab 5 times, why do they move in the same direction? I feel like I'm misunderstanding what prefabs are & what they are used for
random =/= true random
the randomness is based on something and if you make 5 of the same things it's all probably gonna land on the same value

Show your code?
UnityEngine.Random is shared so you wont get the same values unless you set the same seed
So i dont think thats the issue
it was the same seed oops I feel so dumb now I was just testing earlier with same seed and forgot to remove it
Hello! I'm making a 2D game and was wondering how can I use different sprites for left and right directions (it's a soldier with an arm band on one side)
Assign the desired sprite when changing directions.
Then use a blend trees in the animator.
You will need different clips for the two directions of each animation then
Hi, I'm having trouble with Raycast. I'm trying to change a Pacman tutorial project to connect nodes that make movement decisions of ghosts (I need the neighbor nodes to implement an A* pathfinding). But Raycast isn't colliding with another node. Perhaps nodes are generated with tilemap (they aren't in hierarchy if I don't start the game). I checked the prefab and runtime layers, and they are identical. Any ideas? I can show my code if you want.
You need to show the code and the objects you expect the raycast to hit
Also is this a 2d grid based project?
` private void CheckAndAddNeighbor(Vector2 direction)
{
float maxDistance = 50f;
RaycastHit2D obstacleHit = Physics2D.BoxCast(
transform.position, Vector2.one * 0.5f, 0f, direction, maxDistance, obstacleLayer
);
float distanceToCheck = obstacleHit.collider != null ? obstacleHit.distance : maxDistance;
RaycastHit2D nodeHit = Physics2D.BoxCast(
transform.position, Vector2.one * 0.5f, 0f, direction, distanceToCheck, nodeLayer
);
if (nodeHit.collider != null)
{
Debug.Log($"[Node] Hit node in direction {direction} at {nodeHit.point}");
}
else
{
Debug.Log($"[Node] No node hit in direction {direction}");
}
if (nodeHit.collider != null && nodeHit.collider.gameObject != gameObject)
{
Node neighborNode = nodeHit.collider.GetComponent<Node>();
if (neighborNode != null && !neighbors.Contains(neighborNode))
{
neighbors.Add(neighborNode);
}
}
}`
yes
then why use physics at all?
just check your grid to see if something is in the neighboring coordinate\
I didn't explain why I chose this technique, sorry. There are many nodes in the map, and setting neighbors one by one is harder than this approach
There is no need to set neighbors one by one
we know from the grid structure who our neighbors are
thjey are the nodes at coordinates:
(0, 1) + our coordinate,
(1, 0) + our coordinate,
(0, -1) + our coordinate,
(-1, 0) + our coordinate,
Yes, but the ghosts calculate pathfinding only if they arrive in a intersection. Oh, I understand now... lol
I just need to call A* when they arrive in a node
I was trying to avoid setting a map as a matrix, that's why I chose nodes (and because in the original project the ghosts use the nodes to determine how direction chosen)
I'm not really sure what you mean by nodes and matrices here
Hello, addressing an issue I had yesterday, I have been trying with a possible solution that an user gave me, but i'm still having waypoint overshooting issues. The force applied doesn't seem to be enough no matter what value of deceleration I set, and the "orbiting" effect around the next waypoint is still there.
protected override void UpdateVelocity()
{
float distanceToPoint = Vector3.Distance(travelPoint, transform.position);
float currentVelocity = rb.velocity.magnitude;
float stoppingDistance = (currentVelocity * currentVelocity) / (2f * Ship.Stats.Deceleration);
if (distanceToPoint <= stoppingDistance + 2f)
{
rb.AddForce(-travelDirection * Ship.Stats.Deceleration * Time.deltaTime, ForceMode.Force);
}
else
{
rb.AddForce(travelDirection * Ship.Stats.Acceleration * Time.deltaTime, ForceMode.Force);
}
Debug.Log($"Stopping Distance: {stoppingDistance + 2f}, CurVel: {currentVelocity}, Distance to point: {distanceToPoint}");
}
What i'm trying to accomplish is that the npc entity that uses this behaviour decelerates when reaching the detection limit stoppingDistance + 2f
It's a space based game so i'm using rb.drag = 0f and no gravity.
but a grid-based graph (which is what A* operates on) can be represented in memory in two ways:
- A 2D array1
- an Adjacency list (basically
Dictionary<Node, List<Node>>
Time.deltaTime should never be used with AddForce.
Also make sure this is happening in FixedUpdate not Update
Yes, this is happening in FixedUpdate.
This is the original project, maybe it can be useful
https://github.com/zigurous/unity-pacman-tutorial
Yes, in this case, I would use a list, but the nodes are generated when I start the game, so I made the raycasts to detect their neighbors
Oh, well. It was a really dumb issue. It was in fact the dtime.
Thank you so much.
Any reason why the website doesn't work? I am clicking on "Get Started" but the page doesn't load
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
Can please someone else also give it a try?
and let me know if this is happening only to me
yeah seems to be giving 204s
unity learn's been having some problems lately, apparently
this might be one of said issues
Thanks for the help Chris!
the nodes are generated when I start the game
I don't see how that changes anything. You should still use a grid representation and not physics.
Any reason why I cannot see this 3d plane object?
Are you looking at it from the right side? Are you close enough to it that it's more than a blip on the screen?
Double-press F while hovering over the game view to focus on it
what material do you have set on it?
I pressed f
π
I think I am close enough :d
how do I understand that
Try looking at it from the other side
Try looking at it from the bottom
though given it's rotation this should be correct IIRC
Checked other side
still the same
I am just trying to learn something π
Why is Unity giving me headeache everytime
Actually I think your problem is this menu
I notice it's blue for you
which means you may have hidden some layers
make sure the eyeball next to the Default layer is not crossed through for you
different menu
this one
two sheets of paper w/ a star in the corner
Lol he probably just got banned
two layer cake being assaulted with a ninja star
no clue what that was about π
that was just plane silly..
guys, I have a question, in terms of which is easier to program, what is the better option? a 2D game or a 3D game? i did some research on this, and I saw that a lot of people said 2d games are more difficult, and i wanted to know why
The difference between 2D and 3D is a checkbox on your camera and a bit of different math
There's not a lot different when it comes to code
neither is easier or harder than the other
they're just different
alr thanks everyone
πββοΈ im in the group that believes 2D is harder than 3D, but has nothing to do with code, and more to do with art
i hear mostly the other way round tho
i can't comprehend 3d modelling π
2D is easier, but significantly less scaleable. 3D is more work up front but pays dividends for future assets
i suggest paper-craft π
fr tho, taking 3 2D images.. and making a 3D image basically just that lol thought this was unity-talk
β€οΈ
Ok guys I really need help this is PISSING ME OFF SO MUCH.
Ok first question that is pissing me off : Do you use VSCode or VSCommunity ?
Second question : if you use VSCode, do you use extensions like Unity or things like that ?
if you use VSCommunity do I have to select Unity alone or Unity AND .NET ?
Third question : I use VSCode but when I follow EXACTLY the tutoriel it does this : (see images)
When I install unity extension on VSCode I have some errors and there are problems and it doesn't work.
Now I uninstalled the extensions but I have a new problem with the compiller (I don't know what that is) (see image).
- VS Community is 2 separate words, the ide is VS and the free license for VS is the community license; this is incontrast to VS Code/VSC, which is the full name of the ide
- unless the ide has stuff built-in, you'll generally always want extensions for the specific thing you're using. built-in stuff tends to be language support
you have not exactly followed the tutorial
configure your !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
I use VS (non-code) but am using an older version of Unity (< 6).
You've got an error in your code. You'll need to properly configure your IDE.
The solution though if you're interested ||gameObject.name = "String needs double quotation characters";||
I use JetBrains Rider, which generally has no configuration problems.
VSC configuration if you're having trouble with the official steps: https://unity.huh.how/ide-configuration/visual-studio-code
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
When I install unity extension on VSCode I have some errors and there are problems and it doesn't work.
those are issues with your code. you have to fix the issues.
Now I uninstalled the extensions but I have a new problem with the compiller
so you've now removed the notifications from your ide, so the compiler is telling you that you still have issues
You have errors the tutorial doesn't
that's not the only issue
You can't fix errors by removing the thing that tells you where they are
the errors are still there
Damn I wish
yes, I watched some tutorials but when I do the excat same thing I always have a problem
Increment the counter
So then why not show your code when you are doing the exact thing instead of one where you aren't
just close your eyes, no more errors
Ok but what are the erros when I just install something, do the same things the others do but I have an error ?
- VSCode, yes
- Lots of extensions, yes
- as for tutorial see: #π»βcode-beginner message
Yours isn't the exact same as theirs
you are not doing the same things
your code has issues
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 184
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2025-05-09
the extension just tells you where the issues are
so by removing the extension, you just blind yourself to what the issues are
I just changed the name but it isn't changing anything, I can put the same thing that appears in the tutorial or not it doesn't change anything
That "thing" you installed that "causes" the errors are actually just telling you about the errors you already have. Uninstalling it just made it so now nothing is telling you that you have them
Reinstall the addon, fix the code
that's not the only difference
@hollow crater buddy please stop being stubborn.
reinstall the extension. you should see errors.
hover over the red line and see what it says.
Rooh I ll do it and take another screen
The server isn't meant to fix syntax errors. You need to configure your ide
uh, ok, we don't need to see those
make sure to fully configure your ide according to the instructions linked above
!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
If you did get errors before, you had it configured
then for some reason uninstalled the addon instead of fixing your errors
yes... [vertx](#π»βcode-beginner message) guide is pretty solid, as well
Ok thanks for your answers everyone, I will uninstall it AGAIN and reinstall it with the guide maybe it'll change soomething (I don't think so)
why would you uninstall it again
installing it is like the first step of the guide
what it'll change is that you'll be able to see the issues you have
it won't magically fix the issues. that's your job
but to fix issues, you have to first know what and where they are
that's what the extensions do
I know but I'll begin from zero to be sure I didn't miss anything or whatever
I need help. I am trying to get my model from mixamo to move when I press wasd but itβs not working. I need help, Iβve been working on this for like a whole afternoon and it still only keeps them in motion
Hoxo #π»βcode-beginner message
Keep doing the IDE config stuff, but just wanted to point out the original issue is visible in this message..
Like one of those "One of these is not like the other" minigames..
It's super blurry
but you need to have your console window open when you're using Unity
so you can see errors like this
This one is telling you that you're trying to use the old input system in your code but your project is configured to use the new system only
Do not ignore errors in your console.\
Yeah Iβve been using tutorials online for this.
Wait I just saw the ; was missing. Is that what you'all were trying to say ?
that's the problem with your code but the reason it took you this long to find it is because your code editor is not set up
ok thanks
config ur ide and ur ide will tell u
go into the preferences -> player -> and change ur active input handling setting
if ur gonna be following alot of tutorials (most will probably be using the older system)
i like to set mine to Both but all up to u
good to start inching ur way into the new system tho πͺ
Thanks bro that helped! I got it working.
This is a code channel. I donβt see a code question here. Delete and ask in #π»βunity-talk
okie
Hi, I wanna do vector multiplications in unity, but I noticed im limited to 4 dimensions, is there a solution to this?
make your own vector structs?
thats a pain to do no?
Also im worried about efficiency over for example dot products
efficiency wouldn't be any different
Do you mean with a struct an array btw?
not particularly? i mean you don't have to make the whole vector api for a higher dimension if you don't need all that
depends, do you need it to be variable size or something?
yes
bigger then 4
How would it work to make a event for an instance of an object? ie: notify a character that he, and only him has apply an OnHit effect
I only need dot products of 2 vectors (im implementing a feedforward later of an neural network)
then sure...? i mean if it's all the same type regardless of dimensionality you wouldn't have any static guarantees about multiplying the same dimension vectors
i feel like this is overkill though
may as well just pass around your vectors as arrays and then have static methods to operator on those arrays, would be way simpler
uh, then only trigger OnHit for that specific instance? not sure what exactly you're asking, perhaps provide more context about the system you already have?
Like, how do I subscribe a listener to an specific instance of a script?
by.. doing that?
But HOW do I declare that? This way is pretty much subscribing to all instances???
I am not sure I fully understand how this works
Is there maybe a way of how i can use an existing packacke for doing the neural network logic?
And if so, how do i make it working for my unity
ok so first off you have terminology backwards; here you get the effect of all instances subscribing to the event
but this action doesn't make all instances subscribe to the event at the same time
this just makes each individual instance subscribe to the event
so if you want only 1 instance to subscribe, then.. just have that single instance subscribe, just gotta have a way to know which single instance you're targetting
- Get a reference to that specific instance.
- Subscribe to the event on that instance.
The event needs to not be static.
The way you wrote EntitySelectSystem.OnEntitySelect implies that the OnEntitySelect event is static
It's static, that's what I was asking. I didn't know you could make non-static events
I want the BasicAttackManager of each entity to notify the rest of scripts on the entity that it has triggered an OnHit event, but just for that entity, not the rest
Nonstatic is the default.
if you want something associated with a specific instance, it should not be static.
not sure what you mean by "document", but yes, you can use any delegate type you want for your event
I mean like this but actually showing on the ide
like summaries ?
///
I think you would document the parameters on the delegate type.
Yep just tried it. The correct way is on the delegate type:
This requires you use a custom delegate type instead of Action<...>
(which is something I prefer anyway)
I barely understand actions to begin with, so I don't wanna add another layer lol
Actions are just a shortcut to making delegate types
Action<GeneralBehaviourManager, int>``` is identical to defining a delegate type:
```cs
public delegate void BehaviourChangedHandler(GeneralBehaviourManager manager, int amount);```
and then using `BehaviourChangedHandler` wherever you would have put `Action<GeneralBehaviourManager, int>`
public delegate void BehaviourChangedHandler(GeneralBehaviourManager manager, int amount);```
is just:
**public **-> is the access modifier, (it's public so everyone can use it)
**delegate **-> the delegate keyword signifies we are defining a delegate type
**void **-> this is the return type (we don't return anything, just like Action does)
**BehaviourChangedHandler **-> this is the name of our delegate type. You can name it whatever you want
**(GeneralBehaviourManager manager, int amount)** -> this is the list of parameter types and names for the delegate type, just like a regular function
In fact since this way lets us name the parameters, that's the only way it would make sense for us to be able to document them.
Anyway using Action and Func are just shortcuts to defining your own custom delegate types, but they're not as expressive and you can't exactly document them well.
Mmmm, I think I get it, but I would rather stick to actions cause makes it easier for me to read it later
I disagree on that point, but to each their own
public event CommandQueueChangedHandler OnQueueChanged;``` is much more clear and descriptive to me than:
```cs
public event Action<CommandQueue, int, CommandType> OnQueueChanged;```
Ye, I just ignore the event thing and read, oh, this is an action, sure
hi, small error. i wanted my character to rotate the direction he's facing. he does it when moving but when stationary, he does this (photo 1)
the code:
Quaternion targetRot = Quaternion.LookRotation(moveDir);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRot, Time.deltaTime * rotSpeed);
the setup: (photos 2, 3, and 4)
Model was imported from blender if that helps
this code is incomplete, where is showing how moveDir is calculated? its probably that passing wrong direction
if (charController.isGrounded)
{
moveDir = new Vector3(Input.GetAxis("Horizontal"),0, Input.GetAxis("Vertical")) * speed;
}
show inspector of body before you hit play, but you probably only want to pass the direction if its moving ?
thats the model's body
before play
it messes up more if i change it from that to 0
the resting rotation here is -90 on x? that don't look correct as default
yeah, if i put it to 0, it will just mess it up even more somehow
if you put 0 does it look the same as when you release the keys in-game ?
but do you see why its doing this in code?
no inputs = moveDir to 0,0,0
your 0,0,0 is not correct in the first place
the code is doing exactly what it should be doing, the wrong to fix is the model
either fix it in blender, or nest it inside another parent called "Graphics" where its 0,0,0 but child is -90 on x and rotate the "Graphics" object
wdym ? first put the CharRig at 0,0,0
ok.. so show the hierarchy now
yeah so now should be okay rotate the parent actually, CharRig ?
in code
does the fact i used mixamo for rigging have anything to do w this? in blender the character is upright
idk works fine when I use mixamo
ahh the character's visuals were on the mixamo thingy and not "cube"
blender usually has different axis system than unity tho
so does that mean that it's rotated in unity and not blender then?
so i should rotate it in blender and re-do everything?
would that be a quick fix?
if you want you could , I mean usually the parenting thing does quick fix anyway
alr well i'll try that then. thanks for your help!
oh ok.did parenting not work ?
parenting didn't, no. i think i might just be doing something wrong as it's 11:30pm
i'll probably fix it in the morning. thanks!
Does making a class abstract imply anything else other than allowing for abstract methods?
It just states it as some kind of interface does it?
You cannot create an instance of an abstract class. It exists to define things a child class must implement
So they are, like that, interfaces, right?
Abstract classes can contain code and private members, interfaces cannot
So they are just worse lol
A class can implement MANY interfaces, but a class can only inherit from 1 class so they are not the same
abstract classes are so you can define some protected/public functions for something to inherit but prevent use of the base as its incomplete.
public abstract void DoThing() This MUST be overwritten by sub classes
public virtual void DoThing(){} This can be optionally overwritten
how to center a object in center of grid cell? I changed Unity 5 to Unity 6, now my object is centering on corner of cells when I press ctrl
I presume you do not actually mean unity 5 because thats like 10+ years old
yeah, its just another old version, like 2021.3...
anyone know how to solve these errors? Im new to unity
hey i was wondering how i go about importing mixamo animations and characters into my project and making them work with my fps controller
What project is it? You seem to be using some kind of modding framework? Are you modding a game?
oh wait wtf some of my stuff is in that screenshot π
@violet timber gotta ask in lc modding discord if your doing that kinda stuff
Yes I am modding REPO
suprised that script is even included in a repo context π€
but yeah gotta go to repo server
We don't really provide modding support here. You'll need to ask in the game modding community. The only thing I can guess is that you're missing some dependencies required for modding, maybe il2cpp build module. Make sure you follow some modding guide properly.
btw dlich if nomnom's unity patcher is in the error its 100% modding related
Yes, that's why I asked it. The issue itself seems a bit more low level though.
ye, only reason i mention it is ive seen some studios use harmony for non modding reasons π
think they might have installed the wrong thing tbh, repo server will know
alr thanks guys. π
public void Interactdoor()
{
if (!isOpen)
{
drawer.transform.DOLocalMoveZ(openvalue, 1f, false);
(isOpen) = true;
drawaudiocontroller.clip = drawopen;
drawaudiocontroller.Play();
}
else if (isOpen)
{
drawer.transform.DOLocalMoveZ(closedvalue, 1f, false);
(isOpen) = false;
drawaudiocontroller.clip = drawclose;
drawaudiocontroller.Play();
}
}
Hey folks! Trying to figure out why the first time I interact with the door nothing seems to happen, but the second time its fine
Actually, It does play the sound on the first click but doesn't move
Seems I had the bools backwards
Wrapping (isOpen) in brackets is unnecessary, by the way.
Oh really? Thanks for that
hello, I am getting this error when trying to make a game in unity and I don't know what it means, this is it: "UnassignedReferenceException: The variable groundCheck of PlayerMovement has not been assigned. You probably need to assign the groundCheck variable of the PlayerMovement script in the inspector. UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <fde3c13fb32a45329a891b3df03f7908>:0) UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at UnityEngine.Transform.get_position () (at <fde3c13fb32a45329a891b3df03f7908>:0) PlayerMovement.Update () (at Assets/scripts/PlayerMovement.cs:23)"
i have tried using all the methods my teacher has recommended and they don't work
i have been following a tutorial, and i have gone over it multiple times and done everything exactly, in the inspector the tutorial doesn't assign anything to the groundcheck variable with no issue, however when i do this, i have errors
the tutorial is from 2022 and i am using the latest unity model, is this perhaps the root of the issue?
If I reference a List like this (ignore the errors), I get a reference to the original list that will remain updated to anything that happens to the original list rather than getting a "snapshot" of the list right?
It means exactly what it says:
The variable groundCheck of PlayerMovement has not been assigned. You probably need to assign the groundCheck variable of the PlayerMovement script in the inspector.
https://unity.huh.how/runtime-exceptions/unassignedreferenceexception
Yes, it's a reference type, copies are only made manually.
my tutorial doesn't have this issue and i've followed it exactly
screenshot of the tutorial
I don't have access to this tutorial, they probably assign the value later
The error isn't complicated
I don't have access to this tutorial
It's impossible to say whether there's an issue with the tutorial. The error says the value hasn't been assigned, and you're showing that it isn't. So assign it the appropriate transform and move on
the tutorial doesn't do this