- Home /
Getcomponent through tag and findgameobject with tag and do a function but somehow gives errors (It's hard to explain)
As above it's hard to explain. As well as I know it's only one object that's tagged with "player" and "firingpoint" So I get this error that says:
BCE0019: 'GetComponent' is not a member of 'Object'.
and here's my code #pragma strict var isMedkit : boolean; var isAmmo : boolean; var otherObj1; var otherObj2;
function Start()
{
otherObj2 = GameObject.FindGameObjectsWithTag ("Player");
otherObj1 = GameObject.FindGameObjectsWithTag ("FiringPoint");
}
function OnTriggerEnter (other : Collider) {
if (other.gameObject.tag == "Player")
{
if(isAmmo == true){
otherObj1.GetComponent(Thunderbolt).magsLeft += 5;
Destroy(gameObject);
}
if (isMedkit == true){
otherObj2.GetComponent(Health).health = 100;
Destroy(gameObject);
}
}
}
Answer by HarshadK · Aug 05, 2014 at 11:21 AM
You are using GameObject.FindGameObjectsWithTag which returns an array of game objects.
Even though there is one game object tagged player you still get your 'otherObj1' and 'otherObj2' as an array because Unity will create an array of game objects to store the result of GameObject.FindGameObjectsWithTag.
So you have to access it as otherObj1[0], considering there is only one element in your array which you want to access.
Or
use GameObject.FindGameObjectWithTag if you are to use it to find and store only one game object via tag.
Can you explain a bit more about how to access it as otherObj[1], please? (I'm new to arrays)
You access the particular element from the array using its index.
The index of first element of an array is 0. Then each next element from array will increase by 1.
So in your case since there is only one element its index will be 0.
So your line of code above will be:
otherObj1[0].GetComponent(Thunderbolt).magsLeft += 5;
And same for otherObj2.
I'm sure that will work but my syntax must be wrong BCE0048: Type 'Object' does not support slicing. and I typed the code like this (I might have messed up)
#pragma strict
var is$$anonymous$$edkit : boolean;
var isAmmo : boolean;
var otherObj1;
var otherObj2;
function Start()
{
otherObj2 = GameObject.FindGameObjectWithTag ("Player");
otherObj1 = GameObject.FindGameObjectWithTag ("FiringPoint");
}
function OnTriggerEnter (other : Collider) {
if (other.gameObject.tag == "Player")
{
if(isAmmo == true){
otherObj1[0].GetComponent(Thunderbolt).magsLeft += 5;
Destroy(gameObject);
}
if (is$$anonymous$$edkit == true){
otherObj2[0].GetComponent(Health).health = 100;
Destroy(gameObject);
}
}
}
Declare your arrays like:
var otherObj1 = new Array();
var otherObj2 = new Array();
Or
You can also remove #pragma strict. Although, it is not the suggested way.
I still get this error, I don't know why:
'GetComponent' is not a member of 'Object'.
Your answer
![](https://koobas.hobune.stream/wayback/20220613155852im_/https://answers.unity.com/themes/thub/images/avi.jpg)