Cannot convert type `UnityEngine.GameObject[]' to `UnityEngine.GameObject' via a built-in conversion
I am a beginner as a coder, not so sure how to fix this error. these code is from the lesson video on internet, but does not work in my project. please help me..... thank you very much!
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Spawner : MonoBehaviour {
public Transform ball;
public int amount = 100;
private bool doOnce = true;
// Update is called once per frame
void Update()
{
if (Time.time > 3f && doOnce)
{
for (int i = 0; i < amount; i++)
{
Vector3 pos = new Vector3(transform.position.x, transform.position.y + i, transform.position.z);
GameObject go = Instantiate (ball, pos, Quaternion.identity) as GameObject;
go.GetComponent<Rigidbody>().useGravity = false;
}
doOnce = false;
},using System.Collections;
using System.Collections.Generic; using UnityEngine;
public class Spawner : MonoBehaviour {
public Transform ball;
public int amount = 100;
private bool doOnce = true;
// Update is called once per frame
void Update()
{
if (Time.time > 3f && doOnce)
{
for (int i = 0; i < amount; i++)
I have not much a coder, these code is copy from the lesson video on internet, but it does not work in my project, please help me, thank you very much!
{
Vector3 pos = new Vector3(transform.position.x, transform.position.y + i, transform.position.z);
GameObject go = Instantiate (ball, pos, Quaternion.identity) as GameObject;
go.GetComponent<Rigidbody>().useGravity = false;
}
doOnce = false;
}
}
}
Please could you format your code (use the 101010 button) and remove the duplication (you seem to have pasted the code in twice?).
And what makes you think the problem is in this piece of code? Does the error message not tell you where the issue is?
FWIW, on reading the title, I was expecting to see something broadly like this....
GameObject go = GameObject.FindGameObjectsWithTag("xx");
(the function returns an array of GameObjects, which the code tries to assign to a single GameObject variable - a mistake which would give an error message like the one you've shown).
Answer by MaxGuernseyIII · Dec 01, 2017 at 05:31 PM
The compiler should be telling you exactly where that error is. Wherever it is, you need to address the fact that you have an array and you need an element from that array. If instances of that array will always have exactly one element, you can get that element like this:
var theGameObject = gameObjects[0];
That's assuming that you want to call the selected object theGameObject and your array is called gameObjects.
Your answer
Follow this Question
Related Questions
How to destroy only a clone in Unity 3d? 0 Answers
Unity5/C# beginner here! Need some scripting help :) <3 1 Answer
How do you order an array by numbers held in Game Object String 0 Answers
how do i check if a gameobject is not active? 0 Answers
I need help with boss design. I am new to coding so any help would be nice. 0 Answers