Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

c# - 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)

question from:https://stackoverflow.com/questions/66065577/how-to-get-first-script-from-gameobject-while-having-propery-unity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...