I am building a clone of Doodle Jump in Unity to teach myself the basics and have come across a problem. The flow of this game goes:
Main menu ---(click start)--> Level select ---(click level)--> Selected level
The player controlled object is actually created in the main menu screen. It is controllable right from the very beginning with GameObject.DontDestroyOnLoad() stopping it from being destroyed throughout each scene transition. Once you get into your selected level, there is a script attached to the camera to get it to move with your character.
I have some code in the LateUpdate method which handles the camera movement:
void LateUpdate () {
if (gameObject.transform.position.y > transform.position.y) {
Vector3 newPosition = new Vector3(transform.position.x, gameObject.transform.position.y, transform.position.z);
transform.position = Vector3.SmoothDamp(transform.position, newPosition, ref currentVelocity, smoothSpeed * Time.deltaTime);
}
}
but for this to work correctly, I need to be able to reference the the player (gameObject in the code above). I was originally doing this by using
GameObject gameObject = GameObject.Find("Doodler");
in the same LateUpdate method, but there is no reason for me to find the Doodler every frame as it should not be replaced until you hit game over. For this reason, I moved the GameObject.Find line into the Start method, but it doesn't seem to be finding the Doodler and as a result, the camera doesn't move. Can anybody help with this?
EDIT:
I've now changed my Start method to be like this:
private GameObject gameObject;
void Start() {
gameObject = GameObject.Find("Doodler");
Debug.Log("START Found the Doodler: " + gameObject.GetInstanceID());
}
rather than this:
void Start() {
GameObject gameObject = GameObject.Find("Doodler");
Debug.Log("START Found the Doodler: " + gameObject.GetInstanceID());
}
and this seems to be working. I'm guessing the second method means gameObject is not accessible to LateUpdate?
Final Solution:
Whilst the code in the edit does work, it gives a warning because I called my GameObject gameObject and this is a predefined object referring to the object the script is attached to. The final code should look like this:
private GameObject doodler;
void Start() {
doodler = GameObject.Find("Doodler");
Debug.Log("START Found the Doodler: " + doodler.GetInstanceID());
}
GameObject.Find
can't find it. If it is not in the scene yet,GameObject.Find
can't find it too. Which one is it? – Programmer