Changing attributes of an instance (not of a prefab!)

TL;DR: I’m trying to change attributes of instances exclusively, but my code is changing the attributes not only of the instance, but also straight up changing the attributes of the prefabs in my assets folder!

I’m sorry if this is a dumb question that has been answered a million times, but I have been looking for the answer and I never found what I was looking for, maybe because I’m a beginner and I don’t know how to research right. Anyway, I’m trying to instantiate prefabs and change their properties immediately upon instantiation – properties such as material and mesh. Here’s what my code looks like after reading some suggestions I’ve found on forums:

public GameObject SectionedBuilding;

void OnTriggerEnter(Collider other)
{
    if ((other.gameObject.tag == "Missile") | (other.gameObject.tag == "Explosion"))
    {
        Instantiate(SectionedBuilding, transform.position, transform.rotation);
        SectionedBuilding.transform.localScale = transform.localScale;
        Destroy(gameObject);
    }
}

Problem is that it doesn’t change just the instance’s attributes, but also the prefabs’ attributes in the assets folder, which is rather spooky ngl. What am I’m doing wrong? Thanks in advance!

Edit: Removed something extremely dumb

1 Like

You are changing the localscale of SectionedBuilding - the prefab you reference at the top. NOT its instance, which would be the returnvalue of Instantiate. So simply save that. GameObject instantiatedBuilding = Instantiate(…);
Then work with the instance.

2 Likes

Thanks a lot, Yoreki, it worked perfectly! I didn’t know you could do that in csharp, I’m very new to the whole programming thing. I owe you one!

Just for the record, my corrected code is:

public GameObject SectionedBuilding;

void OnTriggerEnter(Collider other)
{
    if ((other.gameObject.tag == "Missile") | (other.gameObject.tag == "Explosion"))
    {
        GameObject instantiatedBuilding = Instantiate(SectionedBuilding, transform.position, transform.rotation);
        instantiatedBuilding.transform.localScale = transform.localScale;
        Destroy(gameObject);
    }
}
3 Likes