Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Script Causing Another Script To Become Inactive

Discussion in 'Scripting' started by iainblackwood, Feb 17, 2018.

  1. iainblackwood

    iainblackwood

    Joined:
    May 20, 2017
    Posts:
    1
    I am trying to destroy my Player and re-spawn him after 3 seconds. To do this, I detect a collision in my Player's script, instantiate the explosion and fire particle systems at point of crash, send a notification to my GameManagerScript to initiate the Coroutine function for reset and then delete the player object.

    However, if I have the GameManager empty that holds the GameManagerScript attached to the player prefab slot that asks for the script (public GameManagerScript GMS), when the player respawns, the instantiated prefab no longer holds the script in the slot.

    But if I create a prefab of the GameManager empty and slot it in, then when it goes to run the coroutine in the GameManagerScript, I get an error saying:

    "Coroutine couldn't be started because the the game object 'GameManager' is inactive!"

    Why would it be setting the GameManager script to inactive?

    So my collision code, in my player's script looks like this:

    void OnCollisionEnter(Collision col)
    {
    if (col.gameObject.tag == "Solid")
    {
    Instantiate(explosionEffect, transform.position, transform.rotation);
    Instantiate(fireBurn, transform.position, Quaternion.Euler(0, 0, 0));
    Debug.Log("Hit something solid");
    GMS.CallToReset();
    Destroy(gameObject);
    }
    }​

    and the code in the GameManagerScript is:

    public void CallToReset()
    {
    StartCoroutine(ResetPlayer());
    }

    IEnumerator ResetPlayer()
    {
    yield return new WaitForSeconds(3);
    Instantiate(player, StartPosition.position, StartPosition.rotation);
    }​

    I have no idea why when GameManager is not a prefab it works but does not attach to the new instantiated player object, or when set as a prefab, the player script causes the GameManagerScript to become inactive.

    Any ideas?
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    If you don't have to destroy the player, you could disable it & then re-enable it. That's one option.

    The other option is to use the return value of the newly instantiated player, and from your game manager script, set the variable (on the player script) to be itself.

    Inside reset player, it might be like this:
    Code (csharp):
    1. GameObject g = Instantiate(player, StartPosition.position, StartPosition.rotation);
    2. g.GetComponent<PlayerScript>().GMS = this;
    It doesn't attach itself, as you put it, to the new game object, because you didn't tell it to. :)

    Hope that helps.