- Home /
Accessing component of a single prefabs' instance.
Hello everyone, I'm new to Unity and coding. My question may be simple, but I couldn't find a simple answer to this problem anywhere.
I'm trying to clone a prefab multiple times and set alpha (or color) of its every instance to random. My problem: after the Instantiaton all the clones look the same.
Code I attach to an empty game object (works fine):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Spawner : MonoBehaviour {
public GameObject prefab;
public Transform canvas;
public int rowsInt;
public int columnsInt;
void Start()
{
StartCoroutine(SpawnDelay());
}
IEnumerator SpawnDelay()
{
for (int x = 0; x < rowsInt; x++)
{
for (int y = 0; y < columnsInt; y++)
{
Instantiate(prefab, new Vector3(x,y), transform.rotation, canvas);
yield return new WaitForSeconds(0.2f);
}
}
}
}
Code attached to the prefab:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PrefabScript : MonoBehaviour
{
Image img;
Color color;
void Awake()
{
img = GetComponent<Image>();
color = img.material.color;
color.a = Random.Range(0.1f, 0.9f);
img.material.color = color;
}
}
I guess I'm changing the component of the prefab and not the instances, but how can I get access to the components of the clones?
Your answer
Follow this Question
Related Questions
Prefab with component, and attached sub component 1 Answer
Why is instantiated animator prefabs are not working properly? 2 Answers
How to randomly instantiate other prefabs parallel? 1 Answer
How do i Instantiate a prefab with specific assests included 3 Answers
ID or name for Instantiate prefab 1 Answer