Welcome, Guest! Login | Register
get the same script component from multiple objects
Info
Report
246 Posts

the method i know for getting and using the script from an object consists of doing something like thing.GetComponent<scriptname>(); then doing scriptname.yaddayadda, but if i have two gameobjects in the same script and they both use the same script how do i tell them apart?
Created on: 2 weeks ago
Info
Report
305 Posts

It is really unclear of what you actually want to achieve.

Unity has a bunch of other GetComponent methods that I can suggest.

One is GetComponents<YourScript>(), which will get all the components on the game object if it has many "same type" components. Example is having 2 BoxCollider components on a game object.

Second is GetComponentsInChildren<YourScript>() which will get all the components on the current object, but also the object's children. Example is having many children objects that have one or more of that component type.

See more info: https://docs.unity3d.com/ScriptReference/GameObject.html in section Public Methods.
Created on: 2 weeks ago
Info
Report
246 Posts

ahh my apologies @powersupersport i'll try to make myself clearer
the pic shows what i usually do when getting a script from a gameobject and using variables from said script
the problem is that if i need to get the same script component from different game objects i obtain weird results when i have to change the variables from said script
i was trying to find a way to make sure every time i call a script, its the one from the gameobject i need
Created on: 2 weeks ago
Edited on: 2 weeks ago
Info
Report
305 Posts

If you want to get a specific component instance, then the easiest way is to assign it in the inspector instead of getting it runtime with GetComponent. Otherwise you'd need to design your own way of detecting which object you want to get (tags, layers, component properties etc).

Also, just to clear that up, GetComponent will get the component on the current game object it's being called. If you want to get the component from another game object, then you can do this:

// Some object.
GameObject obj;
YourComponent yourComponent = obj.GetComponent<YourComponent>();
Created on: 2 weeks ago
Info
Report
246 Posts

ok it works have a kiss
Created on: 2 weeks ago
Reply
Preview
Post
Or use the advanced reply form here...
Sponsored