My Player Character Have Infinite Jumping + ArgumentException Error
Hello, my character's game don't return to the floor after they has jumping (the jump is do by the character when I touch the screen, iPhone Project).
I have this error in the console too
ArgumentException: Index out of bounds. UnityEngine.Input.GetTouch (Int32 index) (at /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/InputBindings.gen.cs:619) Jump.Update () (at Assets/Jump.cs:20)
Here's my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Jump : MonoBehaviour
{
public bool onGround;
private Rigidbody2D rb;
private void Start()
{
onGround = true;
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (onGround)
{
if (Input.GetTouch(0).phase == TouchPhase.Began)
{
rb.velocity = new Vector3(0f, 0.5f, 0f);
onGround = false;
}
}
}
void OnCollisionEnter(Collider2D other)
{
if(other.gameObject.CompareTag("Ground"))
{
onGround = true;
}
}
}
Can you tell me what to do for this work normally? (my 2 problem) Please, Help me! :)
Answer by korkilo · Aug 18, 2017 at 03:08 AM
Try, private bool onGround;
instead of public bool onGround;
since you can declare its value in the script.
and try putting this code:
void Update() { if (onGround) { if (Input.GetTouch(0).phase == TouchPhase.Began) { rb.velocity = new Vector3(0f, 0.5f, 0f); onGround = false; } } }
In void FixedUpdate () {}
than void update () {}
Why? Because void Update is called before a frame is rendered, void FixedUpdate on the other hand is called before any physics calculation is made.
And Remove private in private void Start()
Not sure if this will help you fix you're problem. Don't worry about making too many mistakes as a beginner, you'll learn out of them eventually.