- Home /
Instantiated variables of a prefab + script
Hi, total noob here, sorry for not being able to make sense out of answers to similar questions here.
I'm instantiating a tile, which is a prefab sprite with a script component and some text. The text shows the value of a variable of the script.
As I've instantiated the whole thing, I now have a bunch of tiles, each with their own text.
So far so good. However, all of these variables are the same actual variable. I can't figure out how to instantiate each script's variable.
for each tile i'm trying this:
TileArray[i].GetComponent<tiledata>().TileValue += 1;
text.text = "" +TileArray[i].GetComponent<tiledata>().TileValue;
Instead of having each individual tile get +1, it's adding +1 to the same instance of the variable. Tile 1 value = 1 Tile 2 value = 2 etc.
What I want is to have each for loop add +1 to an instantiated variable, resulting in: Tile 1 value = 1 Tile 2 value = 1
Hope any of this makes sense... Cheers guys!
Just a blind guess, can't your property TileValue access a static variable?
I tried it both as a static var and not. Using a static var would not compile for me. I'll post the whole script later...
can you post both scripts: the tiledata script and the script that is using it?
tiledata script:
using UnityEngine;
using System;
using System.Collections.Generic;
public class tiledata : $$anonymous$$onoBehaviour {
public int TileValue;
// Use this for initialization
void Awake ()
{
TileValue = 10;
}
}
The script calling up tiledata:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class hostiles : $$anonymous$$onoBehaviour {
public GameObject[] TileArray;
Text text;
void HostileSpawner ()
{
TileArray = GameObject.FindGameObjectsWithTag ("Tile") ;
for (int i = 0; i < TileArray.Length; i++)
{
print ("Tile " +i+ " Position:" +TileArray[i].transform.position+ " Tile Value " +TileArray[i].GetComponent<tiledata>().TileValue);
TileArray[i].GetComponent<tiledata>().TileValue +=1;
text.text = "" +TileArray[i].GetComponent<tiledata>().TileValue;
}
}
void Start ()
{
text = GetComponent <Text> ();
InvokeRepeating ("HostileSpawner", 0, 2);
}
}
can you change your function to this:
void HostileSpawner ()
{
TileArray = GameObject.FindGameObjectsWithTag ("Tile") ;
for (int i = 0; i < TileArray.Length; i++)
{
tiledata data = TileArray[i].GetComponent<tiledata>();
print ("Tile " + i + " Position:" + TileArray[i].transform.position + " Tile Value " + data.TileValue);
data.TileValue += 1;
text.text = data.TileValue.ToString();
print (data.TileValue);
}
}
and post what is printed to your unity console?
Answer by Fappp · Apr 25, 2015 at 09:30 AM
Add an ID variable to your tileData script, and only assign +1 if the ID equals! Adding ID's to objects that are instantiated multiple times is always a good idea!