Character prefab loosing references when spawned. (I know this is normal behavior)

Nortonb

New member
Joined
Nov 24, 2022
Messages
3
Programming Experience
1-3
Hi, I'm creating a 2d runner game where the camera follows the player, i have 3 prefab characters which you choose at the main menu, but when the game starts the camera loses the reference to the player and won't follow. I know this is normal, but I can't figure out how to implement this. any help would be greatly appreciated.



//THIS SCRIPT IS ATTACHED TO MAIN MENU SCENE - CANVAS - CHARACTER SELECTION GRID THAT I CREATED.
----------------------------------------------------------------------------------------------------------

C#:
public class CharacterSelectionUI : MonoBehaviour
{
    public GameObject optionPrefab;
    public Transform prevCharacter;
    public Transform selectedCharacter;

    private void Start()
    {
        foreach (Character c in MenuManager.instance.characters)
        {
            GameObject option = Instantiate(optionPrefab, transform);
            Button button = option.GetComponent<Button>();

            button.onClick.AddListener(() =>
            {
                MenuManager.instance.SetCharacter(c);
                if (selectedCharacter != null)
                {
                    prevCharacter = selectedCharacter;
                }

                selectedCharacter = option.transform;
            });

            Text text = option.GetComponentInChildren<Text>();
            text.text = c.name;

            Image image = option.GetComponentInChildren<Image>();
            image.sprite = c.icon;
        }
    }

    private void Update()
    {
        if(selectedCharacter != null)
        {
            selectedCharacter.localScale = Vector3.Lerp(selectedCharacter.localScale, new
                Vector3(1.2f, 1.2f, 1.2f), Time.deltaTime * 10);
        }


        if (prevCharacter != null)
        {
            prevCharacter.localScale = Vector3.Lerp(prevCharacter.localScale, new
                Vector3(1f, 1f, 1f), Time.deltaTime * 10);
        }
    }
}





//THIS SCRIPT IS ATTACHED TO A EMPTY GAME OBJECT IN PLAY MODE.
-----------------------------------------------------------------------------------------------------------------

C#:
using UnityEngine;

public class PlayerSpawnScript : MonoBehaviour
{
    void Start()
    {
        Instantiate(MenuManager.instance.currentCharacter.prefab, transform.position, Quaternion.identity);
    }
}


//THIS SCRIPT IS ATTACHED TO THE MAIN CAMERA IN PLAY MODE.
----------------------------------------------------------------------------------------------------------------

C#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraScript : MonoBehaviour
{
    public PlayerController thePlayer;
    public Vector3 lastPlayerPosition;
    public float distanceToMove;

    void Start()
    {
        thePlayer = FindObjectOfType<PlayerController>();
        lastPlayerPosition = thePlayer.transform.position;
    }

    void Update()
    {
        distanceToMove = thePlayer.transform.position.x - lastPlayerPosition.x;
        transform.position = new Vector3(transform.position.x + distanceToMove, transform.position.y, transform.position.z);
        lastPlayerPosition = thePlayer.transform.position;
    }
}
 
Last edited by a moderator:
Thank you for posting your code as text (and not as a screenshot). In the future please put your code in code tags (the toolbar icon looks like </>). This will automatically display your code with line numbers, and also preserve any indentation formatting you have. (If I get to my PC later, I might go back and move your code into code tags.)
 
I put your code tags and got rid of the terrible vertical spacing inconsistencies.
 
I don't do Unity, so forgive my naive question. You defined a PlayerSpawnScript, but you are trying to find an object of type PlayerController in your CameraScript. Why?
 
Thanks for your help, the playable character prefabs hold the PlayerController script, the camera takes the players transform and uses that to calculate the distance to move so the camera follows the player.
if I were to drop the character into the game mode scene drag and drop the player into the camera script reference and press play everything works fine the camera follows perfectly. But if i remove the player from the game mode scene and select the character from the main menu and press play, the character will spawn in, and the game starts but the camera won't follow the player.

I'm assuming maybe it's because all 3 characters share the same script, and the camera is using an inactive prefab for the reference. i really don't know.
 
This is the error code - NullReferenceException: Object reference not set to an instance of an object
CameraScript.Start () (at Assets/Scripts/CameraScript.cs:25)
 
You are getting that because FindObjectOfType<PlayerController>() is returning null because it couldn't find an object of type PlayerController.
 
Back
Top Bottom