Search Unity

Question how to enable a component through script ?

Discussion in 'Scripting' started by TokyoDustOff_, Jul 1, 2022.

  1. TokyoDustOff_

    TokyoDustOff_

    Joined:
    Dec 12, 2021
    Posts:
    12
    So, while coding a script for the player to respawn after dying, it worked, though, while respawning, all the Player components got disabled, wich is weird, but to fix that, i wanted to enable individually each components through scripts, i tried different syntaxes but always had errors, how do you enable components through scripts please?
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    what component are you tying to change?, some can't be disabled\enabled.
    what was the code you got errors on and what errors did you get?
     
  3. Kreshi

    Kreshi

    Joined:
    Jan 12, 2015
    Posts:
    446
    Can you copy paste the first error?
     
  4. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,304
    Find out why it's doing that instead of trying to fix the symptom.
    Maybe post your death/respawn code
     
  5. TokyoDustOff_

    TokyoDustOff_

    Joined:
    Dec 12, 2021
    Posts:
    12
    these are the two pieces of code i used:

    Code (CSharp):
    1. public Transform respawnPoint;
    2.     public static LevelManager instance;
    3.     public GameObject playerPrefab;
    4.  
    5.     private void Awake()
    6.     {
    7.         instance = this;
    8.     }
    9.  
    10.     public void Respawn()
    11.     {
    12.         Instantiate(playerPrefab, respawnPoint.position, Quaternion.identity);
    13.        
    14.     }
    and

    Code (CSharp):
    1.  
    2.  
    3.     void OnTriggerEnter2D(Collider2D collision)
    4.     {
    5.         if(collision.gameObject.CompareTag("Hazards"))
    6.         {
    7.            Destroy(gameObject);
    8.            LevelManager.instance.Respawn();
    9.         }
    10.     }
     
  6. TokyoDustOff_

    TokyoDustOff_

    Joined:
    Dec 12, 2021
    Posts:
    12
    the error was "'Component' does not contain a definition for 'enabled' and no accessible extension method 'enabled' accepting a first argument of type 'Component' could be found (are you missing a using directive or an assembly reference?)"

    and the components are:
    Box Collider2D, Circle Collider2D, and all the scripts on it

    sorry, my problem may be dumb
     
  7. venom789

    venom789

    Joined:
    Apr 18, 2022
    Posts:
    178
  8. TokyoDustOff_

    TokyoDustOff_

    Joined:
    Dec 12, 2021
    Posts:
    12
    venom789 likes this.