I am using Unity3D to create a demo. The demo is like this: Use the EasyTouch to control the movement of the gameobject named "Player" —— the plane.
After creating the EasyTouch, I create a C# script like this:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float m_speed = 1;
protected Transform m_transform;
public MovePlayer m_movePlayer;
// Use this for initialization
void Start () {
m_transform = this.transform;
}
// Update is called once per frame
void Update () {
}
void OnEnable(){
Debug.Log ("OnEnable");
EasyJoystick.On_JoystickMoveStart += HandleOn_JoystickMoveStart;
EasyJoystick.On_JoystickMove += HandleOn_JoystickMove;
EasyJoystick.On_JoystickMoveEnd += HandleOn_JoystickMoveEnd;
}
void HandleOn_JoystickMoveStart (MovingJoystick move)
{
}
void HandleOn_JoystickMoveEnd (MovingJoystick move)
{
}
void HandleOn_JoystickMove (MovingJoystick move)
{
Debug.Log ("HandleOn_JoystickMove");
if (m_transform == null) {
m_transform = this.transform;
}
if (move.joystickName != "moveJoystick") {
Debug.Log ("return");
return;
}
float currentPositionX = this.gameObject.GetComponent<Transform> ().position.x;
float currentPositionZ = this.gameObject.GetComponent<Transform> ().position.z;
float joyPositionX = move.joystickAxis.x;
float joyPositionY = move.joystickAxis.y;
Debug.Log ("joyPositionX = " + joyPositionX + " joyPositionY = " + joyPositionY);
float moveh = joyPositionX / 10;
float movev = joyPositionY / 10;
this.m_transform.Translate (new Vector3 (-joyPositionX/10, 0, -joyPositionY/10));
}
}
When I start the game, the code worked fine, and the plane will be control.
Then I create the button by GUI.
When the button was clicked, the code Application.LoadLevel(0) will be called.And the level will restart.
But after I called Application.LoadLevel(0) to restart the game.
The plane will can not be control by the EasyTouch, and the Error message will appear:
MissingReferenceException: The object of type 'Player' 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.
I wonder at why the "Player" will be null.
The "Player" should be init after called Application.LoadLevel(0), doesn't it?