Search code examples
c#loopsunity-game-engineget

How to get first script from gameobject while having propery : Unity


I would like to get the first script in an gameobject, and still be able to set and get proper's of it. I'm coding in c# in unity I have tried "GetComponents(typeof(MonoBehaviour))" , "MonoBehaviour[] scripts = gameobject.GetComponents()" and other methods but all of that methods does not let you set and get

I dont know if it is even possible, and if it is not a i work around would be nice. Thanks

(If you need more info about this please comment and ill try to answer)


Solution

  • You change properties of any Component (Unity Component or Script) by getting a reference to the Component and using that.

    Assuming that the component is actually on your GameObject:

    ComponentType component = GetComponent<ComponentType>();
    component.RandomProperty = randomValue;
    

    Example:

    Rigidbody rigidbody = GetComponent<Rigidbody>();
    rigidbody.freezeRotation = true;
    

    You can use GameObject.AddComponent<ComponentType>(); to Add a component.

    Any component needs to derive from MonoBehaviour in order to be able to attach to a GameObject.

    See:

    GameObject.GetComponent

    GameObject.AddComponent