Cannot convert UnityEngine.Gameobject[]...

Hello,

I have a lot of “pillars” in my scene which i have tagged “pillar”. I want to be able to change the color of the particular pillar I’m shooting at, as of right now though I’m trying to just change the color of all the pillars at once, but i get an error message.

Cannot convert UnityEngine.Gameobject to UnityEngine.GameObject…

I assume i want a for-statement here or something, I’m not entirely sure how to go about this.
Here’s my code:

#pragma strict

var ammoLeft : int;
var distanceToGround : float;
var clickedColor : Color;
var pillars : GameObject;

function Start () {
ammoLeft = 3;
pillars = GameObject.FindGameObjectsWithTag(“Pillar”);
}

function Update () {

var hit : RaycastHit;

if(Input.GetButtonDown("Fire1")) {
	if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, hit)) {
		distanceToGround = hit.distance;
		pillars.renderer.material.color = clickedColor;
	}
}

}
Also: trying to learn C-sharp but Javascript is much easier…

As said, I want to get every pillars tag, shoot at one of the pillars, and get the color to change.
Thanks in advance

1 Answer

1

You need to make your pillars an array of GameObject since GameObject.FindGameObjectsWithTag will return an array of game objects.

Then you can access the specific element from your pillars using: pillars[index]

You code becomes:

var ammoLeft : int; 
var distanceToGround : float; 
var clickedColor : Color; 
var pillars : GameObject[];

function Start () { ammoLeft = 3; pillars = GameObject.FindGameObjectsWithTag("Pillar"); }

function Update () {

var hit : RaycastHit;
 
if(Input.GetButtonDown("Fire1")) {
    if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, hit)) {
        distanceToGround = hit.distance;

        // Here the consideration is that you want to set all the pillars to a specific color
        for(int i=0; i< pillars.Length; i++)
        {
            pillars*.renderer.material.color = clickedColor;*

}
}
}
}

Thanks for this, this didn't solve the issue where the raycast should change the color of one pillar in particular. But i'll figure it out, thank you so much for solving my issue! :)

If you want to change the color of pillar to which raycast hit then you can simply use: hit.gameObject.renderer.material.color = clickedColor;

Ofcourse, apparently you're much smarter than I am. Would definetly be stuck with this without you, you made my day. Thanks my man

It's just 'been there done that' a thousand times. ;-)