- Home /
ID or name for Instantiate prefab
Im trying to create a Big Die out of small ones, so far it works but my problem is to give each small dice a id or name, i searched for a while and it doesn't work, this is a part of my code:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class CreateDiceV1 : MonoBehaviour {
public Transform prefab;
public int Anzahl = 4;
void Start () {
float Abstand = 1.5F;
int IDCounter = 0;
int AllDiceCounter = ( ( ( (int)Math.Pow(Anzahl,2) ) * 2 ) + ( ( ( Anzahl - 2 ) * Anzahl ) * 2 ) + ( ( (int)Math.Pow((Anzahl-2),2) ) * 2 ) );
Debug.Log("This Many Dice -> " + AllDiceCounter);
//Front
for (float x = 0; x < Anzahl; x++) {
for (float y = 0; y < Anzahl; y++) {
GameObject GameObj = Instantiate(prefab, new Vector3( x * - Abstand + Abstand * ( Anzahl / 2 ) - 0.75F, y * - Abstand + Abstand * ( Anzahl / 2 ) - 0.75F, 0 * - Abstand + Abstand * ( Anzahl / 2 ) - 0.75F), Quaternion.identity) as GameObject;
GameObj.name = "TEST"+IDCounter;
IDCounter++;
}
}
}
}
I saw the solution with the gameobject in several places but i just doesnt work, i got this error message:
NullReferenceException: Object reference not set to an instance of an object CreateDiceV1.Start () (at Assets/CreateDiceV1.cs:28)
I also tried to create it as a public var, doesn't work either.....
Can you help me or at least have a hint for me?
please note that the word
DICE IS A PLURAL
The singular is "die". One die, two dice, three dice. This is quite surprising to many non-English speakers. The die is cast.
.name is correct, you have some other simple problem. You should indicate clearly (paste it) which line is throwing the error.
Also .. You cannot have very long lines of code like that. Carefully rewrite it over a few lines.
The error is because of this line:
GameObj.name = "TEST"+IDCounter;
I understand the meaning of the error but i cant figure why its happening, because i just fill the object the line before.....
Answer by syclamoth · Jun 04, 2013 at 08:40 AM
The problem is that you are trying to instantiate a 'Transform' as a 'GameObject'. Change the type of the prefab variable to 'GameObject' and the problem will go away (you will, of course, have to re-assign the prefab in the inspector.
Yep he is right. Technically speaking when you instantiate a gameObject with a reference to a transform of it, you can not cast it to gameObject so there reference should be in the type that you want to cast the result of instantiate to.