Search Unity

[Solved] Acces to script in GameObject

Discussion in 'Scripting' started by Kandrbol, Jul 1, 2019.

  1. Kandrbol

    Kandrbol

    Joined:
    Aug 15, 2018
    Posts:
    117
    Hi. I have common script in every GameObject. There is variable int. How can I acces from GameManager to this script and change int for each object? Example change int in GameObjectA to 35, ini in GameObjectB to 23 etc.?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    There's a couple of different ways to do it depending on your exact needs. If you just need a list of every object, you can do this:
    Code (csharp):
    1. SomeScript[] allSomeScripts = FindObjectOfType<SomeScript>();
    2. foreach (SomeScript ss in allSomeScripts) {
    3. ss.someVariable = 23;
    4. }
    Note: this will be slow if you're running this every frame, so store your result from FindObjectsOfType if you plan to use it repeatedly.

    That's probably the most simple and straightforward way, but if you can better describe what this is intended to be used for I could give a better answer.
     
  3. Kandrbol

    Kandrbol

    Joined:
    Aug 15, 2018
    Posts:
    117
    Thanks. I understand create a list with scripts from all specific object (example door).
    No understand how change different int. Example I want change int doorA to 23, change int doorB to 15, change int doorC to 7 etc.
     
  4. Kandrbol

    Kandrbol

    Joined:
    Aug 15, 2018
    Posts:
    117
    I have it. Thanks.
    I didn't understand that GetComponent also works with script.

    door[0].GetComponent<Script>().int = 1;