- Home /
Unity2D - Creating multiple Ladders that centers the player?
I am trying to create a ladder that will lock the X axis and center the player. The code I have been working towards, below, accomplishes this... but this doesn't expand to more than one ladder. I can't get the player to center.. it just teleports the player to "Ladder". I understand why, now, but my attempts at altering the script ends in failure :/
I would like to be able to drag and drop my ladder prefab into a scene and have it work with the code. When I try to do FindGameObjectsWithTag.. it doesn't work because apparently it's an array?
I am new to Unity and C#, obviously, but this has been tripping me up for days. I have watched many videos and read many articles.. but I cannot put this together.
Thanks in advance to whomever can assist :) See code below (minus all the extra script)
public GameObject Ladder;
void FixedUpdate() {
Ladder = GameObject.Find("Ladder");
RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, Vector2.up * 2, distance, whatIsLadder);
if (hitInfo.collider != null)
{
if (Input.GetKey(KeyCode.W) || (Input.GetKey(KeyCode.S)) && isGrounded == false)
{
isClimbing = true;
}
}
else
{
isClimbing = false;
}
if (isClimbing == true)
{
r_anim.SetBool("isClimbing", true);
inputVertical = Input.GetAxis("Vertical");
rb.velocity = new Vector2(0, inputVertical * climbSpeed);
rb.gravityScale = 0;
//center on ladder
Vector2 center = new Vector2(Ladder.transform.position.x - .1f, 0);
rb.transform.position = new Vector3(center.x, rb.transform.position.y);
}
else
{
r_anim.SetBool("isClimbing", false);
rb.gravityScale = 10;
}
//if climbing and become grounded, stop climbing
if (isClimbing)
{
if (isGrounded == true)
{
isClimbing = false;
}
}
}
Answer by Captain_Pineapple · Oct 09, 2019 at 11:05 AM
Ooookay
hey there and welcome to the forum,
first off, try to minimize as much code as possible in a fixed update. This is way too much physics unrealted stuff going on there.
Secondly, do NEVER EVER use general find functions like Gameobject.Find or FindObjectOfType in an Update or FixedUpdate. If you take a look at the profiler this is horrible on performance.
Next: Your problem is probably that GameObject.Find("Ladder")
will return A Gameobject with this name. But no specific one. So if there are more than one with this name there will be one ladder that will always be the first. You should get the ladder gameobject from your raycast output.
Something like Ladder = hitInfo.gameobject;
should be your ladder. Then it should work as intended.
In general it can sometimes help to read the Documentation on this. It will point out all the stuff that i mentioned in my post.
Hope this helps, let me know if something was unclear. Happy coding :)