Home > Net >  How can I set parameter's value for player clone in unity?
How can I set parameter's value for player clone in unity?

Time:06-05

I made a transfer code, if player clone touched the door, player will transfer to another room. But it doesn't work. I think 'currentMapName' is only set in player object, not clone object. So I want to know how can I set parameter of clone object. Thanks for anything your helps.


the error code

enter image description here


transfom source code

public string  transferMapName; // map name for transform

private PlayerScript thePlayer;

// Start is called before the first frame update
void Start()
{
    thePlayer = FindObjectOfType<PlayerScript>(); // player objects.
}

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.name == "Player(Clone)")
    {
        Debug.Log("Hit door");
        thePlayer.currentMapName = transferMapName;
        Debug.Log(thePlayer.currentMapName);
        SceneManager.LoadScene(transferMapName);
    }
}

and clone parameter that I want set value

enter image description here

CodePudding user response:

Change the condition to having a player script.


var playerScript = collision.gameObject.GetComponent<PlayerScript>();

if (playerScript)
{
    playerScript.currentMapName = transferMapName; // for e.g
}

CodePudding user response:

I suspect, that your thePlayer object is null, as the NullReference appears after "Hit door" log. I guess you spawn/clone the player after Start() has run. So, easy ways to fix that:

Option A:

private void OnTriggerEnter2D(Collider2D collision)
{
    
    if (collision.gameObject.name == "Player(Clone)")
    {
        if(thePlayer == null)
        {
            thePlayer  = FindObjectOfType<PlayerScript>(); // careful if you have more than one Player!
            if(thePlayer == null)
            {
                Debug.Log("NO Player Found!");
                return;
            }
        }
        Debug.Log("Hit door");
        thePlayer.currentMapName = transferMapName;
        Debug.Log(thePlayer.currentMapName);
        SceneManager.LoadScene(transferMapName);
    }
}

Option B (preferred):

if (collision.gameObject.name == "Player(Clone)")
{
    Debug.Log("Hit door");
    if (collision.gameObject.TryGetComponent(out PlayerScript player))
    {
        Debug.Log("Player script found!");

        player.currentMapName = transferMapName;
        Debug.Log(player.currentMapName);
        SceneManager.LoadScene(transferMapName);
    }        
}

Option C: Spawn your Player in Awake() so it can be found in Start()

Option D: Assign the Player Reference to the OnTriggerEnter Object, where you make thePlayer public and drag-drop the player, if it's already available in the scene during editmode.

  • Related