- Home /
Accessing List in another gameObject via script
I'm trying to iterate through all stored gameObject in a List and if a certain condition is met (in this case, if the gameObject is seen by the player), access another list in the current gameObject and add to it:
var List1 : new List.<GameObject>(); //contains all Characters in scene
var SeenBy : new List.<GameObject>();
for (var CurrentObject : GameObject in List1)
{
CurrentObject.GetComponent(LineOfSight).SeenBy.Add(gameObject); //access the other objects SeenBy List and add this gameObject to it
}
However, I get this error:
Assets/Scripts/LineOfSight.js(7,46): BCE0023: No appropriate version of 'UnityEngine.GameObject.GetComponent' for the argument list '(function(UnityEngine.GameObject): boolean)' was found.
What am I doing wrong? How do I access Lists or even normal variables (tried that too via GetComponent) while iterating through a List?
I'm confused because you show a line defining SeenBy as if it's in this script, then you say '..access the other objects SeenBy list..'
Expand the section at this site 'How to access variable or method...'
Yes the code above is all in the script called LineOfSight, the idea is that both characters have this script and if character 1 sees character 2 then character 1 is added to character 2's SeenBy list :) (and vice versa)
The main point however, is how to access a gameObject's variables if it's currently being iterated as part of a list.
try something like foreach(GameObject go in List1) { go.variable1...
After some more testing, I really don't understand how to access any variables (let alone lists) in the gameObject that's currently being iterated. For example, we have the folling main script "ExampleScript":
import System.Collections.Generic;
var ActorList : GameObject[];
function Update()
{
ActorList = GameObject.FindGameObjectsWithTag ("Actor");
}
function CountActors()
{
for (var ActorCur : GameObject in ActorList)
{
ActorCur.GetComponent(ValueScript).Value = 20; //this line gives the error
}
}
and all Actors have this simple script called ValueScript:
var Value : int = 10;
it still gives the error Assets/Scripts/ExampleScript.js(11,24): BCE0023: No appropriate version of 'UnityEngine.GameObject.GetComponent' for the argument list '(function(UnityEngine.GameObject): boolean)' was found.
FindGameObjectsWithTag in Update, slow down there sailor :O!
Answer by fherbst · Sep 01, 2013 at 06:56 PM
Might it be that you have an additional method called "LineOfSight" which returns a boolean?
If yes, you could either rename that method or use
GetComponent.<LineOfSight>()
to be more specific that you want the type, not let Unity figure out what LineOfSight is (like I said, the error message says that there is also a method with exactly this name).
Derp, that was indeed the problem... I had a function named LineOfSight inside the script named LineOfSight! I feel kinda dumb now :[
Cheers!