- Home /
How do I find a GameObject by a script attached to it?
I'm currently using FindGameObjectsWithTag("")
. I'm trying to use FindObjectsOfType<>()
to the same thing with a script attached to it instead of a tag (since no multiple tags).
public List<GameObject> isObject;
GameObject go;
void Start () {
//isObject.AddRange(GameObject.FindGameObjectsWithTag("Player"));
// Trying to find an object by component
go = GameObject.FindObjectsOfType<IsObject>();
isObject.AddRange(go);
isObject.Clear();
}
I get the errors
Assets/Scripts/IsObject.cs(15,21): error CS1503: Argument
#1' cannot convert >
UnityEngine.GameObject' expression to type >`System.Collections.Generic.IEnumerable'
and
Assets/Scripts/IsObject.cs(15,21): error CS1503: Argument
#1' cannot convert >
UnityEngine.GameObject' expression to type >`System.Collections.Generic.IEnumerable'
Are you trying to refer all game objects added in your scene?
Answer by Bunny83 · Jun 17, 2018 at 01:45 PM
You don't need to find anything. Every component instance already knows which gameobject it belongs to. You can access the owning GameObject by using the gameObject property of your component.
void Start ()
{
IsObject[] components = GameObject.FindObjectsOfType<IsObject>();
foreach(IsObject comp in components)
isObject.Add(comp.gameObject);
}
I wouldnt recommend using FindObjectsOfType in your final game.
Answer by Bouldoro · Jun 18, 2018 at 06:19 AM
To follow up, can I add a condition to that?
I only need objects that are above me (the object that is found). For example I have 5 objects lined up vertically
o(1) has 0 objects above it
o(2) has 1 object above it
o(3) has 2 objects above it
o(4) has 3 objects above it
o(5) has 4 objects above it
I also want to keep doing this (not just at the start). Since I'm not applying forces I should place this in FixedUpdate List isObject; IsObject[] listOfObjects; SpriteRenderer sr;
void FixedUpdate () {
listOfObjects = GameObject.FindObjectsOfType<IsObject> ();
sr = GetComponent<SpriteRenderer> ();
}
void FixedUpdate () {
foreach(IsObject foundObject in listOfObjects){
if (foundObject.transform.position.y > transform.position.y){
isObject.Add (foundObject.gameObject);
sr.sortingOrder = isObject.Count;
}
}
isObject.Clear();
}
When I moved to fixedupdate i get the error
NullReferenceException: Object reference not set to an instance of an object IsObject.FixedUpdate () (at Assets/Scripts/IsObject.cs:36)
Your answer
Follow this Question
Related Questions
GameObjects Array Problem 2 Answers
Resource counter doesn't reset on each iteration 0 Answers
AI cannot find closest Target 0 Answers