Index out of range on ray declaration
I feel retarded at having to actually post this, but reading through everything and google for hours not helping.
Im just simply trying to make the console type HIT when i touch a rigidbody but its currently also dumping "ArgumentException: Index out of bounds. PlayerController.FixedUpdate () (at Assets/Scripts/PlayerController.cs:25)"
over and over
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour {
public Ray ray;
public float speed;
private Rigidbody rb;
public Boundary boundary;
public float tilt;
void Start ()
{
rb = gameObject.GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
//mobile movement stuff)
ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
if(Input.touchCount < 0)
{
if(Physics.Raycast(ray,Mathf.Infinity))
Debug.Log ("hit");
//old movement stuff
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.velocity = movement * speed;
Vector3 position = new Vector3 (Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
);
rb.position = position;
rb.rotation = Quaternion.Euler (0.0f, 0.0f, (rb.velocity.x * -tilt));
}
}
}
Answer by NoseKills · Mar 01, 2016 at 05:43 AM
You can not raycast from the position of the first touch if you have no touches. GetTouch(0) is null when you don't touch the screen.
ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
And i don't think you can ever have a negative amount of fingers touchig the screen.
if(Input.touchCount < 0)
You should first check the amount of touches and GetTouch only if it's over 0
hahaha so I thought i was just declaring it there but I guess I am initializing it since I am setting it = to the null value
Thank you! Literally just put that as
if(Input.touchCount < 0) {ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position); if(Physics.Raycast(ray,$$anonymous$$athf.Infinity)) Debug.Log ("hit");
and problem solved.