#💻┃code-beginner
1 messages · Page 44 of 1
Does any object in the array have any part of its bounding box intersect with the bounding box of the given box?
i think thats right
you're asking if there are any intersecting colliders.
The function you're using returns an array of intersecting colliders.
A Collider[] is not a true/false (aka bool)
no it's asking which colliders are overlapping
and gives you an array containing all such colliders
so what do i need to add to this line of code in that respect then?
think about it
how do you go from an array of colliders to an answer to your question "are there any colliders"?
what would that array look like if there are no such colliders?
what would it look like if there is at least one collider?
Alternative:
Use Physics.CheckBox() if you don't care about which colliders it detected, just if it detected anything. Returns a bool, so should be compatible with your method.
I understand the second question being no and the third question being yes, but the first question is just kinda going over my head
none of my questions were yes or no questions though... assuming you were responding to me
no theres no colliders that overlap
I'm not asking what the actual case is here
I'm asking how you would write code to determine that
and yes SPR2 is correct and you should be using that instead, but if that didn't exist, you should be able to figure out how to use OverlapBox
oh sorry i was misunderstanding
The array would look... empty. Right? Not a yes or no, but an integer value...
How would compare the integer value to turn it into a bool?
Arrays have a length property to see how many elements are in it btw, if that is the part you are struggling with
https://gdl.space/povatexike.cs
When I try this, I get an error because selectedObject is unassigned?
do I need to do something special to make it "remember" the variable from the previous loop?
you'll need to account for the case when selectedObject was not assigned yet, yes
the variable already remembers from the previous execution, that's the point of the variable
sorry
return Physics2D.OverlapBox(coll.bounds.center, coll.bounds.size, 0f, jumpableground); so is that right? as there is 0
Physics2D is completely different from Physics
you can't interchange them
sorry i didnt mean to add the 2d id just hit the wrong one, i meant Physics
return Physics.OverlapBox(coll.bounds.center, coll.bounds.size, 0f, jumpableground);
that is what i meant
Wait...
#💻┃code-beginner message
But AREN'T you doing 2d?
Didn't we already establish that doesn't work?
That would still return an array. Is that even different from before in any way?
think about what OverlapBox returns
no thats a new line of code i just wrote without the vector2
the vector2 is totally irrelevant to the problem
The vector2 is irrelevant to this issue though
Damn, too slow
I'm not even really sure which Vector2 you're talking about, but it doesn't matter much
Does this help?
bool MyFunction() {
Collider[] colliders = Physics.OverlapBox(coll.bounds.center, coll.bounds.size, 0f, jumpableground);
return ??? // << what goes here?
}```
i thought thats the issue because when changing boxcast to overlap box the error was cant convert vector2 to int
Does Unity require .NET framework?
Yea
I gave you the answer right here
#💻┃code-beginner message
so the integer value is 0?
And that would mean there are no colliders in the box
How would you turn that into a bool
What comparison would you make?
is there any colliders in the box
Yeah... and what comparison operator would you use?
= 0
and what things would you actually be comparing?
what do you want to compare to 0?
That is an assignment
the integer value and the bool is what we are comparing
what integer value?
There is no integer here
how many colliders are in the box
there's an array of colliders
we don't have a box anymore though
we have an array of colliders
so what does the 0 here stand for sorry
i think thats throwing me
i don't know , you wrote that
but it's also completely irrelevant
ignore what's inside there
bool MyFunction() {
Collider[] colliders = Physics.OverlapBox(/*stuff that doesn't matter*/);
return ??? // << what goes here?
}```
so what part of this am i focussing on
i see
what do we put in place of the ???
we have an array of colliders called colliders, which contains all of the colliders that are in the box
we want to know if there was something or nothing in the box
what do we do?
collider length
Good!
needs to me more then 0?
yes!
yes!
that will return true if there are colliders in the box
false if there are no colliders in the box
private bool IsGrounded()
{
Collider[] colliders = Physics.OverlapBox(coll.bounds.center, coll.bounds.size, 0f, jumpableground);
return colliders.Length > 0; // << what goes here?
}
so this should be correct?
Should be, try it
Argument 3: cannot convert from 'float' to 'UnityEngine.Quaternion'
i get that errpr from the 0f
So, why are you using a float where it wants a rotation?
do i need to change that to Quaternion.identity
I sent you the documentation for OverlapBox that shows what parameters it expects and in what order
or am i on a completely different track
Try it
so now it does that
doesnt even react to the space bar being pressed and loops the jump animatio from srat to finish
added a debug to the jump and its like the jump isnt even being registered anymore
Why does my pc crashes when I save a script in Visual Studio? My whole pc like hangs and crashes.
It doesn't happens everytime but most of the time, yes.
And also my Unity runs as an administrator everytime, I've checked properties and everything. Is there anything I can do instead of create a new standard user account?
Hi! Is there a way to use Rigidbody2D physics system, but make velocity completely static?
Is there any way to share code from a .net 6 project with my unity project?
my server and client need to share code but my server is .net 6
Thanks
Show updated code. Also, what is the layermask set to, that never changed right?
is it possible to reference "other" from outside of an OnTriggerEnter method?
You can save it to a variable
Otherwise no, it is locally scoped
how would I save it to a variable?
Make a variable of that type, and use an equals sign
just set one beforehand and inside the method assign other to that variable?
Yep
oh ok
so I am doing it right
in that case how can I make a variable inside ontriggerenter update even if the method isn't called?
You would make the variable OUTSIDE ontrigger. Otherwise that variable would also be locally scoped
You would also have to check if it's null before using it because of what you said
Um guys can anyone help me why my camera ain't following the player SMOOTHLY? It is following "smoothly" but it's like SHAKING a lot so I don't think we can call it "smooth".
Show code
how would I make distFromCenter track noteCenter if I can't reference other directly?
{
notesInside.Add(other);
notesReady = true;
noteCenter = other.bounds.center;
distFromCenter = Vector3.Distance(noteCenter, hitCollider.bounds.center);
Debug.Log(distFromCenter.ToString("F1") + " from center on touch");
}```
public class smoothCameraFollow : MonoBehaviour
{
public Transform target; // The object the camera will follow
public float smoothSpeed = 0.125f; // The speed at which the camera follows the target
public Vector3 offset; // Offset from the target's position
void LateUpdate()
{
if (target != null)
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
}
}
}```
what is hitCollider?
the object that has the trigger
Where do you change smoothspeed? Lerp doesn't take a speed, it takes a fraction between the first two variables
im trying to track the distance from the center of trigger object and the center of the object that has triggered it
but anyway you'd just make distFromCenter a property - so it gets calculated whenever you use it:
float distFromCenter {
get {
return Vector3.Distance(mostRecentNote.transform.position, hitCollider.transform.position);
}
}``` and save the note in a variable called mostRecentNote
Um so how can I do that...?
but I need distFromCenter to be updated every frame
this code does that
oh
it actually does better than that - it's updated whenever you read it
What is a popular error detection extension for Visual Studio?
I recommend following the first three links here
https://unity.huh.how/lerp
Visual Studio?
It detects its own errors
The extension is itself
Weird
Okay, thank you.
I don't get any red zig zags
Make sure it's configured
!vs
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
• Other/None
does !vs not work now? Did it ever work? Am I going crazy?
They changed some commands, I guess !vs no longer exists
Does !vscode?
Nope
!vsc
Welp, it's all in the general IDE one at least
Looks like the #854851968446365696 commands haven't been updated to reflect the changes yet either
i have a question
how do i make my character to hide then wait 1sec and then show again and play an animation
use a coroutine
or bake all of that into an animation
you can use a coroutine whenever you want
I guess you're saying if the coroutine is on the character and you are deactivating the character object? No, but you get around that in many ways:
- only disabling the renderer, not deactivating the whole object
- putting the renderer on a chilkd object and deactivating that
- running the coroutine on a separate object entirely
thank you
the layermask stayed the same yes
How can I design levels the quick and easy way in Unity 3D? By creating new sprites, Duplicating and replacing is hard and it takes time. Is there anything else I can do to create objects?
Debug the colliders value
Is it actually ever more than 0
I'm wondering if using the exact size of the collider is making it so it doesn't reach the ground
what code do i use specifically i only know how to debug.log and say something
does anyone understand how to make navmesh stuff work? every video tells me to download specific components but I assume these old videos only have links for stuff that won't work with my unity version
Debug.Log(colliders.Length);
Capital L, sorry
do i just put that in start?
or update i meant
What? Start runs once in the entire lifetime of the object. How would that help?
Do it in IsGrounded
You can't access colliders outside of IsGrounded
It's a locally scoped variable
okay i meant update anyways i thought that would tell you for every frame
ohhh i didnt know that thasnkyou
It WILL tell you every frame if you do it in IsGrounded
Since you call that method in update
Anytime you declare a variable, it will have a scope. If you do it in a method, its scope is that method. If you declare it in a class, its scope is that class (but in that case you can use access modifiers to change the scope it can be accessed in)
should i worry about the error?
It's a warning and yeah
It is saying the debug can litterally never be accessed or run
You return from the method the line before it
So it will NEVER run
how do i fix that?
The issue is that your code has a return on the line before it...
so i need to remove the return before colliders length/
a return ends the function
No!
No no no
Just simply move the debug lol
Select with your mouse the Debug.Log() line and press ALT + UpArrow
It can't be after the return, right? And it can't be before you actually create variable you are debugging, right?
just saying 0 colliders
when pressing play
Then it isn't reaching the ground
Move it down
Umm how do I duplicate tilemap objects...?
ive moved it so it is as on the ground as it can be and even in the ground so when hitting play it bring it up to the ground but no change
What are you moving down?
Hopefully not the player?
the colliders
Yeah no. Move the OverlapBox down
Offset the position downwards
You use coll.bounds.center
And the size
But the colliders prevent it from going into the ground..
Also, can you show a screenshot of the inspector of the ground
Ctrl + D to duplicate any GameObject
so i just add down to the end of the coll.bounds.centre and coll.bounds.size or am i wrong
ignore me
theres inspector of the ground + the new code to size down and move down, but still no change @summer stump
Change the size back
Also... just to make sure... show the layermask field
sorry how do i shwo that?
Send a screenshot of the player inspector with jumpableGround variable expanded/clicked
Also, why have a GroundLayer and jumpableGround?
Is _Idle_0 your player?
And I wanted the layermask expanded, but it shows Ground so that should be fine
i had an old way to do the ground check involving a ground layer so when it is detecting the ground then i can jump, if no ground is detected then the player jumping is true but i replaced it with the new one and forgot to delete the old layermask
Is this the right way to do what I'm trying to do?
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}```
I forgot what I had to write and searching the web will take a while...
I hope you understand the code, I don't know how to explain rn :/
yes just forgot to rename it its a sketchy looking code just wanted the script nailed on before i start tidying up
That will Add force vertically if you press the left mouse key or touch the screen.
And that's it
Got it, thank you.
Ok... so, you offset the position fine. The layermask is right.
Did you change the size back?
yes size is as it was before moving it down and making it smaller
Ok... and it is not working still?
Like, the debug still shows 0?
yeah still just stuck in jump animation and debug saying 0
if it helps its also showing the debug a second time every time i press the space bar, aswell as ever frame
I dunno. The only thing I can think is that you are in 2d and are not using the Physics2D version...
But I dunno if that is strictly necessary
Can't check, as I'm on my phone
could i test it incase that is it or unlikely
What I am trying to achieve is this:
I have a linePrefab to which LineController script is attached. Similarly I have a TravellingBallPrefab to which the TravellingBalls script is attached. The balls are spawned after every "interval" & travel along the line with "speed", & have "lifeSpan". These speed, interval, lifeSpan are controlled via SlidersWithEcho script which has the sliders.
The issue I am facing is this:
Except for speed, the interval & lifeSpan for the balls prefab is not being controlled properly. I wanted every ball to have it's own speed, lifeSpan & interval I think can be common because after every interval new ball is spawned. How can I properly use sliders to manipulate the lifeSpan & interval after which ball will be spawned?
LineController.cs https://pastebin.com/HG27K34S
TravellingBalls.cs https://pastebin.com/wuVGV36H
SlidersWithEcho.cs https://pastebin.com/hkzNA7EX
You can certainly try
Here are the docs for it.
Probably want the middle overload that returns an int to keep it similar to yours
https://docs.unity3d.com/ScriptReference/Physics2D.OverlapBox.html
It is pretty different though. You'll need to pass in an array instead of assigning it TO and array
You would assign it to an int instead
i seriously cant figure it out
got some issues trying to flatten my 2d array and just noticed this, how is this wrong size? [2,3] is right one not [3,3] or [2,2] why it differs lol
Can someone tell me what's wrong with it?
Try this instead
lmao
line 7 is the problem. Finish writing it.
but yes please share screenshots in the future
Okay thanks
3,3 would be 3 sets of 3
you have only 2 sets of 3
3,3 would be 3x3, as in 3 arrays of 3 elements.
You have 2 arrays of 3 elements, 2,3
oh bruh
Ok I need serious help right now, I'm trying to make a game in which you're a square trying to avoid touching the top, bottom and the objects that'll appear in your path, the thing is I'm adding the force to move up(The only thing you can do is move up, the square will go down because of the rigidbody) adding the force make square go up too fast or too slow and I'm confused what to do here :/ It's 2D game btw
Here's the code if needed:
using UnityEngine;
using UnityEngine.SceneManagement;
public class playerMovement : MonoBehaviour
{
public float movementSpeed;
public float jumpForce = 10f;
private Rigidbody2D rb;
public string sceneName;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetMouseButton(0) || Input.touchCount > 0)
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
transform.Translate(Vector2.right * movementSpeed * Time.deltaTime);
}
void OnCollisionEnter2D(Collision2D collision)
{
SceneManager.LoadScene(sceneName);
}
}
Sorry for writing a long ass message btw
You're mixing force based movement and teleportation
That's going to wreak havoc on your momentum.
If you're using physics, don't move with translate
can anyone elsethink of a fix for this please?
Got it, thanks for that. But the main problem still remains tho, the force works with the mass of the object and when the object's going down it won't go up at the same speed, that is why sometimes it's slow and sometimes it's going up fast.
That makes my game 10 times more harder
If you want the speed to instantly change to a fixed amount, modify velocity instead of using AddForce
this is happening largely because you're using Input.GetButton and therefore adding force every frame
if you used FixedUpdate and/or GetButtonDown it would work more consistently
never add force in Update
Yeah but the problem is with the physics, like said here, use velocity instead of AddForce, I'll try that.
Got it, thank you.
wait I just realized the translate was to move the object to the right side, um how can I use the Velocity for it? rb.velocity.x makes the object move up, isn't y is to move up and down?
my particle system won't play even though my script says partSys.Play()
If x is moving your object up then your world is sideways
It isn't?
Here's the code:
using UnityEngine.SceneManagement;
public class playerMovement : MonoBehaviour
{
public float movementSpeed;
public float jumpForce = 10f;
private Rigidbody2D rb;
public string sceneName;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
if (Input.GetMouseButton(0) || Input.touchCount > 0)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
rb.velocity = new Vector2(rb.velocity.x, movementSpeed);
}
void OnCollisionEnter2D(Collision2D collision)
{
SceneManager.LoadScene(sceneName);
}
}
Then an X velocity wouldn't be pointing up
You're changing the y value of the velocity here
wdym
I mean you're changing the y value of the velocity here
wheree
It's velocity.x
In both places where you change the velocity
You're setting the y velocity to movementSpeed
The jump force one is correct, that one should be y
Yeah but movementSpeed, I mean there is no declaration of an axis in the variable, I don't understand about that one, what can I do?
does anyone know how to play a particle system, i dont get this 😭
When you create a vector, the first number is x, and the second number is y
Ohhh I got it now man I'm dumb tysmmm
it doesn't work for whatever reason
It does. It will play whatever particle system you call it on
{
Destroy(note.gameObject);
AddScore(1);
notesReady = false;
print("Good Hit");
partSys.Play();``` my script should be playing the particle system along with executing all that other stuff, but it doesn't. I have the particle system saved as a prefab
What is partSys
And what is it assigned to
So it is playing. It's playing the prefab, which does not exist
The prefab that is not in the scene and thus cannot be observed by anything
https://www.youtube.com/watch?v=1OOWHB-BOAY I followed this tutorial but it does not seem to be working. When launching, the program gets stuck in a constant loop and instantiates infinite text gameobjects that contain the string from the .txt file im reading from.
I want the program to read from the .txt file and change the text gameobject under Input Field to whatever it reads from the .txt file
In this Unity Tutorial, i'll show you how to display information in a text file!
https://youtu.be/iFJeg9AzN2Y (How to write to a text file)
*Note, a vertical layout group and content size fitter was placed on the content window to allow the text objects to display one after another and scroll properly.
Twitch https://www.Twitch.tv/PrefixWiz
...
so the prefab needs to be somewhere in the scene?
thats weird
If you want to play a particle system that you can see, it needs to exist
How is it weird? Lighting the schematic of a firework on fire won't make a spectacular light show it's just gonna burn up a piece of paper
Show code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so does the prefab also need to be placed where I want it to be played?
or can it be played on the transform im calling from
Yes, if you want the object to be in a specific place it needs to be in a specific place
I want to make my enemies stop following the player after leaving a trigger zone. The thing is there will be multiple trigger zones and the enemies will be instantiated to respective zones. How can I tell enemies what trigger zone they are “linked”to (the ontriggerexit/enter is on the player)
When you spawn the enemy, set a variable on it that references the specific trigger. Then, when you have an on trigger event you can see if the trigger it interacts with is the same one they have a reference to
okay
so for example, if I placed a prefab of a particle system that makes a blood splatter onto an enemy, and when the enemy dies it plays, does that mean the particle system will follow the enemy transform's position?
A particle system is just a component on a game object. Assuming it's in local space it's just going to play from wherever the object is
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.
i see, would it be better to just paste the component straight onto the object instead of adding a child object with the particle system to the object?
Your TheText object wouldn't happen to have a GetText component on it would it?
It doesn't matter, as long as the particle system is where you want it and you have a reference to it
thanks so much
what do you mean?
Does the object you have referenced as TheText have a GetText component on it
yeah, the script
So, for every line in your text file, you are spawning an object that will look through every line in your text file to spawn an object that will look through every line in your text file to spawn an object that will look through every line in your text file to spawn an object that will~~
Yes i see the problem. I dont want to instantiate anything though, i just want the text gameobject under input field to change to whatever is written in the .txt file and i have no idea how
Do I need to use a unique tag for every unique reference to a trigger?
If you don't want to instantiate anything, why are you instantiating anything
No, you shouldn't be using tags at all
I followed the tutorial hoping to get at least similar results to what i wanted and then change it
private void SpawnShip()
{
GameObject enemyShip1 = Instantiate(_enemyShip1PF, transform.position, Quaternion.identity);
enemyShip1.GetComponent<EnemyShipPathfinding>().SetTriggerZone(???);
}
I'm not sure what kind of reference I should be adding here
bruh why is the documentation website so slow
Which trigger do you want to set this objects trigger zone to?
Also, why is _enemyShip1PF a game object instead of the type you actually want from it
I was thinking I can assign some kind of reference in the enemyspawner object with a serializedfield so I can reuse the same script for every unique zone
{
Instantiate(TheText);
TheText.GetComponent<Text>().text = line;
}``` how can turn this into just changing the text under input field instead of instantiating?
Instead of instantiating something, don't.
yes but what do i write
the functionality I'm trying to get is:
Make it so when the player leaves a zone, the enemies from that respective zone that are linked to it will no longer follow you
i dont know any syntax for this
Yes, and what you've written does that (assuming your setTriggerZone function changes that variable). Just pass in the the trigger you want it to ise
Why the variable ain't showing in the inspector? Yes, it is a public gameobject variable.
You are already changing the text of the object you instantiated. Instead of changing the text on that, change it on the object that exists in scene instead.
What variable
Do you have any compile errors
Nope
Show the full code for GameController
public class GameController : MonoBehaviour
{
public GameObject tapToPlayText;
private bool gamePaused = true;
void Start()
{
Time.timeScale = 0f; // Pause the game initially
}
void Update()
{
if (gamePaused)
{
if (Input.GetMouseButtonDown(0) || Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
StartGame();
}
}
}
void StartGame()
{
tapToPlayText.SetActive(false);
gamePaused = false;
Time.timeScale = 0.1f; // Slow down the game
Invoke("ResumeNormalSpeed", 1f); // Resume normal speed after 1 second
}
void ResumeNormalSpeed()
{
Time.timeScale = 1f; // Set normal speed
}
}
Show a screenshot of your unity console
Try reimporting the script, or changing something and saving it again
Alright it works now, thanks.
If I have List<Monobehaviour>, is there a way for me to produce a simple IList<GameObject> defined based on monobehaviour => monobehaviour.gameObject, without actually making a whole list?
I think that is useful, but maybe not exactly what I'm looking for
I'm thinking about which is the type I should return, to give access to that list as though it were an IList<GameObject>
IEnumerable is good to enumerate, but I'm wondering if I could maintain the info of Count by giving an IList
ok, Linq Select is the way to go. ty lol
Um so in my player code I added an OnCollisionEnter that'll show me the lose game scene but I've made an OnTriggerEnter that I want it to show the win game scene but uh it does the same as OnCollisionEnter, what can do I to fix this? I don't want the change scene on collision script to every object that'll make me lose the game if we collide with it...
Because there are like thousand of them and I'll have to add the script to every single one of them, is there anything I can do without changing those objects?
can someone lead me in a direction to making my inventory have drag and drop
what does this error mean?
Help-
You cannot both get and set .color in the same line, because it's a property, not a variable. You would need to store the color in a variable, modify that variable, then set the text's color back to that
gotcha
So, when you collide with something solid, you want to lose, and if you collide with something not solid, you want to win. Is that right?
Yes
Show code, show the inspectors of this object and the thing you are trying to collide with that isn't doing what you want
using UnityEngine.SceneManagement;
public class playerMovement : MonoBehaviour
{
public float movementSpeed;
public float jumpForce = 10f;
private Rigidbody2D rb;
public string sceneName;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
if (Input.GetMouseButton(0) || Input.touchCount > 0)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
rb.velocity = new Vector2(movementSpeed, rb.velocity.y);
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("FUCK"))
{
SceneManager.LoadScene(sceneName);
}
}
void OnTriggerEnter2D(Collider2D collision)
{
SceneManager.LoadScene(sceneName);
}
}
(Ignore the tag name plzz)
Both of these load the same scene
I don't know why you expected them to do anything different
Am I stupid,
Why is this function not resulting in the camera not returning to the position it started, I understand why it might be off by a little but it's like not even moving back at all: https://hastebin.com/share/ebekajiser.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Is the condition for the second loop already true? Is forwardPunchCameraShakeDecreaseLength 0 or less?
Do you get both logs?
yeah
they're different values tho which is weird
oh actually it makes sense y theyre differnt
Log the position before the first loop, between loops, and at the end. Give them each a different prefix so you know which is which. Debug.Log($"Before: {transform.position}"); and then the same for middle and end
Here its only off my one tick which makes sense, but sometimes its a lot worse, let me see if I can get an example
I have a feeling the issue is coming from a different script
You're going to be off by one or two on occasion. You said it wasn't moving back at all which is a different problem
The number of time steps to make 0.3 seconds is not going to be consistent
yeah lol
yeah there's no way you couldve known that just by looking at it
if I want to implement IEnumerable<T>, why do I need to implement both IEnumerator IEnumerable.GetEnumerator() and public IEnumerator<TStored> GetEnumerator()? Isn't it a bit redundant?
is there a function in unity like CrossFadeAlpha but for the size of a text element instead of alpha?
you can use a tweening library to do this stuff.
DOTween is pretty popular
What is a tweening library?
It's a library for changing one value to another over time
Ah
Like moving an element around, or resizing, shaking etc
But if you want to do it manually you can too
That sounds like exactly what I need
I would recommend trying out DOTween
Actually there's another one on the asset store that's meant to be way better...
Is it not a standard unity asset that comes with every project?
PrimeTween
No, they're third party
Because this sounds really good, I'm just not sure if I'm gonna be able to use them since they're a third party addon
Some legal restriction?
Or because it's a school project/
Most ppl add a tweening lib to their unity projects
But if you can't, you can write your own
It's a uni project, I just need to find out if I'll get docked points for using a third party addon or not since my specialization is programming
static IEnumerator TweenLocalScale(Transform transform, Vector3 to, float duration) {
var from = transform.localScale;
var startTime = Time.time;
var endTime = startTime + duration;
while (Time.time < endTime) {
var t = Mathf.InverseLerp(startTime, endTime, Time.time);
transform.localScale = Vector3.Lerp(from, to, t);
yield return null;
}
transform.localScale = to;
}
//
StartCoroutine(TweenLocalScale(someTransform, Vector3(1, 2, 3), 1f));
Now that I think about it I should be fine considering it's just a library, unity has plenty that we already use
I would think so, yes.
So long as the library isn't doing the core thing you're being assessed on
Just ask your teacher
I would definitely recommend using a library over writing it yourself
It's a good tool to know
Oh nah I just want to cut down the time spent programming tiny cosmetic changes, the core stuff is all me
Yeah, thanks a lot for recommending it, I had no idea something like this existed
Hey guys I was following someone's tutorial where they gave a ragdoll a 3rd person camera controller: https://hatebin.com/fwidzztlpp but after following their steps and applying the component, the camera moves left and right when you move your mouse up and down, similar to in real life when you tilt your head from left to right, side by side. Could anyone help me with this?
how could i make a slot be able to hold up to 160 of the item thats inside it?
i already have item data for each item to have a stackable bool
but im not sure how id make stacking in the actual slot
Create a ItemStack class that would hold a list of the item data. And make the slot contain it.
ive already done that
Then I don't get the question
nvm i was confused
so then when items are added to the inventory
if its a stackable item it should instead go to the ItemStack class instead of the slot class?
or both and the slot just holds data but not like the amount
I'd just make all slots hold Stacks and the stacks would have a reference to the item definition and item instances list. If it's a non stackable item, it would just have 1 instance of an item in the list.
if it isnt stackable it wont use the ItemStack class at all probably
oh well
But if you really want to differentiate, you could make a stack inherit from an item instance so that you can pass them to the slot as an item instance.
ItemStack: ItemInstance
i could just make them all a stack and limit the non stackable items to 1
which sounds simpler
like you said
Yeah, that's what I meant.
ya
should i really be changing anything inside of this then?
Yes. Instead of ItemData, it should be ItemStack
which ones
I read a bit more abouot my issue and turns out I can't rotate the camera at all to adjust it, if i do, then it'll just rotate on the Z axis instead of Y but it's not looking at the player now
[Header("Item inside of the slot")]
public ItemStack _itemInSlot;
https://img.sidia.net/ZEyI5/MiTizOfu11.mp4/raw
So thanks to your help here I got the new Inputsystem for local multiplayer running perfectly, the only problem I have now:
How can I allow the first player to navigate down to the start button? Currently both of the added players are contained in their little button test structure at the top but i'd like the first player to be able to break out of it and press start, any way to make that possible?
I attached a screenshot of how the "button container" prefab has the containment per-player configured
how do you get the amount of data inside of a list
myList.Count
Do you mean the number of elements? if so, lists have a Count property
yeah i had it right, i just made a goofy error
thanks anyway
im getting a null error for my scriptable objects bool whenever its unchecked on the object in the inspector
bools can't be null
Might be a silly question but, can you make a TMP_Text button, move you to a new scene?
I've been trying but, can't seem to get it to work..... 😅
You can make th button call some code that would load a new scene.
I do have that script but, it's not working.....
Is there anything wrong with this code??
I'm not getting any prompts from the console......
using UnityEngine;
using UnityEngine.SceneManagement;
public class Go2GameMode_Scene : MonoBehaviour
{
public void LoadGameModeScene()
{
SceneManager.LoadScene("GameMode_Scene");
}
}
The scene I want to go to is called GameMode_Scene
I'm trying to create my build, this is intended to be rendered under HDRP. However, it says that it's also rendering the Universal Pipeline as well
Add a log in your function to see if it's executed.
That would imply that you have urp shaders referenced somewhere. The safest bet would be to remove the urp package from the project.
real quick wondering, how do people achieve tabs like this? I cant imagine them having a sprite for each tab
the same 9-sliced sprite would be used for all of them . . .
well heres the tricky part for it
i want to do tabs a bit like this
where the gradient of the tab follows the ui color
i was thinking maybe a mask for the highlighted tab or something could maybe work?
hard to say
try a ui channel, this is a code channel
nothing tricky. just use an image with a gradient for the background and mask to shape of the tab. this is a #📲┃ui-ux question though . . .
fair enough, and ill try that out, thanks
Hello, I am quite new to coding in of itself, and I would like to ask-
I have a script to select units written by a friend, and I would like to ask- what does it actually do? I would like to understand unity more instead of just constantly asking other people to help.
public class Unit : MonoBehaviour
{
public InputManager inputManager;
void OnMouseDown()
{
inputManager.UnitSelected(this);
}
public class InputManager : MonoBehaviour
{
public Unit selectedUnit;
public void UnitSelected(Unit unit)
{
selectedUnit = unit;
}
first: !code
second: it uses the OnMouseDown method on the MonoBehaviour class which detects clicks on that object. when a click has been detected on that object is calls the UnitSelected method on the instance of the InputManager class that it has a reference to and passes itself. The InputManager's UnitSelected method just assigns the reference that was passed to it to a field on that class.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh, sorry and thanks
hey could anyone help me identify the problem? im getting null reference exception in this line
var collectionSlot = unitsCollectionController.collectionSlots.First(c => c.unitData.objectType == unitSlots[index].assignedUnit.objectType);
unitsCollectionController is assigned
unfold the Unit Slots collection there and make sure that it actually contains non-null elements
well there are null elements, because the fill based on what units i choose
so for example right now in the deck i have 2 units, digger and north assasin
and if i add another it fills the [2] index
Hey, I have a bunch of blocks which each have a script (the same script _containing some variables. Now how do I get the information from a certain block into a different script? Im doing the inspector link method but it only allows me to manually select which block it takes the script from in the inspector. How can I make is so that I can just pick which gameobject does it take the information from? I hope that I wrote that clearly
It has null assignedUnits
it was a wrong screenshot not of this list, sorry
everything in the collectionSlots list is referenced, theere are no empty elements
Yeah but things inside those slots vould be null
the unitDatas might be unll
And your Linq is trying to use those
in the collectionSlots?
Basicly: How can I make it so that I can change "A1" my script
everything looks good here
the unit data is referenced
and that's the only thing im using
var collectionSlot = unitsCollectionController.collectionSlots.First(c => c.unitData.objectType == unitSlots[index].assignedUnit.objectType);
objectType is an enum
there are so many objects on that line that could potentially be null
unitsCollectionController is referenced
collectionSlots is a list with no empty elements
how have you verified that any of this not null
unitDatas are referenced inside the elements
and just looking at the inspector isn't really enough
wdym i can see it's referenced
what have you done to verify your assumptions
The screenshot you deleted, is it related? It had null elements used in that Linq
well then i guess everything is fine and your issue is solved
and collectionSlots list doesnt contain any empty elements inside
It is not related
public void UpdateUnitUI(int index)
{
unitSlots[index].isAssigned = true;
unitSlots[index].assignedUnit = PlayerDeck.Instance.unitSlots[index].assignedUnit;
unitSlots[index].slotImage.gameObject.SetActive(true);
unitSlots[index].slotImage.enabled = true;
unitSlots[index].slotImage.sprite = unitSlots[index].assignedUnit.unitSlotSprite;
unitSlots[index].plusEmptyImage.enabled = false;
var collectionSlot = unitsCollectionController.collectionSlots.First(c => c.unitData.objectType == unitSlots[index].assignedUnit.objectType);
if (collectionSlot != null)
collectionSlot.hasBeenAdded = true;
unitsCollectionController.RefreshCollection(index);
UnitDeckPreviewController.Instance.AddUnitToPreview(index, unitSlots[index].assignedUnit);
}
this is entire function
i have a UI preview of my current deck
PlayerDeck.Instance.OnUnitAdded.AddListener(UpdateUnitUI);
and im triggering this function everytime i add a unit at specific slot index
Debug.Log(unitSlots[index].assignedUnit);
var collectionSlot = unitsCollectionController.collectionSlots.First(c => c.unitData.objectType == unitSlots[index].assignedUnit.objectType);
if (collectionSlot != null)
collectionSlot.hasBeenAdded = true;
And this is line 48?
instead of using linq you should write a loop and do the check manually so that you can null check the relevant objects instead of just assuming that they are not null
yes
How do we know that PlayerDeck.Instance.unitSlots[index].assignedUnit is not null?
I agree that a loop will make it more debuggable
because
Debug.Log(unitSlots[index].assignedUnit);
prints correct value
unitSlots[index].assignedUnit = PlayerDeck.Instance.unitSlots[index].assignedUnit;
and before debug log im doing this
so if PlayerDeck.Instance.unitSlots[index].assignedUnit; would be null
don't make assumptions. actually verify what is happening
the debug.log would be null aswell
are you actualyl reading what im writing
well you're clearly not reading what i've written
how is that an assumption?
PlayerDeck.Instance.unitSlots[index].assignedUnit; is not null
otherwise the Debug.Log will print null
What about unitsCollectionController or unitsCollectionController.collectionSlots or c...
now what about the individual elements of the list and the objects you access on those elements?
stop making assumptions that they aren't null when there is at least one or more null object
the only element that im checking i unitData which is SO and unitSlots[index].assignedUnit
and both aren't null and this is not an assumption xd
oh my mistake, here i was thinking you were using the First method from linq which will loop through the collection. i guess you aren't doing anything at all that could end up with a null object
Well you are being a bit defensive
how have you verified that?
Debug.Log(unitsCollectionController);
Debug.Log(unitsCollectionController.collectionSlots);
Debug.Log(unitSlots[index].assignedUnit.objectType);
foreach(var c in unitsCollectionController.collectionSlots)
{
Debug.Log(c.unitData.objectType);
}
nothing of that
prints null
nothing else can be null
in this line
var collectionSlot = unitsCollectionController.collectionSlots.First(c => c.unitData.objectType == unitSlots[index].assignedUnit.objectType);
Do you have a duplicate of this script in the scene?
no
Hey guys, creating a very simple ship game, 2D, where i shoot and destroy 1 enemy.. i dont know what could be wrong with my scripts.. have like 2 c# scripts 1 for enemy 1 for player, with just few lines, but i feel like when I am moving the ship sometimes there is a LAG on the input and even tho i already released the keys it continues to move for half a second like if it was a lag or something, any potencial reasons for that?
try this and see if it prints any errors. if it doesn't then the issue does not lie here.
CollectionSlot collectionSlot; //obviously change this object's type to whatever it's correct type is
var collection = unitsCollectionController.collectionSlots;
for(int i = 0; i < collection .Count; i++)
{
var slot = collection[i];
Debug.Assert(slot != null, $"Element {i} is null on {name}", gameObject);
var unitData = collection[i].unitData;
Debug.Assert(unitData != null, $"Element {i} contains a null unitData on {name}", gameObject);
if(unitData.objectType == unitSlots[index].assignedUnit.objectType)
{
collectionSlot = slot;
break;
}
}
show !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
// Getting the Input to use A,D,W,S
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.right * _speed * horizontalInput * Time.deltaTime);
transform.Translate(Vector3.up * _speed * verticalInput * Time.deltaTime);
} ```
I call it on void update
it works, but sometimes it just moves with a lag, and its so simple script.. imagine a complex one.. 😦
are you sure that it is actually lagging though? and not perhaps something just being stuttery, perhaps camera movement being stuttery?
if you think it is actually lag then you need to use the profiler to determine the source of any performance issues
does the ++ operator just add 1 to the current value?
yes
thanks
i++ is
int temp=i;
i=i+1;
return temp;
a quick google search would have also told you the same thing though.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#increment-operator-
people on the discord explain much quicker and easier though 😜
microsoft documentation is pretty confusing for me too so I appreciate that the people here answer questions so concisely and in a way that's easy to understand
It even highlights the answer 🤷♂️
I'm not sure what this is called. I want to have a function which takes some C# code, creates another new function, and sets this new function to a variable. For instance ```cs
public object Action;
public void CreateNewFunction(object action)
{
Action = action;
}
CreateNewFunction(Some code here);```
Do you need to use it in runtime or is all the code written before hand? If so I guess UnityEvent could maybe work?
For now it's just at runtime but both in the longterm.
Hmm, so like the player can type the code or?
what do you mean by "takes some C# code"? are you referring to a delegate where you can pass it an anonymous function?
Right now I just want to create some functions at runtime by setting them via a code-block instead of directly to functions. Later I'll do the playercode thing.
So basically you want a input field and then the text becomes code yeah?
Or did i missunderstand?
I believe this may be what I'm looking for
So you want a runtime interpreter.
It's a pretty advanced topic. Are you sure you can handle it?
No idea... but may as well take a look.
you may need to provide more details about exactly what you are trying to do
So yeah you need a runtime compiler/interpreter, I found this with a quick search: https://github.com/SoapCode/UCompile
Dynamic compilation tool for Unity3D engine. Contribute to SoapCode/UCompile development by creating an account on GitHub.
because there are multiple interpretations for the vague description you've given
Hello guys, I am following an Udemy Unity course, still at the begining of the course but now I started to encounter a prob that even having EXACTLY the same code and setting as the teacher, he doesnt have a prob I have that SEEMS like its a LAG but not sure what could it be as sometimes when I am moving my ship and relase the key it continues to move in some direction or half a second.
Scripts:
Player: https://paste.ofcode.org/8G2N8UCrpJbHqDfjQyTR3T
Enemy: https://paste.ofcode.org/KQmAc5uHadHpAVLtw4XrR6
Laser: https://paste.ofcode.org/38jdzhzbSjuZfjSfZ9AUcfB
PowerUps: https://paste.ofcode.org/yLzhbPpfE3hNTjGgPhE9jg
Also checked the profiler and all seems to be fine.
Thank you in advance.
That's the problem, I'm not sure what it is called. But I'll try to give a better example.
well you've not really described it in a way that gives a definitive answer
you're still using GetAxis rather than GetAxisRaw
You want to write code at runtime and execute it, right?
Changed already but it didnt fix, that is why, but I can put raw again no problem
Not really sure. I'll get back to this in a bit.
What is the exact usecase for this?
if the issue is that your ship keeps moving after releasing the input keys then that is what is causing your issue
its not always I can move it for 1 minute and it wont happens and out of a sudden it happens.. its completly random
but I changed bat to GetAxisRaw
I use the new input system, it detects a input action, and then I want it to run some function. The idea is that instead of making a function ahead of time, I'd put the functions code as part of a parameter, save it to a variable, and then run the variable-function instead of a normal function.
that's a delegate
I'll look that up. thanks everyone
I am also using the old input system as the course it a bit old, but i will implement the new one when I finish it, for now I am focusing more on learning the unity it self and stuff related to it other than just bothering my mind with new or old input system as to implement the new one is pretty straight forward but I also dont think that is the prob.
Honestly I would just use a UnityEvent if possible, you have to code it ahead of time but you can change it fast and you will save yourself a lot of headaches with runtime interpration.
I'll look into this too
i am aware you are using the Input Manager. nobody has suggested you learn or implement the Input System.
UnityEvent is also a kind of delegate (sort of). it's just serializable so that it can be assigned via the inspector so it isn't directly a delegate
also there is another prob.. when i limited the SHIP to not pass the lower border of the screen. sometimes RANDONLY and sometimes jut once.. it sticks there and wont get out for like some seconds.. what also doesnt happen with the teacher. and could be a lag also or whatever it is.. as A beginner see a code so small and game so small like that already having a prob that is hard to see where the prob is, damn.. imagine trying to create something a bit bigger.
the code you are using is fairly naive when it comes to ensuring the object stays within the bounds. it's very probable that the issue you just described also happened to the course instructor but they just didn't show when it happened
you'll probably also notice that your objects can move through colliders pretty easily and the instructor probably won't show that either. but that's because you are effectively teleporting the objects to specific places instead of moving them in a way that will automatically react to collisions like with physics
yeah its a super beginer course.. so I imagine if he fixes everything if really there is a prob me as a beginer would be overwhelmed. Not sure if that would be the case. But all the tests he did I didnt see him having the prob at all. But could be just that he is hiding that as you say, no idea. Any ways its impossible for me to learn all now and I need to focus in some stuff. So for now maybe is just better to forget about this prob.. and focus on other stuff to learn that might be more important as a beginer.
Also this happens sometimes and sometimes not, sometimes i hit play.. move the char for like 5m nothing happens.. and sometimes hit play and happens in the next 10 sec.. so no idea.. if it was a consistent prob maybe would be easier to find
well if you can get a recording of what is actually happening like was suggested a bit ago by dlich that would be incredibly helpful for determining the cause
Thinking now, is there a quick way to export the game, and test it in a .exe? So I can test if that is unity or the game itself?
you can build the game from the Build Settings menu
Will try, it thank you
yeah.. opening from the .exe tried some times and for minutes and the prob didnt happen so I am assuming this is unity lag. just assuming not saying it is
if I want to send that game to someone I need to send all that folder? or just the .exe?
you can use the profiler to profile the editor to see if it is actually causing a performance issue
everything there
already checked, and I didnt see any spikes , but at least knowing the .exe is fine I am more ok with it
the only exception would be if you were using Burst, it would create a folder that specifically says not to ship it
Thank you for the help and time.
If i want to move my character by using rigidbody velocity, should i put the logic inside the Update method or FixedUpdate? Currently this is my script, but it is really buggy in regards to jumping
[SerializeField] private Transform groundCheckTransform = null;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float speed = 10f;
[SerializeField] private float jumpSpeed = 10f;
[SerializeField] private float turnSpeed = 10f;
private Animator animator;
private bool jumpKeyWasPressed;
private float hzInput;
private Rigidbody rb;
private bool isGrounded;
private void Awake() {
rb = GetComponent<Rigidbody>();
animator = GetComponentInChildren<Animator>();
}
void Update()
{
hzInput = Input.GetAxis("Horizontal");
if (Input.GetKeyDown(KeyCode.Space))
{
jumpKeyWasPressed = true;
}
}
private void FixedUpdate() {
rb.velocity = new Vector3 (hzInput * speed, rb.velocity.y, 0);
animator.SetFloat("Speed", rb.velocity.magnitude);
transform.Rotate(Vector3.up, hzInput * turnSpeed);
isGrounded = Physics.CheckSphere(groundCheckTransform.position, .3f, groundMask);
Debug.Log(isGrounded);
if (jumpKeyWasPressed && isGrounded) {
rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.magnitude, 0);
jumpKeyWasPressed = false;
}
}
typically you would get your input in Update and apply physics inside of FixedUpdate
as for why it is buggy for your jump, why are you using the magnitude of the velocity for the Y velocity of your jump? that doesn't make a lot of sense
Actually, I don't really know lol. would rb.velocity.y + jumpSpeed make more sense?
Okey, I see, it feels better with AddForce. Thanks!
is there a way to check == true null?
it's still null . . .
Would ReferenceEquals(obj, null) work?
☝️ that will work for c# objects . . .
if you destroy a unity object, you can still plug it into a dictionary as a key
not the same as actual null, if that makes sense
unity does a bunch of internal checks for null on unity objects, so you have to use == null . . .
you can't use any of the c# null checks . . .
well, I'm assigning null to represent actual nothing in this case
I thought it's because the C# object still exists but not on unity. 
I'd prefer obj is null instead since they work the same. 
Yeah, that's the weird part . . .
Is it because you can't really manually dispose a c# object?
Yep.
anyway, I made my first public git repo class
It's hard to distinguish between fake null and real null. You can have a bool on a MonoBehaviour class that marks it as destroyed but you can't access it if/when the UnityObject does become null . . .
Yeah, pretty much . . .
I guess that's a pretty annoying limitation for cases like that. 
For all intents and purposes, a destroyed object should be considered as null. There isn't really a need to make distinction.
Here is the first public class I made. Looking for rough feedback: https://github.com/LoupAndSnoop/GenericDataStructures/blob/main/ForestGraph.cs
I'd just check for null and call it a day. It's considered null when destroyed anyway . . .
in my case, null means it was never assigned. == fake null means it does exist, and my dictionaries/lists might still have keys that need to get removed in other objects that depend on it
Btw, casting a unity object to an interface and then comparing it is a foot gun ye? 
Are weak references a no go? 
wdym weak references?

WeakReference wouldn't account for destroyed objects though
Yeah sadly.
Hello! I have 2 questions, let's start with the first one. My unity engine just locked my cursor, so I can't make colide boxes or choosing items on the screen with my mouse anymore. It can be fixing by just creating a new project, but I would like to continue with my existing one. is there anything I could do to fix it? Thank you before hand 
it still wouldn't become null until the object has been GCd which could be a while after destruction
My unity engine just locked my cursor
are you assigning to Cursor.lockState anywhere?
They can get randomly gced too i guess. 
in code?
yes
nop I'm not
somehow i doubt that
if your cursor is actually getting locked, then some code somewhere in your project is locking it via the Cursor.lockState property
U can try global word search on ur IDE. 
Yes, but I can use it to choose assets in project or inspector, but not on screen
That's weird :(
what do you mean?
is the cursor locked or not?
keep in mind that it being locked is not the same as it being visible but not able to click anything
anyway, the feedback I’m looking for is mostly, after a 5-10 second glance, would you mind if you had to inherit code like this?
Then It may be the second case, since I'm not able to click on thing I see on my screen, except inspector, project and scene
so it's just affecting Game view? is it that you cannot click on buttons and other UI objects?
Nop, I'ts no affecting the game. but it's not allowing me to add any coliders or move any objects

what? you just said you can click on things in your inspector and scene, no?
can you record a video of whatever is happening? because you can't seem to describe what is actually happening without contradicting yourself
also is this even code related?
Pink area isn't working 👀
:|
Pretty much. Before, we used to cast to a c# object and then check for null, but that was inconsistent, IIRC . . .
that is your Game view. you cannot add or move objects via the game view, you do that in the scene view
Congratulations. I never thought I'd have a repo for — personal —open use either . . .
The dangers of override == operator is real. 
You know? I question why there is no System delegate called Meth for Method. 
How would you guys handle a character rotation based on the horizontal input?
private void FixedUpdate() {
rb.velocity = new Vector3 (hzInput * speed, rb.velocity.y, 0);
animator.SetFloat("Speed", rb.velocity.magnitude);
Quaternion startRotation = transform.rotation;
Quaternion targetRotation = transform.rotation * Quaternion.Euler(0, hzInput * turnSpeed * -1, 0);
// pseudocode ?
// if (transform.rotation.y < 90 || transform.rotation.y > -90) {
transform.rotation = Quaternion.Slerp(startRotation, targetRotation, .5f);
// }
I managed to get my character to rotate but I'm struggling to find a way to only let it rotate if rotation.y < 90 || rotation.y > -90
search "clamp rotation" or "clamp camera" for examples of how you can clamp it.
but basically you keep a float that you add/subtract to when you want to rotate the object. clamp that, then apply that using Quaternion.Euler to construct a quaternion from your angles and assign it to the object's rotation
do not attempt to clamp the transform.rotation values as they are not in degrees, nor the transform.eulerAngles values as they are interpreted from the quaternion at the time you access them and may not be exactly what you would expect them to be
That's exactly what i've been trying to do for the last 15 minutes... sadly. Thank you a lot!
do you mean I configured it wrong? I can’t tell if that is sarcasm
No sarcasm, I never thought I'd have a public repo to upload for myself (personal) or others to use. It's a cool thing to accomplish . . .
public TMP_Text textDisplay;
is this a good way to assign tmp text objects cuz ik there is another way and this was isnt seeming to work for me?
That's a good way to assign any variable. Setting it directly is always going to be faster than getting it some other way
in what way is that not working?
you probably trying to assign a TextMeshProUGUI to it then it doesnt work
It's fine and the preferred way for most people as both 3D and UI text derive from TMP_Text . . .
well my entire scripts were working, then some guy said he would rewrite them so thy are cleaner and more concise and now none of them work
TextMeshProUGUI inherits from TMP_Text so it would work for that just fine
again, in what way do they not work. just saying something doesn't work isn't actually providing any details about the issue
doesnt know that before
Does "some guy" perhaps mean ChatGPT
the guy is dming me so maybe he will help fix so it is fine for the moment but ill answer in a minute if not
Yikes! I call sabotage . . .
nope,\
Then you're going to have to say what doesn't work. You shouldn't need someone else to tell you that, it's the reason you asked the question in the first place
nah i think the guy just did it wrong by accident, it is annoying tho as he doesnt respond for liek 4 hours sometimes
Maybe avoid using unity Objects as dictionary keys/values if that's the case? There's also OnDestroy when you can finalize all the logic related to the object being destroyed.
as Digi said, this is what the channel is for. just post your code. you'll have the entire channel to help instead of oen person . . .
Hello! It's asking me to add something there, but I don't understand what exactly Unity wants. I tried with scripts and animations, but It's not accepting them
🥺
It wants an Animator
Like, an Animator controller. Not a script. Not an animation
it tells you what type can be added to the field in the parentheses: Animator . . .
Oh, I see
omg, what is that XDXD
You can think of it as an Animation Manager or smth.
You can look it up. There's plenty of tutorials on it
Never tried it before 

Well that's the way you control what animations you play
I believed creating animations was enough XD 🥺
are you following a tutorial?
I have an if event, and want to play a Sound before restarting the Scene. Problem is that the Scene restarts directly without playin the Sound. How to fix that?
if (hit.gameObject.tag == "Deadly")
{
deadAudioSource.Play();
Respawn();
}
Yes, i configured everything.
I followed a tutorial, but it never shown anything about animations, It's just "worked" for them
TIP: it's called an if statement
ANSWER: use a coroutine to load the scene after the sound has finished playing . . .
either make the object playing the sound persist through the scene change by making it DDOL or don't change the scene immediately
Thank you! 
thanks!
I have ItemSO which is a Scriptable Object, got multiple of them, for example: sword, axe, ...
Can I do if (item.ItemSO == itemSO)
to check if item is a sword?
do you have an item type field to compare the type of item?
Sorry for pong, but where did they get the orange box from? I only had red, green and lime one
no it needs to be that exact itemSO, sword is just a very generic example it's not an item type
Right click on a state and set as default
Yep, but is this box important or I can create an empty one and call it the same way?

that should work fine. did you test it?
It's your default state... You can make any state your default state
Armatere | openclose has motion, while empty ones don't, that's why I have a feeling I'm not doing it correctly
Idk the whole context. But yea the orange box is the state that will be entered by default. You might(?) not technically need it, since you could transition to a non default state from the Any State node based on some condition - but idk how an animator behaves whose controller doesn’t have an active state
I’ve never not had a default state
Thank you! I will just try and see if it works, althrough I have a pre feeling it won't XD
Thank you for helping me guys 
yeah seems to work, just had some other bugs lol
!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
• Other/None
i need help
i want my button to just appear when the player touches the Npc
but it doesnt shows again
Show your code
i can tick the setactive manually when the player is in the collider from the Npc
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Please post your code as written in the guide above, screenshotted code does not really help
should i just copy it?
Please follow the guide from that message
How to post !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i dont understand
Click a link at the top
Copy your code there
Click save
okay
Copy the url and paste it here
Show an image of the console tab in the Unity Editor as well
private void Move()
{
Vector3 forward = transform.forward;
float currentYVel = _rb.velocity.y;
Vector3 newVelocity = transform.forward * _moveSpeed;
newVelocity.y = currentYVel;
_rb.velocity = newVelocity;
//_rb.velocity = transform.forward * _moveSpeed;
}
Hey all. I have this move method. My game starts paused so I need to zero only the forward velocity. Since these are local variables. I could not seperate them and use individual axis. Can someone help me out
Are you sure you referenced the correct object?
yes
it also hides when i tick the setactive and walk away
Are you certain you didn't reference a prefab instead?
ye
there isnt any prefab
All objects shown in scene were always active
no
the speechbubble which the button should activate isnt
the others are active
i even restarted unity because i thought its a bugg
but it isnt
Yeah, I've tried it both On Click and just dragging & dropping it onto the UI Text Button and it hasn't been executed either way.
Did I put in the wrong place or something??
If it's important, show us/yourself.
Try more useful logging instead:cs Debug.Log($"{name} was touched by {trigger.name}", this);
instead of?
Instead of what you had prior
instead of the log: hide, show, or istoched, isnttouched?
What else?
these are all logs
.

ok
the example Dalphat gave you says "was touched by", so..
It's pretty implicit where this code can be placed.
What becomes highlighted when touch occurs?
Something should become yellow when you click the log message
So this part is working fine.
Meaning the fault has to do with your IsTouched script/object
so what should i do
Does "Show" ever print?
no
and hide does just 1time
so just in the start not when the player doesnt collides anymore
If not, it doesn't ever think "the player" it's referencing is ever touched.
Meaning "the player" it thinks is the player, isn't the one being touched
Or IsTouched is never called again
Since the code shown are excerpts, we aren't able to know the behavior that you've designed for it - the more important stuff.
It's likely possible that it's one of the two above or that you may have secretly set to the bool to false elsewhere prior to checking etc
The issue isn't related to the code shown above - we weren't given enough info.
Maybe test the two that I've suggested? #💻┃code-beginner message
but there is just one player
istouched have to be called again bcs its in the update method
If that were true, you should be getting hide/show spam in the console.
Is the console spamming hide/show?
Make it spam it or occur once with properties etc?
Spam would be referring to the method being called in Update - apparently it's not according to the video
ye it is
It wasn't prior
in the video the "hide" method is being called 1 time
Hide/Show should be called 999+ times
So that means it isn't being called in Update
but it is
I try to disconnect everything before OnDestroy, but it’s hard to catch stuff when a scene closes and destroys everything. And I need Unity objects as keys because I’m tying the unity object to something. The alternative is to give the unityobject a key field, but then I still have to do the null/destruction checking anyway, but with extra steps.
or should bcs i wrote it in the update method
We'll never know because you aren't showing useful code.
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Is it spamming the console now?
no
Then either:
- You have an error
- This object is destroyed or disabled
or 3. It is
If not, did you save the script? Are there any compilation errors? Are you not using the script (implies you've got backup scripts and aren't using the correct script)?
wait
just a side note: SCREAM_CASE is only normally used for consts
if I read PLAYER, I assume that is a const, but it isn’t. It’s a field
now it works haha
Not necessarily a coding question, but I like you guys better than the other channels:
Doing a platform adventure game with zone transitions back and forth.
Right now I only have a few, I'm setting up each full zone as a prefab that I instantiate at a pre-defined point.
My question is what's the best way to handle instantiating each new zone? Should I lay it out as one big world, each zone with its own point to spawn in when needed?
Should I alternate between a few points? Loading and unloading?
Hello fellow devs.
How can I prevent diagonal movement?
private void Update()
{
inputMove.x = Input.GetAxis(c_horizontal);
inputMove.y = Input.GetAxis(c_vertical);
if (inputMove != Vector2.zero && moveRoutine == null)
{
var dir = new Vector3(inputMove.x, 0, inputMove.y).normalized;
Debug.Log(dir);
moveRoutine = StartCoroutine(LerpPosition(dir, duration));
}
}```
you can use prefabs for each section or scenes. also, how you load can influence which method works best. try what you have now and see if that works, or check what others have done online or in forums . . .
check both axes . . .
sorry could you clarify a bit, I been at this for 4 hours already 😢
Pick a direction that "wins" over the other one. If that direction is nonzero, don't check the other one
Yea, I'm trying to find examples, but I don't really know what I'm looking for yet.
I'm thinking alternating between 2 spawn points might work best as that keeps the overall size of the map down, but might be tricky with different sized zones
you can check if both axes have a value, if so, don't move. if you want to move on one of the axes when both are pressed, do what digiholic mentioned, and pick one that "wins" over the other . . .
I tried something like this but didn't work when pressed together
var horz = inputMove.x > 0 || inputMove.x < 0;
var vert = inputMove.y > 0 || inputMove.y < 0;
if (vert && !horz && moveRoutine == null || !vert && horz && moveRoutine == null)
{
var dir = new Vector3(inputMove.x, 0, inputMove.y).normalized;
moveRoutine = StartCoroutine(LerpPosition(dir, duration));
}``` :\
yeah that sounds good , I'm trying to get this priority thing working but not sure how
Implement it both ways and pick your preferred thereafter 
You're still using two values for dir
Check if your X value is nonzero. If it is, set dir to that X value.
If it's zero, set dir to that Y value.
Or vice-versa
!learn
:teacher: Unity Learn
Over 750 hours of free live and on-demand learning content for all levels of experience!
something like this?
var horz = inputMove.x > 0 || inputMove.x < 0;
var vert = inputMove.y > 0 || inputMove.y < 0;
if (inputMove != Vector2.zero && moveRoutine == null)
{
var dir = new Vector2();
if (horz && moveRoutine == null)
{
dir = new Vector3(inputMove.x, 0, 0).normalized;
}
else if (vert && moveRoutine == null)
{
dir = new Vector3(0, 0, inputMove.y).normalized;
}
moveRoutine = StartCoroutine(LerpPosition(dir, duration));
}```
It works for left / right but doesn't work up and down for some reason
Oh wait. I wrote Vector2 intead of Vector3
I think it works
thanks for the push in the correct direction @polar acorn & @cosmic dagger
Hello, can someone tell me whether/how i can implement gizmos in one script that i can toggle individually (preferably from the unity editors gizmo menu)?
Thanks, i got that covered. I want to draw 2 seperate lines, for different purposes and want to be able to select to just draw either one or both of them. Cant find anything about that there.
bounce a 2d object with a OnTriggerEnter2D?
create a bool field. toggle it from the inspector to draw one or both. use it [bool field] in your code to draw the correct line(s) . . .
like getting the same effect as a gameobject with rigidbody2d and collider2d with a bouncy material atached
but instead I want to replicate this behaviour on script with a trigger collider
I have done this in the past with a OnCollisionEnter2D but I cant seem to figure it out with trigger
bouncing off a wall btw
just use raycasts
how would I mirror them?
when you hit trigger you do reflect
just use VectorX.Reflect . . .
Okay, that would work, but can i get that toggle bool to show up in the gizmo menu to be able to toggle if from there?
how would I find the normal tho
with raycast
@cosmic dagger Thanks!
can I just create the raycast itself when the object gets triggered by the wall or should I call it every frame checking if it is hitting the wall
creating the cast after the 'trigger' may yield unexpected results as the cast could be too small or negative since the collision has already occurred . . .
okay thank you
If you're using physics trigger, you should be able to just create your direction given the difference in position of the two object and find the necessary normal thereafter
problem is, the object itself is a tileset
not sure if it would work
Convert coordinates to the appropriate space 🤷♂️
last I did this was with colliders
and I did something like this
but how would I find the trigger coordinates
I'm assuming you meant collision info etc
I guess so
Whereas this time you're only given info about the collider and have to use some math to obtain the direction yourself
Why building my game's stuck at "Finished" I'm building a game for Android, it's a small game everything else was done in 2 minutes but it's stuck on "Finished" from over 5 minutes...
Doesn't seem related to coding, try #💻┃unity-talk
yup I guess, so first I would need the vector between the object and the collision coordinates right?
collisionCoordinates - transform.position
now what do I do with it
because from what Ive seen I cant even find the collision coordinates with trigger
If you're wanting the normal to some surface, consider raycasting for ease of life on the trigger event
yup thats what I was talking about, so I can know to where the object should actually go
isnt raycast expensive tho?
On collision callbacks provide you a collision info data whereas on trigger callback simply provides you the collider that was involved in the event.
No.
I have a question, It is supposed to be in #💻┃unity-talk but I'm afraid nobody's active there right now, so I want to build the game for iOS, how can I build so my friend can install and play it?
For Android it's simple, you just install the apk and play.
well download ios support, and then switch to build for ios
