- Home /
Changes done in prefab script get applied to all instances of that prefab.
I am making multiple instances of prefab that has a script asign to it. In the script I am simply changing its color on mousedown. But clicking on one instance of prefab in the scene makes all other instances to change. I tried to change the material, so that each instance has its own material, but it did not seem to help. By logging I found out, that the method called on mousedown gets call for each instance. Could anyone explain this behaviour to me? I attached the code of script of the prefab and also code that I instantiate the prefabs with.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class markTile : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.Log(GetComponent<Renderer>().transform.position+"clicked prefab");
Color currentEditorColor = EditorController.getEditorController().getCurrentEditorColor();
GetComponent<Renderer>().material.color = currentEditorColor;
}
}
}
}
public void CreateTileMap()
{
for(int i=0; i<gridWidth; i++)
{
for(int j=0; j<gridHeight; j++)
{
GameObject tileObject = Instantiate(tileItem);
tileObject.transform.localScale += new Vector3(5,5,5);
tileObject.transform.position = new Vector3(i * tileOffset + 5 + defaultOffset, j*tileOffset + 5 + defaultOffset, 0);
//this is the instance I am having problem with
GameObject topRightTile = Instantiate(innerTileItem);
topRightTile.transform.position = new Vector3(i * tileOffset + 5 + defaultOffset, j * tileOffset + 5 + defaultOffset, 0);
Material material = new Material(Shader.Find("Specular"));
topRightTile.GetComponent<Renderer>().material = material;
}
}
}
Hi, I got the same problem, have you found the cause of it and/or a solution?
Hi, I am not sure as it was quite a while ago. I can check the code and refresh my memory.
I am not sure if it is going to be of any help for you, I am not able to find the previous versions of the code and I am not sure what innerTileItem referred to in the code above but this is how I made the instance in the later version:
public override GameObject CreateTile(int i, int j)
{
GameObject tileObject = Instantiate(Resources.Load<GameObject>("Prefabs/FirstLevelTile"));
tileObject.transform.localScale += new Vector3(25,25,25);
tileObject.transform.position = new Vector3(i * TileOffset, j*TileOffset, -10f);
return tileObject;
}
Your answer
Follow this Question
Related Questions
How to manipulate a variable of a prefab script (instantiated) while the game is runnning . 1 Answer
Prefabs won't change? 1 Answer
How to instantiate a prefab declared in one script, from another script 2 Answers
How to add components to all spawned prefabs ? 0 Answers
How can I save multiple instances of a single prefab? 1 Answer