I created a script that allows controller to keep moving where I marked him even if I chose a different controller.
The script works twice then it stops working and gives me back the same error message 500 times per sec:
MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
keepMoving.FixedUpdate () (at Assets/Controller/keepMoving.cs:26)
The script:
using UnityEngine;
using System.Collections;
public class keepMoving : MonoBehaviour {
private Transform standardPos;
private GameObject controllerPosition;
private GameObject playerPosition;
private Vector3 DistanceV;
private float Distance;
private float Movement;
public float MovementSpeed = 10F;
private Quaternion targetRotation;
void Start ()
{
playerPosition = GameObject.Find("PlayerNewPosition");
controllerPosition = new GameObject("controllerPosition");
controllerPosition.transform.position = playerPosition.transform.position;
standardPos = GameObject.Find("controllerPosition").transform;
Destroy(playerPosition);
}
void FixedUpdate()
{
targetRotation = Quaternion.LookRotation(controllerPosition.transform.position - transform.position);
controllerPosition.transform.rotation = targetRotation;
DistanceV = new Vector3(standardPos.position.x - transform.position.x, 0, standardPos.position.z - transform.position.z);
Distance = Mathf.Sqrt(DistanceV.x*DistanceV.x + DistanceV.z*DistanceV.z);
Movement = Time.deltaTime * MovementSpeed;
if (Distance > Movement)
{
transform.Translate(0, 0, Movement);
if (Mathf.Sqrt(DistanceV.x*DistanceV.x + DistanceV.z*DistanceV.z) < 0.01f)
{
Destroy(controllerPosition);
GetComponent<keepMoving>().enabled = false;
}
}
else if (Distance > 0.01f)
{
transform.Translate(0, 0, Distance);
Destroy(controllerPosition);
GetComponent<keepMoving>().enabled = false;
}
else
{
Destroy(controllerPosition);
GetComponent<keepMoving>().enabled = false;
}
}
}
The part where I call the script from the main script (line 9):
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast (ray, out hitInfo))
{
if (hitInfo.transform.tag == "Player")
{
if (PlayerNewPosition != null)
{
MovementExam = false;
GetComponent<keepMoving>().enabled = true;
if (PlayerNewPosition != null)
{
Destroy(PlayerNewPosition);
}
}
MoveWithMouse script = hitInfo.transform.gameObject.GetComponentInChildren<MoveWithMouse>();
if (script)
{
script.enabled = true;
GetComponent<MoveWithMouse>().enabled = false;
}
}