#💻┃code-beginner
1 messages · Page 89 of 1
DiscThrow
Okay where do you tell the code that
Yes
That is not an assignment
damn
Okay where do you tell the code which DiscThrow that variable holds
references are literally just telling the computer where to look for a particular thing .. if you don't its null..
i guess nowhere? I didn't know i needed to do that
how would I tell it which one it is
Then how is it supposed to know which DiscThrow you want
Need to learn about declaration/definition/initialization. Basically, go through C# basics...
A script is a concept. You need to tell it the thing that actually exists. The objec
Edit: sorry, I guess that has been explained already
without actual some basic c# this will just go in one ear and out the other (figuratively ofc)
is this as simple as just doing throwB = FindObjectOfType<DiscThrow>();
DiscThrow will only ever exist on one object so
Yes, but that is the WORST way to do it.
Dragging the object into the inspector would be better if it exists before you click play
put in void start btw
If there's only ever one to exist why not just set the reference directly in the inspector
idk i guess im dumb
so ive replaced "anim.Play" with animator.SetBool()
[SerializeField] public GameObject player;
[SerializeField] private Animator anim;
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject == player)
animator.SetBool("Collision", true);
Debug.Log("Called");
}```
now i get this error
(13,13): error CS0103: The name 'animator' does not exist in the current context
What is animator
the one in "animator.SetBool"
sorry i dont understand what you mean to show me with this. I think i already know about serialising variables
is there something im missing?
Serialized references mean you can drag and drop the object into a box
You seemed confused by that part
What is animator
wdym
yup
i already knew that's what serialising does
there are two
so why did we waste half hour on back n forth
I see zero
This seems like the same idea as what Em is going through. Where do you declare and assign animator?
i mean idk i thought you were explaining something else
honestly im still lost as to what im doing wrong
then you dont know what serializing really is or
That says anim
if you're not getting error highlighted here !ide (follow bot message)
serialising a private variable means i can protect that variable AND have it appear in the inspector, right?
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
No, show where you assign animator
from this; " [SerializeField] private Animator anim;"
Yep
so what am i missing?
Okay, where is animator
That is anim, not animator
yes but WHY do we want it in the inspector
thats the true importance of reason
Just that you should DO that, instead of Find
animator
Show the variable animator
where do you make it
where do you assign it
so that i can assign an object so that the reference is no longer nothing
That... is... anim... not... animator
anim is a completely different word
also Serializing doesn't just apply to private
[SerializeField] is just an attribute that Allows a variable to be serialized
sorry could you remind me what serialising means again
alright well you finally got it so now you should know what to do
buddy
you just said what serializing is
Are there two people using your discord account or what
lol
I think it was sarcasm?
That confused me too
no please im just really stupid
where the animation trees are????
its just a fancy word for putting everything in order
No, the variable animator
that you are trying to use
where did you make it
in unity it exposes stuff in the inspector when its done so
No.
You are literally just using the wrong word.
You wrote ANIM. but you are trying to use ANIMATOR. Those are different words 😂
public Animator anim
Is not
public Animator animator
so serialising just makes it appear in the editor?
In the context of unity , yes
thank god i finally got that right
serializing is done outside of unity as well but nothing you should worry about now
it just puts everything in order so the code can be stored
what about here
if (col.gameObject == player)
animator.SetBool("Collision", true);
Debug.Log("Called");```
That is where you are attempting to use a variable called animator
now
where did you make that variable
I DONT KNOW
then why are you trying to use a variable you haven't made
I TOOK THAT LINE FROM MY OTHER CODE USING BOOLS
Yeah, that is USING it. Which is the error
You made a variable called anim, but you are writing animator in that code
my other code works like this
public CharacterController2D controller;
public Animator animator;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
// Update is called once per frame
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
animator.SetFloat("Speed", Mathf.Abs(horizontalMove));
if (Input.GetButtonDown("Jump"))
{
jump = true;
animator.SetBool("IsJumping", true);```
See the second line?
shit
How it says animator
im sorry
So you see how you have a variable named animator here
and you do not in the other one
oh i just remembered why i didn't assign newBall a value in the ThrowDisc script through the editor. Its because in the ThrowDisc script, newBall is assigned the value of an instantiated object, so I have to leave it empty through the editor because it gets assigned when the ball is actually instantiated.
does that make sense?
{
isReturning = false;
throwReady = false;
newBall = Instantiate(discPrefab, discSpawn.position, cam.transform.localRotation);
ballRB = newBall.GetComponent<Rigidbody>();
ThrowBall(newBall);
}```
no it doesnt
cause ur error was never newBall
newBall has nothing to do with your error
What does newBall have to do with anything
newBall assignment was just the catalyst to the underlying cause
make sure to configure your IDE now cause it shouldve been highlighted from code editor for you
!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
also my project just crashes now whenever i try to make the ball move to the items in the list
recursive spawn i bet
its definitely some kind of infinite error loop or something
what is that
Are you spawning an object that spawns objects that spawns objects...
it should only be spawned once
also another question: do i need to specify an end to a coroutine?
oh you touched something in a coroutine
yeah...
Show code
{
if (Input.GetKey(KeyCode.Mouse1))
{
FireRay();
}
else if (Input.GetKeyUp(KeyCode.Mouse1))
{
foreach (GameObject go in hitList)
{
go.GetComponent<LockedOnVisual>().VisualMarker(false);
}
bailiffActive = true;
StartCoroutine(BailiffMove());
hitList.Clear();
Debug.Log(hitList.Count);
}
}
IEnumerator BailiffMove()
{
throwB.isReturning = false;
throwB.throwReady = false;
throwB.newBall = Instantiate(throwB.discPrefab, throwB.discSpawn.position, throwB.cam.transform.localRotation);
while (bailiffActive)
{
if (Vector3.Distance(throwB.newBall.transform.position, hitList[currentHit].transform.position) < 0.8f)
{
if (currentHit < hitList.Count - 1)
{
currentHit++;
}
else
{
throwB.RetrieveDisc();
break;
}
float t = 10 * Time.deltaTime;
throwB.newBall.transform.position = Vector3.MoveTowards(throwB.newBall.transform.position, hitList[currentHit].transform.position, t);
yield return null;
}
}
}```
No, unless you have a loop
Ah, which you do
so it will just end at yield return null?
goes outside the if statement
in the while loop
cause your code may not ever hit that if statement thus never end the frame
If that condition in BailiffMove isn't met, it'll loop forever
Nothing can change so it can never become true to hit the yield
wait which condition
can i start a timeline as soon as the bool turns true
the one that has yield return null
The distance check in BailiffMove
You can also break the coroutine with yield break; line.
well maybe they wanna execute code after the loop
but i dont understand, shouldn't it be moving if its not close enough?
Where inside the while loop is it moving
isn't this the code from earlier ?
yeah lol, my dumbass is still stuck here
i give u some of this no? note where this is
im sorry could you explain
yield return null waits a frame then continues. It does not stop.
And yeah, you want that outside the if statement
you're using VS so we can't even blame poor brackets lmao
without yield return null the coroutine never finishes the loop
so you're stuck forever there
oh is the yield return null meant to be outside the if statement
while (x)
{
if (y)
{
//yield here if you want. Optional
}
//yield here definitely
}
Yes, absolutely
it tells the while loop that frame has ended, go to the next
Let me put it this way:
You start the while loop.
You check if the distance is less than 0.8
It is not, so you skip to the end of the loop.
You begin another iteration of the loop.
You check if the distance is less than 0.8
It is not, so you skip to the end of the loop.
You begin another iteration of the loop.
You check if the distance is less than 0.8
It is not, so you skip to the end of the loop.
You begin another iteration of the loop.
You check if the distance is less than 0.8
It is not, so you skip to the end of the loop.
You begin another iteration of the loop.
You check if the distance is less than 0.8
It is not, so you skip to the end of the loop.
You begin another iteration of the loop.
You check if the distance is less than 0.8
It is not, so you skip to the end of the loop.
You begin another iteration of the loop.
You check if the distance is less than 0.8
It is not, so you skip to the end of the loop.
You begin another iteration of the loop.
You check if the distance is less than 0.8
It is not, so you skip to the end of the loop.
You begin another iteration of the loop.
You check if the distance is less than 0.8
It is not, so you skip to the end of the loop.
You begin another iteration of the loop.
Haiii Quick question I need to see if something I’m thinking of will work;
Can classes derived from an abstract class be assigned to a variable with the type of the abstract class?
Yep
Just had to make sure idk why I thought I saw something that said it can’t
And if you need to get to that derived class from the parent class, you can do a checked cast:
if (theAbstractVariable is DerivedClassName derivedVariable)
Me when the coding solutions hit me while folding laundry
Ohh thats cool thank you :)
It checks if it's that type, and if it is, assigns it to a variable you can use inside the if statement
Thanks!!
my brain must be full of holes
me trying to learn something like Haskell
Haskell is great
it is just breaks my brain sometimes
https://hastebin.com/share/jeqogomovu.csharp
i cant look on the y, what did i do wrong?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
@rich adder that line gets the currentHit index from hitList, which is first set to 0
dont use Time.deltaTime on mouse
if (Vector3.Distance(throwB.newBall.transform.position, hitList[currentHit].transform.position) < 0.8f)
whats value of currentHit then
clear its more than list contains
that wasnt the problem
I never say it was, but you should still not use it
the value at that moment is 0
ok
where do you do anything with Y
transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
not at the moement, when you try to use in that if statement
but why is there an error?
What is in the hitList?
send new script
everything that is caught in the ray while the player is holding right click
{
throwB.isReturning = false;
throwB.throwReady = false;
throwB.newBall = Instantiate(throwB.discPrefab, throwB.discSpawn.position, throwB.cam.transform.localRotation);
while (bailiffActive)
{
if (Vector3.Distance(throwB.newBall.transform.position, hitList[currentHit].transform.position) < 0.8f)
{
if (currentHit < hitList.Count - 1)
{
currentHit++;
}
else
{
throwB.RetrieveDisc();
break;
}
float t = 10 * Time.deltaTime;
throwB.newBall.transform.position = Vector3.MoveTowards(throwB.newBall.transform.position, hitList[currentHit].transform.position, t);
}
yield return null;
}
}```
i haven't changed anything except for the yield return
show where you do that
{
// MAKE CLASS A SINGLETON
public List<GameObject> hitList = new List<GameObject>();
public DiscThrow throwB;
int currentHit = 0;```
This is an assignment by the way! You assign a new empty list to hitList
private void Update()
{
if (Input.GetKey(KeyCode.Mouse1))
{
FireRay();
}
else if (Input.GetKeyUp(KeyCode.Mouse1))
{
foreach (GameObject go in hitList)
{
go.GetComponent<LockedOnVisual>().VisualMarker(false);
}
bailiffActive = true;
StartCoroutine(BailiffMove());
hitList.Clear();
Debug.Log(hitList.Count);
}
}
void FireRay()
{
RaycastHit hit;
if (Physics.Raycast(rayOut.transform.position, rayOut.transform.forward, out hit, maxDist, hitLayer))
{
if (!hitList.Contains(hit.transform.gameObject))
{
hitList.Add(hit.transform.gameObject);
hit.transform.gameObject.GetComponent<LockedOnVisual>().VisualMarker(true);
}
}
}```
im declaring and assigning in that line right?
yep
okay cool
it's possible for you to NOT put something in hitList, but still run the coroutine and have it check an empty list
goddamit
fun fact when you do publicand [SerializeField] private a list/array Unity already new()
thats what i thought the problem was
still good habit to write it though
if you hit mouse1, it fires a ray, if it hits something that is NOT in the list, it will add it, then you check the list with no guarentee that it actually hit something
just do an if (hitList.length > 0) before checking it
thank you
also i would do that before vector3.distance right?
i watched a brackeys tutorial
just wanna make sure
so i dont know where im using Y
look at your code again
dang it! I still always mix them up and don't know why hahaha.
if you're not using it why would anything rotate on Y ?
idk where i can
im nub
i do it too sometimes
{
if (hitList.Count == 0)
{
if (Vector3.Distance(throwB.newBall.transform.position, hitList[currentHit].transform.position) < 0.8f)
{
if (currentHit < hitList.Count - 1)
{
currentHit++;
}
else
{
throwB.RetrieveDisc();
break;
}
float t = 10 * Time.deltaTime;
throwB.newBall.transform.position = Vector3.MoveTowards(throwB.newBall.transform.position, hitList[currentHit].transform.position, t);
}
yield return null;
}
yield return null;
}```
please tell me i got it right this time
werent u watching a video
follow it again, im sure it works there, just skip the Time.deltaTime
😭
current hit is a value that isn't within range of your list/array
just use what Aethenosity wrote
Since it can't be negative, yeah that should be fine
is there a way for the camera to follow the player without moving its y axis
sorry that was just me being tired
kk i see how i messed up
i promise i at least understand that basic stuff
transform.localRotation = Quaternion.Euler(0f, 0f, 0f); instead of having xRotation, 0f, 0f
okay so now the ball gets instantiated but it doesn't actually move towards the targets
The error was happening because you never hit anything.
You are still not hitting anything, you just make sure that doesn't cause an error
Blend trees I guess?
More of an #🏃┃animation question
it doesn't cause an error anymore
That's what I said
void OnCollisionEnter2D(Collision2D collision) { // Collisions
Debug.Log("Hi");
if (collision.gameObject.CompareTag("bullleft"))
{
Debug.Log("Hi");
Destroy(gameObject);
Destroy(collision.gameObject);
}}
Why does this code not work?
im trying to make an object collide with an object but imnot getting a debug
every time i go to program its like im back to square 0 and know nothing
is it debugging the first hi
You're fine!
The issue is just that you don't hit anything, so there is nothing to move to
nope
does both objects have a collider
Both have a box collider 2d yeah
no wait but i am though, i know for a fact im adding objects to the list
wait I'll send you the full code
How do you know that for sure?
because the objects in the list get a visual marker in the scene, so i know they're in the list
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;
public class GhostMovement : MonoBehaviour
{
public Transform player;
public Transform leftBullet;
public float chaseSpeed = 1.3f;
public float ghostradius = 6.5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Vector2.Distance(transform.position, MovementFunc.MovPos) <= ghostradius)
{
Vector2 direction = MovementFunc.MovPos - transform.position;
direction.Normalize();
Vector2 targetPosition = new Vector2(transform.position.x, transform.position.y) + direction * chaseSpeed * Time.deltaTime;
transform.position = targetPosition;
}
void OnCollisionEnter2D(Collision2D collision) { // Collisions
Debug.Log("Hi");
if (collision.gameObject.CompareTag("bullleft"))
{
Debug.Log("Hi");
Destroy(gameObject);
Destroy(collision.gameObject);
}}
}
}
{
RaycastHit hit;
if (Physics.Raycast(rayOut.transform.position, rayOut.transform.forward, out hit, maxDist, hitLayer))
{
if (!hitList.Contains(hit.transform.gameObject))
{
hitList.Add(hit.transform.gameObject);
hit.transform.gameObject.GetComponent<LockedOnVisual>().VisualMarker(true);
}
}
}``` @summer stump
the collision isnt working at all
the OnCollisionEnter2D method should be outside of update
they're both monobehaviour broadcasts
np
dw you'll spend many hours on dumb issues its just the nature of programming
Ok then. Use some Debug.Logs to figure out where the code gets to in BailiffMove or whatever that was called
wait
i might know the issue
i have a hitList.Clear right after my BailiffMove coroutine. Could that be called before the coroutine is over or no?
It could, yes.
i'll try and remove that for now
holy christ
ah of course
its in the update function
okay next question, so I have a bullet object, and I've assigned a tag to it and there's code that makes it so that whenever it touches an enemy it sends a line of debug, however its not working
- The tag did work on another object (my player character) and the collisions worked perfectly fine
- both objects have a box collider 2D
any ideas?
i had an issue like this once, send your code if you haven't already
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("bullleft"))
{
Debug.Log("Hi");
Destroy(gameObject);
Destroy(collision.gameObject);
}
}
this worked perfectly fine on my player character but didn't work on my bullets
code applies to the enemy btw
the collisions also work I changed my bullet's sprite to my character sprite and my player is getting pushed back
does it log anything
nope
so this is meant to destroy both the bullet and the enemy?
yeah
not sure if the destroying part works but its supposed to debug a line of code thats the part im trying to work out
try just collision.CompareTag
the collision itself is broken the tag is not
ill send a pic of the bullets components and the enemy's 1 sec
ok
the bullet's
is the tag assigned?
just try collision.CompareTag
instead of collision.gameobject
in the if statement
the problem isn't with the tag though
I added another debug line above the tag comparison and it still doesn't work
I added a 2D collider to my player object and gave it the tag and it did work there's just something wrong with my bullet object
make sure it is spelled like this OnCollisionEnter2D(Collision2D)
returns an error
could it be because its not OnColliderEnter2D
it is not
correct me if im wrong but isn't it Collider not Collision
colision
is it collision for 2D and collider for 3D
i named it collision and like i said it didnt work, there's something very strange I wonder if putting it under the player in the hierarchy fixes it though
collider is for triggers
isn't it OnTriggerEnter though?
it is but it is like this OnTriggerEnter2D(Collider2D collider)
that is werid
try to rewrite the oncollsionenter2D code and make sure that it is collision.CompareTag instead of collision.gameObject.ComparTag
the code shouldnt be the problem it detects the player when i added a box collider 2d to it
i probably made a mistake somewhere down the line
📃 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 MY GOD i figured it out
what was it
you need to have a rigidbody2d component as well
that makes sence
yeah lol
if you dont want the player to move though make it static
cool thanks
no problem
how do you completely block out gravity for the rigid body objects btw?
are you making a topdown game
nope a platformer
ohhhh
just turn it off on the component
sorry
no you need it for collsion
turn the rigidbody back to dynamiv and set the gravity scale to 0
One of the two objects needs a rigidbody OR a charactercontroller
You can make it kinematic, but that won't work for OnTriggerEnter
Could set gravity scale to 0
really?
but that shouldn't be an issue for collisions right?
no
you just need a rigidbody
doesnt matter what you do to it
unless its ontriggerenter'
strange
i guess i haven't used 2D that much
i always use 2d
fair enough
It's the same for 3d
oh
does someone know why when the player jumps they can no longer control their horizontal movement
https://gdl.space/iwipifexuq.cs
A basic one here:
https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.3/api/TMPro.TMP_InputField.html
How can I set an input field to that greyed-out, disabled state that means that a user can't edit the input field (the type of state that you see all over the internet)? I can't find it at the above link.
but you can turn off gravity in 3D rigibody and collisions will still work
@boreal tangle You only get horizontal input when grounded
Wrong one 🙂
Grounded = isGrounded();
horiMovement = Input.GetAxisRaw("Horizontal");
You need some sleep
yes
Nah, it just jumped when I clicked reply
Same in 2d
Whats wrong with that part of the code?
thats what i said brah
can you not do .enabled =false ?
You said "but"
You disable horizontal movement. You were wondering why it didn't work.That is why
god im tired
inputfield.enabled = false;
inputfield.interactable = false;```
It's not in the documentation - this is a TMP Input Field, maybe you're thinking of the legacy one?
either of these should work
Ok I'll give them a try.
how is it disabled. Horizontal checks the axis and in fixedupdate it changes velocity in the x direction regardless if the player is jumping or not.
no its because TMP_InputField inherits from Interactable
which is base class for the UI stuff
it isnt
Dang, that formatting got me
oh
Fix that lol
ok
I think I will leave haha. Like three mistakes in a row. Sorry for the confusion
@rich adder
[SerializeField] TMP_InputField secondaryInputField;
private void Start()
{
secondaryInputField.enabled = false;
}
NullReferenceException: Object reference not set to an instance of an object
But I thought that the InputField would be an instance because it's been created in the scene
that means you didn't drag the input field into the slot in the inspector
the script has no idea which TMP_InputField secondaryInputField is
Oh... it was definitely there before as my code uses it, and then I renamed the GameObject. I thought that Serializing fields protected issues with renaming? Oh well, I dragged it back in
yes
can you tell me
look for a moment what this is doing when you jump ```cs
rb.velocity = new Vector2(horiMovement * movementSpeed, rb.velocity.y);
if (toJump)
{
rb.velocity = new Vector2(rb.velocity.x, 5);
toJump = false;
}```
can someone explain me what Mathf.Atan2 is
code runs top to bottom btw
ik
Did you try looking at the docs?
so what happens to your velocity after you press keys mid-air
yep but idk what a radian is
Is it from a script that makes the player look at the mouse perhaps?
I dont see it. toJump should be false and the keys should act as normal
very smart people thought its better to get angles this way
oh
You can just do Vector3 direction = lookPosition - transform.position
Where lookPosition could be camera.ScreenToWorldPoint(Input.mousePosition), for example.
i get it now
Then do transform.right = direction
Or transform.up/.forward depending on your game
the only thing I can think of is that rb.velocity.y would be 5 forever
oh didnt realize toJump was one frame bool, make sure of that.
what do you mean by one frame bool
wait you are saying they can't move horizontal right ?
i made the code work thx
When I press the UpArrow the player jumps. I used the input manger horizontal axis for horizontal movement and when I press the keys for left and right the player does not go left or right.
You're overriding velocity. So if you aren't pressing forward anymore, it'll completely stop relative to the x component.
If you're pressing right and left but it isn't moving, likely your keyboard might be limited.
even if I contiue to press left or right the palyer doesnt move after jumping
Are you pressing more than one key?
no
Log if left and right are being pressed. If hitting new keys disable older input, you may have a case of https://www.quora.com/Why-cant-I-press-more-than-three-buttons-on-my-keyboard-while-playing-a-video-game
ok il check
The referenced script (Unknown) on this Behaviour is missing!
Is there a way to find out where this is happening?
script was renamed/the script was edited in play mode
put it inside of a method
who would've thunk it...
btw are you having two monobehaviour on one script?
in addition to his answer. if you dont want it in a function and need it to be that number by default you would have made the original longer like public int testInt = 1;
Yeah this was just my biggest brainfart ever. I am making a script file with multiple classes in it, which is something I'm not used to doing, so my brain was treating them like they were methods or something, haha
If you didnt know tho, you can reach other scripts from one script without making another class inside it
with just public TheOtherScript something; then in a function youd do something.testFunction();
Yeah, I know about it, thanks.
hey i got a if statement that loops anyone able to assist me?
with what?
i have it so when i press tab and bool is false it opens then bool turns to true
and another else if statement for when its true
but pressing tab loops both and i get 50 logs for each if statement
are you using getKey not getkeydown or up?
show code
ffs
you were right
is there any good books for learning unity code, im getting nothing from watch videos
ups
https://www.w3schools.com/cs/index.php i went threw this to learn the basics
yeah
thats good
keep doing it
There are also resources pinned on this channel.
Catlike coding is good
ill give them a look tysm
hey guys sorry dumb question but im not trolling.
Destroy(gameObject); will destroy the gameObject alright. Destroy(transform.parent.gameObject); will destroy the parent, but what if you have an empty object por example, a child, and a child of that child like. you can also destroy the "grandparent" (name is dumb but not sure what it would be called)
honestly, i read rb whitaker's beginner and intermediate c# tutorials. i was good after that . . .
pretty much grandparents, ect
destroying the GameObject also destroys any children of that GameObject . . .
They are a totally different thing right? and that would mean you need to make another call to destroy it (although, i do not want to destroy it but im just curious as im experimenting with destroying children and parent)
You can chain parents
transform.parent.parent.parent.parent.etc
Oh, did you mean the other direction?
Yeah. I had 3 gameobjects. "FolderItem" "Item" "Trigger" The trigger would be the "grandchild" and had a destroy. but i also wanted to destroy the "Item"
but i was wondering how it would go if i wanted to destroy the "FolderItem" out of curiosity.
It would destroy everything
and what is the name of that in the case.
chopping the root will usually just kill it all
yeah, i was killing it from the smaller thing, not the main parent.
oh yeah you can use tree terminology too if you want ;)
Grandparent is usually what it's called. Or root if there are no parents beyond it
root, leaf, branch
i mean.
i did not wanted to kill the "main thing" just the smaller ones.
this is the chat.
Then just destroy Item
It is a specific message
I cant.
Oh? Why?
The "Item" has a rigidbody and gravity, if i put on "IsTrigger" too it breaks and goes underground. So i had to add a child to the "Item" and give THEM the "IsTrigger"
Do you want to preserve Trigger? You'd have to reparent it
You can have more than one collider on the same object, but yeah, what you did makes sense
wait wait. you can have more than one collider?
that doesn't make sense . . .
Of course
WOW. I did not knew that.
I mean, the way i did it works. And i just needed to add 1 line of code.
You wouldn't be able to differentiate them though. That is why people often stick them on children with their own scripts.
(Like one for sight, one for hearing, etc)
ooohh.
thats cool
thanks for the info man.
!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.
Does anybody see anything in my code that might make me fall through my floor? I keep collision with it like 90% of the time, but certain triggers like jumping too high, or colliding with the sides of objects makes my player fall right through. https://gdl.space/opuxeceril.cpp
Show the rigidbody inspector
For the floor or my character? I tried adding a rigidbody to the plane, but it says that the plane mesh isn't compatible since Unity 5.
The player.
And yeah, you don't want one for the plane
Turn collision detection to continuous
And interpolate to interpolate (instead of none)
That worked! Thanks. I'm still going through the Learn.Unity.com stuff and this is supposed to be my "project." When they explained how to set up a side-scroller none of that was mentioned though. 😅
Also put Move() in FixedUpdate()
Ahh yeah. It is more costly to do those things, but whenever you have collision issues it's a good thing to do
it is more of an issue if moving kinda faster. As you saw it wasn't ALWAYS an issue
Ah, that's a good knowledge. I appreciate it.
Hello I'm trying to make a quest goal script
This is my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class QuestGoal : MonoBehaviour
{
public GoalType goalType;
public int requiredAmount;
public int currentamount;
public bool IsReached()
{
return (currentamount >= requiredAmount);
}
public void GatheredTrash()
{
if (goalType == GoalType.Gathering)
currentamount++;
}
}
public enum GoalType
{
Gathering,
}
i want it to show up like this
It shouldn't be a MonoBehaviour then
thanks
In a 2d game, what's the best object to detect collision but not to bump into other objects? I'm kinda new to collision stuff
I added the goal but I want it so that each time I click plastic the current amount goes up but it isn't
A collider set to isTrigger
Or use a spatial query like raycasting/overlapsphere/checkbox/etc
Ahhh thank you!
Yh, Imma use the isTrigger var, thanks!
Is plastic a button? If yes, Did you subscribe to the OnClick callback? If yes, Do you have an EventSystem in the scene?
yes its a button
Yeah
i have an event system
but I don't think i subcribed to the callback
can you teach me how?
Show the buttons inspector
So you subscribed to five things there
Mhm
Which object has the script with this code?
is this what I'm supposed to do?
Yep!
Thanks
If picktrashup is what you want of course haha
wait
Nevermind
I want the current amount to go up by 1
I need to add this after the onclick function right?
OH nevermind it works now
i have a list of strings and i was wondering if i wanted to find out what string was placed 1st or 2nd item of the list how woudl i do that
myList[0] to get the first item, myList[1] for second?
oh i see
not sure I fully understood though. Is that what you wanted?
well im trying to have a for loop that checks all items and then summons a prefab for each so i could use mylist[i] to find what each thing has
i think that woudl work maybe
That would be the way to do it, yes
Anyone know why my OnTriggerStay() method isn't being called? These are the two objects' colliders that aren't calling it https://prnt.sc/65lJZag13Umi https://prnt.sc/N4iVJwkHPA1J
https://hastebin.com/share/unuxesajen.csharp hi im making a tower defense game and this script is in the tower. i need help because whenever i place a tower (or multiple it doesnt matter) after a while the tower will just stop doing damage to the enemy. it still has the enemies that it is attacking in the list of enemies in range, but it doesnt attack it. there are no errors so i dont know whats wrong
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hey can anyone help me with the problem that to switch a camera with right click ... The code worked but in game view it's saying no camera found but all things are attached to the script
using UnityEngine;
public class CameraSwitch : MonoBehaviour
{
public Camera mainCamera;
public Camera secondaryCamera;
void Start()
{
// Ensure only the main camera is active initially
mainCamera.enabled = true;
secondaryCamera.enabled = false;
}
void Update()
{
// Check for right mouse button press
if (Input.GetMouseButtonDown(1)) // 1 represents the right mouse button
{
// Switch between cameras
mainCamera.enabled = !mainCamera.enabled;
secondaryCamera.enabled = !secondaryCamera.enabled;
}
}
}
code not working its saying that display 1 no camera found
you should consider using cinemachine
Now I have given the comments also
So that's u all can understand
And pls help me
For cam switch?
so i tried to use tags to identify each item then make it equal to a certain object but it wont work. so how would i make the gameobject change to what item it has to be so i can instansiate it
yes. for all of your camera needs
Is there anything wrong with the code?
i have 1 single camera in my scene, but i can switch the view by simply enabling/disabling different virtual cameras and cinemachine does the hard part of transitioning between them for me
you cannot store an array of GameObjects in a GameObject variable
The type on that line is wrong, as boxfriend said
But how?
by using cinemachine and enabling/disabling different vcams
Can you please provide me the code
When you disable one and enable another, it moves the camera for you. That's how cinemachine works
ya im trying to find what item has the same tag as an item name on the list then instantiate it. so if how i wrote it dont work how would i go about that
This works by changing priorities, but here:
https://michaellandonhatfield.medium.com/switching-between-virtual-cameras-in-unity-cinemachine-4fe7ab16d249
GameObject[] is how you write an array of GameObjects
oh should so i shouldnt use a list of strings
So is it good for switching between my nirmala fps cam and sniper gun cam? And do I also need to change the normal fps cam to cinemachime
ican just make a list of gameobjects straight away i see
Well... I guess? Are the strings different?
Do you have multiple objects with each tag?
no not really i wanted to connect all of them to a gameobject
na
all have there own tags
Then yeah, I guess not.
But I recommend avoiding using Find at all honestly
oh really is it laggy or something
@summer stump
It is costly yes, but also error prone. The tag version is better though
Is what good? Cinemachine? Yes, that's what it's made for.
should i make a reference to all of the prefabs in my script and acess them there then
Thanks sir
https://hastebin.com/share/unuxesajen.csharp hi im making a tower defense game and this script is in the tower. i need help because whenever i place a tower (or multiple it doesnt matter) after a while the tower will just stop doing damage to the enemy. it still has the enemies that it is attacking in the list of enemies in range, but it doesnt attack it. there are no errors so i dont know whats wrong
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yeah, that would be better for sure.
Find won't find prefabs anyways. A prefab is an asset, it doesn't exist in the scene. It only finds gameobjects which have been instantiated or placed (which is just instantiating too) in the scene
oh i didnt even know that tags couldnt do that thank you for the help
Still stuck on this with colliders
Show the code
Literally https://prnt.sc/SHZtW6luIzaD
Ok, which object is it on?
Also, your !IDE is not configured
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 first tried the one with the rigid body, then tried it with the trigger. Which should it be?
Either. The physics message is sent to both
Just making sure it was on one of those two and not a child or something
Go through this:
https://unity.huh.how/physics-messages
Ooh thanks a lot, this worked
What fixed it was using OnTriggerEnter2D. I'm assuming it assumes 3D?
OnTriggerEnter IS 3D
not just an assumption
It is a little confusing that there are the two alternatives but only one is named. It's the same with multiple things like colliders and rigidbodies and whatnot
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour
{
public GameObject Camera1;
public GameObject Camera2;
public GameObject Camera3;
void Update()
{
if (Input.GetKeyDown("1"))
{
CameraOne ();
}
if (Input.GetKeyDown("2"))
{
CameraTwo ();
}
if (Input.GetKeyDown("3"))
{
CameraThree ();
}
}
void CameraOne()
{
Camera1.SetActive(true);
Camera2.SetActive(false);
Camera3.SetActive(false);
}
void CameraTwo()
{
Camera3.SetActive(false);
Camera2.SetActive(true);
Camera1.SetActive(false);
}
void CameraThree()
{
Camera3.SetActive(true);
Camera2.SetActive(false);
Camera1.SetActive(false);
}
}
Will this code work?
I don't see the issue, but I have a few questions:
In your coroutine, why have the while loop? You always yield break on the first iteration.
What is TowerHover?
Why set the local scale to rangeSize instead of the radius of the collider or something?
Why is RangeDetectionAndDamage updating the enemy health?
And lastly, have you tried using the debugger or adding debug.logs?
Also, seems like you do an early return in update if EnemyStats is null. That may be the issue. Naaah, the physics message would still get new ones. So that isnt it
-
good question
-
it is the script that makes it so when you click the gui of the tower you can "hover" it and place it where you want
-
i didnt know how to set the size of the range
-
because im updating the health of the current enemy its attacking which is losing health
-
a little bit i definitely should more lol
using UnityEngine;
public class CameraScript : MonoBehaviour
{
public GameObject Camera1;
public GameObject Camera2;
void Start()
{
Camera1.SetActive(true);
Camera2.SetActive(false);
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
SwitchCameras();
}
}
void SwitchCameras()
{
if (Camera1.activeSelf)
{
Camera1.SetActive(false);
Camera2.SetActive(true);
}
else
{
Camera2.SetActive(false);
Camera1.SetActive(true);
}
}
}
Guys pls say will this code work or not
-
EnemyStats should have its own TakeDamage(float damage) method and update its own health probably. Separation of concerns can be very helpful.
-
I would throw a debug in there to check the isDead value of the enemy to see if that's part of the issue
Why can't you just try it? You will know if it works or not by just trying
I'm in my mobile rn
yea thats definitely a better idea ill try. thanks
Ah, then just wait till you're on your computer
is TowerHover ever destroyed? TowerHover.isPlaced is a condition in OnTriggerStay, if that becomes false, you cannot attack
no its in the tower so it is just there
hi how do I make a text popup after completing a quest?
Ok, hmm. I'm not sure then
Are the enemies dying? Is the tower ATTACKING, just not doing damage?
myText.enabled = true;
like this?
sure. if completed is some text or ui that you want to be enabled
Yeah
the enemies that the tower kills get disabled. i dont believe its attacking because in my script i also make the tower face the enemy it is currently attacking which it is not
So, you can go that way, with ui elements there but disabled, then enable them at the right time. Or you can go another route where you Instantiate a ui element at the right time.
It depends. I usually do a combination.
For example, I have a panel that would pop up, and I would write custom text in it, and maybe create some icons
instantiate would be better right?
because everytime you complete the popup comes up
Ahhhh, if they are disabled... then maybe it is trying to continue attacking that enemy?
Maybe make a public target variable and keep an eye on the inspector to see if it still has the old one
If every time you complete a quest the popup comes up, then instantiate would be worse. Creating a whole new object each time when you can just modify the text is worse imo
when it dies it is removed from the list
Oh
i think im gonna try doing what you said of handling the damage in the actual enemy maybe that will fix it
Ok, I just think it would be worth it to verify that. I see that you check an isDead value, but I dunno.
Other than that, I'm not sure at all. Sorry
alr ill try thx for the help\
i just got rid of the while loop and yield break and it works perfectly lol! thx so much if you didnt mention the loop being there for no reason i wouldve never thought of it
Really!? That is weird! I just thought it was interesting, I didn't think that was the problem haha
Well, glad you got it!
Ohhhhh. I bet I know the issue
You called break early on some condition (can't remember)
It must have broken there, and then never got to the part where you set the bool false again, and this could not start another attack
error CS0103: The name 'Completed' does not exist in the current context
how do I fix this
boolean?
Well Completed is simply not a thing
So you have to make it
Did you make a variable called Completed you are expecting to use? It may be local or something, or you forgot to make it
i don't know which one to make
I want it to popup after finishing the quest
Well, I don't either haha
😔 👊
The like a TMP_Text or a GameObject or a Canvas or something
Depends on what you want
yes tmp_text
so I added this
public void CompleteQuest()
{
Completed.SetActive(true);
}
in the complete quest script
how do I make it popup after the quest tho it has an animation
I cannot get my bullets to damage my enemies. Unity 2D project.
public class Projectile : MonoBehaviour
{
public int Damage;
public float Speed;
public Rigidbody2D rb;
public SpriteRenderer spriteRenderer;
public void SetProperties(int damage, float speed, Vector3 direction, Sprite skin)
{
this.Damage = damage;
this.Speed = speed;
spriteRenderer.sprite = skin;
rb.velocity = direction * speed;
}
public void SetLayer(int layer)
{
gameObject.layer = layer;
}
private void OnTriggerEnter2D(Collider2D hitInfo)
{
if (hitInfo.gameObject.CompareTag("Enemy"))
{
IDamage damageable = hitInfo.GetComponent<IDamage>();
if (damageable != null)
{
damageable.takeDamage(Damage);
}
Destroy(gameObject);
}
}```
also consider using TryGetComponent instead of GetComponent immediately followed by a null check, TryGetComponent does both all in one line and also has the added benefit of not allocating garbage when a component isn't found in the editor
Do the bullets get destroyed?
if there isn't any other code that destroys them, then the issue is that the objects they are hitting have the right tag but do not have an IDamage component
public class EnemyAI : MonoBehaviour
{
[Header("--------EnemyStats-------")]
public float Speed;
public int Health;
[Header("-------Components-------")]
public AudioSource EmoteSource, WeaponSource;
private Transform playerTransform;
// Start is called before the first frame update
void Start()
{
GameObject player = GameObject.FindGameObjectWithTag("Player");
if(player != null)
{
playerTransform = player.transform;
}
}
// Update is called once per frame
void Update()
{
if (playerTransform != null)
{
MoveTowardsPlayer();
}
}
void MoveTowardsPlayer()
{
// Move towards the player's position
transform.position = Vector2.MoveTowards(transform.position, playerTransform.position, Speed * Time.deltaTime);
}
public void TakeDamage(int damageAmount)
{
Health -= damageAmount;
if (Health <= 0)
{
Destroy(gameObject);
}
}
}```
this does not implement IDamage
ahh
Debug.Log($"{name} hit {hitInfo.name}", hitInfo);```
Thank's guys.
are you planning on reloading the scene when the player dies, if not i would just disable the game object instead of destroying it
oh AI class
i would still disable
if your gonna be respawning them
Hey guys newbie here with 0 scripting experience so I copied one online to make my lights flicker. Only have a single error and was wondering how I could fix it. here is the script and the error:
its not in a class
please do not use notepad to code. use a real !IDE like visual studio and get it configured 👇
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
yessir
Yeah i would get a IDE, also its not working because its not in a class
I don't know what that means haha
also post code in !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.
Integrated Development Environment
It does a LOT to help you code
he meant he doesnt know what a class is i presume
Ah, makes sense haha
notepad code 👑
paint is better
Should loosely explain what a class is for you
no shot you've ever seen paint code
Microsoft Word maybe
Indeed i have and it was legendary
took 3 hours to get hello world to work
no shot
and dont forgot the all good google docs
the custom highlighting and stuff is endless
don't mean to be bothersome but how do I put in a class
there are beginner c# courses pinned in this channel. you should start there. then do the junior programmer pathway on the unity !learn site
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
using unityengine;
public class Something : Monobehaviour
{
"everything else in here"
}
pretty much that
i thought my paint shtick was pretty neat
thank you so much 🙏
You may get an error if the name doesn't match the file right
indeed file name must match class name
you can have multiple classes in a script but no need to dive into that right now
networkbehaviours 🥲
depends on the unity version
Does different unity versions function different when it comes to naming in classes?
I didn't know that
2022 and newer do not require them to match
REALLY??
still can only have a single MonoBehaviour in a file that will actually be able to be added via the add component menu. that requirement also only ever affected adding a component in the editor
damn near dood
fix your compile errors
we've been over this already
again, get your IDE configured. nobody here wants to be RoachyVr's Personal Spell Checker™️
well good luck. i won't be helping you any further since you don't want to get visual studio configured. and considering #854851968446365696 specifically says "[Don't] Give answers to users without an IDE configured*.⠀🠖 Get them to configure it first." you probably won't be getting help from any other regulars until you do so 🤷♂️
you've been given the guide and were instructed on what to try after completing the guide. if you're still having trouble with some part of that then you need to fucking say what it is.
i don't enjoy fishing, so i'm not going to go fishing to find out what you're having trouble with
so you don't know which part of the configuration guide you are stuck on? then how the fuck is anyone else supposed to know?
Anyway to Generate 3D Perlin Noise without going to github? I'm kinda supprised Mathf doesn't have a method for 3D perlin noise.
afaik there is not a built in way. there seem to be plenty of guides for implementing it yourself though
a powerful website for storing and sharing text and code snippets. completely free and open source.
I need help, it never calls Sprint()
it prints nothing in console
and trust me I am in play mode
are you sure you have an active instance of that component in the scene?
yeah ive been editing it and getting output
but this one line wont output for some reason
there are only a couple reasons that Sprint would never be called, either you haven't saved your code, the component or its gameobject is not active, or you are receiving an error. your console does not appear to have any errors though so it's gonna be one of the first two
so I put a print statement above the function
and it did work
i deleted the print statement and now it works
but it still won't execute the code inside the function even though I am pressing left shift
also i closed and reopened the project and the gameobject was active idk why
you're calling it every frame. so for one frame it uses the sprintMultiplier and the next frame it will not
ooooh
GetKeyDown is only true the first frame you press a key
I see ty!
!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.
void OnCollisionEnter(Collision2D collision)
{
//Check if player
if (collision.gameObject.CompareTag("Player"))
{
//delete myself
Debug.Log("Player Detected");
Destroy(gameObject);
}
}
this code looks right, but for some reason this is never called. I feel that im missing something obvious in my game but I don't know what. Both the player and the enemy have a box collider 2D
You're probably wanting the 2d variant
Hi ! I'm looking for a way to call a function when the user press and hold 2 input for 2s.
I've found the "hold" system in the input action manager but i can't find a way to tell unity "Do this function when both of theses input action are triggered"
thank's !
is this not the 2d variant?
no, see the link i posted
If I put a line of code with some calculations in Update, it should reach FixedUpdate fine right?
if I put like
totalMaxVel = playerMaxVelocity + sprintVal;
in update, fixedUpdate will receive that value by the time it gets to it right?
as long as totalMaxVel is a class-level variable or property then it will be accessible in FixedUpdate. just keep in mind that on frames where FixedUpdate runs it happens before Update so you'd get last frame's result of that math, but for most things (like this) that shouldn't be a problem
would it be better practice to just calculate this in fixedupdate too or should I just keep it in update?
if the only place you need the value is FixedUpdate then it can just be a local variable in FixedUpdate instead of a field
I think I found a better way to do this whole thing anyways but will keep in mind while I keep writing ty
i'm getting this error
FixedUpdate runs before update
a powerful website for storing and sharing text and code snippets. completely free and open source.
If it runs at that frame at all
I'm super confused cus I don't see sprintVal at all
Never seen that myself. Did you google it first?
i think HotReload might be messing up my Unity or something's wrong with my editor orrr im missing something and im stupid
i thought MissingException was super vague and a common exception so i assumed it'd yield nothing
yeah that's 100% caused by hot reload not actually reloading the code
Ah. I have heard that HotReload can cause problems
ironically i don't know how to disable it or fix it
exit play mode, make a change and save your code so unity recompiles it, then you should be able to use it just fine.
if for some reason that does not work, restart the editor
I just restarted the editor but same issue
ill do it again though since i dont see the hot reload ui
oh yeah hot reload has a recompile button in case of stuff like this
ya works now ty!
is using physics.raycast downward every frame bad for performance
should I find a better way
i'm trying to smartanimate a foot to know when its touching the ground
no, but you should use the profiler if you have performance concerns so you can address what is actually impacting performance
oh how do I get that?
How do I solve this Gradle Build Failed to make an android build? My project version is 2021.1.19f1
public abstract class ScriptableSingleton<T> : ScriptableObject where T : ScriptableObject
{
public static T Instance { get; protected set; }
public abstract void SetInstance();
}
I would like SetInstance() to not be abstract but I can't find a way to do the usual Instance = this in the abstract class that gets inherited. (for a wild guess I tried Instance = T but that doesn't work) is there a way to do it or do I have to have SetInstance() be abstract and have the scriptable object inheriting this override it?
Instance = (T)this;
ah thanks
Can someone explain the logic behind creating a staic instance? We create a static copy of the same class inside the class? Why cant we just make the class static?
it's part of the Singleton pattern
https://refactoring.guru/design-patterns/singleton
uhhh, that doesn't work
ah right, you want to constrain to ScriptableSingleton<T> not just ScriptableObject
for example, here is my singleton monobehavior implementation: https://github.com/boxfriend/Utils/blob/master/com.boxfriend.utils/Runtime/Utils/SingletonBehaviour.cs
oooh the where : ScriptableObject is wrong
thanks :D
I can't believe this actually works xD
i feel like a singleton SO is a bit cursed though. wouldn't a serialized reference to an SO asset not be a better option?
it would probably be better, I'm just learning stuff
also unless you are creating the instance at runtime, isn't there the possibility that the SO asset won't even be included in a build if you aren't referencing it by anything else that is included in it?
it is not a copy of the same class, it is simple a reference to the current single instance of the class. Think of how you reference a GameObject or a Transform. By having either as a field, you are not creating a copy, you are just referencing the existing one
I'm calling SetInstance from a script so something has a reference to it. it's mostly for me to create libraries of classes in scriptable objects, like a list of CharacterData in which I can look up an npc's ID and get their information. I'm sure there's a better way to do it but I enjoy having a scriptable object for this and didn't want to create a reference to the scriptable object whenever I want to get some data from it
Hi guys why does it say this ?
when I open it shows it
oh wait i think i found somethin
This is the issue I got an error
FindObjectOfType<GameSession>().ResetGame();
on this
Guys I planned to launch sniper scope function in later update in my game
I'm trying to get started on the jump part of my PlayerController script but my Public isGrounded value isn't showing true when my player is on the ground. ( already tagged as ground.) Did I mess up on my script? It's my first time using ||. https://gdl.space/icuxafusaw.cs
It is usually best to debug.log the values you expect or attach a debugger and step through your code to see what is happening. Code seems fine ish to me.
OnCollisionEnter is a 3D method but this seems to be 2D. You need to use OnCollisionEnter2D instead
Oh snap, okay. Thank you.
What a G, that fixed it
yo yo guys sorry if this is like NOVICE and im butting in but euler and quaternion angles scare me... im trying to flip an object by making the y scale -1 when the object (which always rotates to follow the players cursor) surpasses the y axis into the 2nd and 3rd quadrants of the unit circle.
y scale is -1 between 90 and 270, and y scale is 1 all else
https://gdl.space/jogayiviku.cpp
the program however only registers between 0-90 as 1 and all else is -1, its probably a really simple fix but i cant figure it out for the life of me guys 😭
-90 angle could be represented as 270, which is why your if-statement probably fails
You could put zRotation into a -180...180 range with this: cs zRotation = Mathf.DeltaAngle(0, zRotation);
would i put that just below
float zRotation = rb.transform.localRotation.eulerAngles.z;
Yep
Next time, try to debug your values. You could do Debug.Log("Z rotation: " + zRotation) and you would notice that it never went into the negatives
i DEFINETELY should have done that
im not quite sure why i didnt as ive done that before like wth
i think i was over relying on the values the unity editor gave me
trying to make connections between the values during runtime and out
either way though im a silly clown 🤡
alrighty hol on so by my understanding THIS is to read the local rotation value of the object in the -180...180 range, rather than the 0...360 range unity usually uses despite what the editor says is that correct?
DeltaAngle finds the shortest angle from a to b
When the first parameter is 0, it effectively just clamps it to -180..180
@real dome no off-topic media, please
I don't think the inspector values always match the localEulerAngles (or localRotation.eulerAngles in this case, which is the same)
But yeah sounds like you got it right
OK i think ive got it
again thanks so much for helping me out and having the patience to explain it does make sense now
The thing is that multiple different euler angles can be used to represent the same rotation
No problem
@real dome That yeah, but there are worse examples where you switch up every axis and the rotation is the same
i think ill stick to single axis rotation for now
i reckon thats a problem for future me to tackle
Yeah you are in 2D so you don't need to worry about this that much
Okay I got one example, (90, 0, 0) is the same as (90, 90, 90) 😵💫
Why did I ever leave unity2D...
Wait uhhhhhh
Consider that I'm in a 3d environment
If I decided to add or subtract 180 to the x rotation for a smoother transition instead of y scale -1
Would there be collateral y rotation movement?
Don't think so, you can always try it out
The best way is to keep your angles in variables, instead of just storing in/reading from euler angles
Unity is gaslighting me. Is there anything wrong with my script? My player won't jump, but the bool for isGrounded still gets tripped to false, and I see my debug message. https://gdl.space/wupirazocu.cs
You are overriding any previous velocity here: playerRb.velocity = (Vector2.right * horizontalInput * speed);
You can solve it by keeping the current Y velocity:cs playerRb.velocity = new Vector2(horizontalInput * speed, playerRb.velocity.y)
UGH. That makes so much more sense, considering I would have needed to change direction midair too. You're a lifesaver. I am STRUGGLING over here lol.
Also make sure that this doesn't get called multiple times:cs Physics.gravity *= gravityModifier;
For example, if you load a new scene with a new player object
Gravity would keep being multiplied everytime
Oh, also use Physics2D.gravity or it won't effect your 2D objects
Well, I'm not too worried about that. This is a one scene demo, and it's just supposed to be for the learn.unity lab. Also, using that new line of code says rb does not exist in this context (CS0103) I tried changing the rb to my playerRb.velocity instead and that said that it can't use my horizontalInput as a modifier with Vector2 because it's a float var.
Yeah, it should be playerRb not rb, I'm just used to typing rb
Not sure about the second error/issue tho...
Oh.
playerRb.velocity.y
Yep, I edited
Ahhhh. Okay. Well, I didn't get any errors, but the issue persists. No jump.
This might not fix the issue, but call HorizontalMovement() from FixedUpdate instead of Update
FixedUpdate is where you should do physics related stuff
Huh. Well that didn't fix it, and now my cube is floating above the ground, rather than dropping to it.
Send updated code
hey guys i need help with making a character sit on a chair, i already have the sitting animation i just need help making the character sit exactly on the chair.
You can modify animated transforms in LateUpdate
You changed the wrong thing
what does that mean 😅
The playerRb.velocity.y stuff is for HorizontalMovement
Revert back and do that
Move the player to the chair.
Using transform.position and transform.rotation on either the root bone or the root transform
OHHHHHHHHHHHHHHHHHHH. So, I wasn't able to call playerRb.velocity for my jump, because I forgot to make the horizontalInput a NEW vector. Gotcha, gotcha.
and how do i make the characters sitting position exactly the height of the chair
Not really what I'm saying
You can make a object as a child of the chair. Get a reference to that object's transform when sitting, and use that transform's position and rotation for the player when sitting.
Revert to this code, call HorizontalMovement from FixedUpdate, and change this line:```cs
playerRb.velocity = (Vector2.right * horizontalInput * speed);
```cs
playerRb.velocity = new Vector2(horizontalInput * speed, playerRb.velocity.y)```
That should be all
I don't know if I'm reciprocating that I understand right. Basically by using //playerRb.velocity in my HorizonalMovement() method, and not listing a new Vector2, it was causing problems with my Vector2 in my jump code.
thank you
Yeah, that's what I did. Still fixing the code to add HorizontalMovement to FixedUpdate and I'll give it a shot
WHEW. Problem solved lol. My lil buddy is jumping now. I appreciate your help.
hao can i Debug.log in unity dots?
in dots code, it seems "'Debug' does not contain a definition for 'Log'"
Try UnityEngine.Debug.Log();
i want the marked Instanciate code to only activate on a 70% probability, how do i do that?
if (Random.Range(0f, 1f) < 0.7f)
Alternatively, Random.value
in this case you can just use Random.value instead of Random.Range
thx
Why do I get transform child out of bonds error
Even when I want to execute this function when the transform child isnt null
Because one of the GetChild calls is trying to get a child that doesn't exist
Better to use serialized references instead of relying on stuff like hierarchy or naming
@verbal dome can u give me a normal answear instead of just sending me a link?
Like what should I change?
Its like u would ask your partner how do you look and he/she would send you a link to a fashion tutorial :/
Use fields with [SerializeReference] and assign them by dragging them in the inspector
I cant assign them in inspector because I reffere to a one of the clients not a single player AND col.transform.childCount > 0 is a better answear than sending a link
i wanna see in realtime how a float value changes, can i simply do "Debug.log(floatparameter)" and display that in the console? or would that not work
U would know that if u would just check my code that I HAVE to refere diffrent way than using inspector if u would just open this link
that I send you
If u want to actually help ppl than try to help them instead of sending a link :/
I don't see a single serialized reference in that script.
Why are you acting so entitled?
Because I cant seralize reference
How does the script tell me that?
Anyway, maybe someone else will help you. I don't deal with entitled kids
Mate I just dont get why ppl here are sending links to documentations or tutorials or other websited that have SO MUCH text to read when answear is just a simple line of code
Welcome to programming. Get used to reading.
Yeah. Maybe someone else will help beacuse u are so grown up that u dont undestand a simple kid's question :/
I get used to beacuse there is not much ppl that actually want to help instead of showing their ego
col.transform.childCount > 0
That was the answear mate
the 'simple' line of code you are missing is Debug.Log. You are doing lots of stuff there which we can know nothing about and yet you are checking nothing worthwhile
The lots of stuff is if (weaponHolder.GetChild(0).gameObject != null)
{
GameObject weapon = weaponHolder.GetChild(0).gameObject;
Destroy(weapon);
}
Doesn't help that you immediately start whining when I point you to learning resources
If its lots of stuff that u dont know nothing about that good luck for you
Yeah. Like i would ask for teaching me resources
"Dad, why grass is green?"
- "Here child, you have a thick book about genetics"
No, the lots of stuff is
Transform player = client.PlayerObject.transform;
Transform holder = player.GetChild(1).GetChild(1);
Transform weaponHolder = holder.GetChild(0);
Transform structureHolder = holder.GetChild(1);
Transform spellHolder = holder.GetChild(2);
Transform potionHolder = holder.GetChild(3);
and as we know nothing about your hierarchy we and you cannot know what those result in
"Dad, but I asked just simple question"
"Stop whining kid"
No the stuff that I ask is
if (weaponHolder.GetChild(0).gameObject != null)
{
GameObject weapon = weaponHolder.GetChild(0).gameObject;
Destroy(weapon);
}
And exacly this if (weaponHolder.GetChild(0).gameObject != null)
See?
Simple line of code
Why I have if isnt null but I still get error when gameobject is null
That was my question
And if u want really to argue about that
One of ppl answeared me
With simple answear
That u big brains couldnt do
Your issue is fixed(?), you can stop now
im encountering something i dont understand, its an enemy patrol script and its supposed to move the enemy between two points, but right now, when my enemy arrives at a point, it stops forever and i dont quite understand why
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Changing >= to > and <= to < might do the trick
Do you know what that line of code means or did you just discover the magic incantation to make errors go away?
What have you learned that might prevent you from having to ask another question in the future?
That using if != null still refere to something that should exist so thats why I got an error wich was my qestion
sadly no
Put a log in DirectionChange and see how it prints
Oh wait. cs if(enemy.position.x >= rightEdge.position.x)
I think this should be <=
You have >= in both