- Home /
Getting Error I don't Understand - 'position' is not a member of 'UnityEngine.GameObject[]'.
Bare with me please if I explain this badly. I currently have 2 scripts running on a game object that work fine on their own.
The first is a simple script that allows my game object to find another object and move towards it (avoiding obstacles using navmesh/navigation)
#pragma strict
public var victim : Transform;
private var navComponent : NavMeshAgent;
function Start()
{
navComponent = this.transform.GetComponent(NavMeshAgent);
}
function Update()
{
if(victim)
{
navComponent.SetDestination(victim.position);
}
}
The 2nd script simply finds all objects in the scene with the tag 'Resource' and prints the name of the nearest one -
public var gos : GameObject[];
// Print the name of the closest enemy
print(FindClosestResource().name);
// Find the name of the closest enemy
function FindClosestResource () : GameObject
{
// Find all game objects with tag Enemy
gos = GameObject.FindGameObjectsWithTag("Resource");
var closest : GameObject;
var distance = Mathf.Infinity;
var position = transform.position;
// Iterate through them and find the closest one
for (var go : GameObject in gos)
{
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
return closest;
}
I've been trying to make a script that will take the variable from script 2 and use it to define the destination for my first script. Or more easily put I want it to find the nearest object with the tag and move to that object.
This is what I have so far -
#pragma strict
private var navComponent : NavMeshAgent;
var targetResource : GameObject = GameObject.Find( "Harvester" );
var otherScript : FindClosestObject = targetResource.GetComponent( FindClosestObject );
var newGos = otherScript.gos;
function Start()
{
navComponent = this.transform.GetComponent(NavMeshAgent);
}
function Update()
{
if(newGos)
{
navComponent.SetDestination(newGos.position);
}
}
I've managed to fix a few compile errors but this error message has me stuck. What exactly does it mean and how can I fix it ?
Assets/AI Scripts/Move to Closest Object.js(20,52): BCE0019: 'position' is not a member of 'UnityEngine.GameObject[]'.
Any suggestions guys ?? (oh and please make any comments idiot proof...lol)
Thanks
Answer by meat5000 · Jan 29, 2015 at 04:29 PM
position is a member of transform, not gameobject
Hmm... ok
But if I try and make it of type transform by
var newGos : Transform = otherScript.gos;
I get this error -
Assets/AI Scripts/$$anonymous$$ove to Closest Object.js(20,52): BCE0019: 'position' is not a member of 'UnityEngine.GameObject[]'.
???
Just access the transform of the gameobject.
gameObject.transform
Of course your inner code is not exposed but you access the transform from a gameobject array by including the index.