It isn't static but acts like one

Hi.

I have a problem with this code.

using System.Collections.Generic;
using UnityEngine;

public class Pez : MonoBehaviour
{
    public GameObject PrefabPez;
    public List<Transform> Posiciones = new List<Transform>();
    public List<Material> MaterialPeces = new List<Material>();
    public int numPeces = 30;

    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < numPeces; i++)
        {
            int rangoVariable = Random.Range(0, Posiciones.Count - 1);
            Vector3 pos = new Vector3(Posiciones[rangoVariable].position.x, Posiciones[rangoVariable].position.y, Posiciones[rangoVariable].position.z);

            var fish = Instantiate(PrefabPez, pos, Quaternion.Euler(0, 0, 0));

            //Here's the issue
            fish.transform = gameObject.transform;
            var material = fish.GetComponentInChildren<MeshRenderer>();
            int rangoMateriales = Random.Range(0, MaterialPeces.Count - 1);
            material.material = MaterialPeces[rangoMateriales];
        }
    }
}

I don’t know in which part of my code I made this Prefab or this GameObject a static, cause, when I try to parent it to another GameObject, this message shows saying that is just to read.

Anyone have any idea of what is happening.

I tried making another script from scratch and writing all over again, but the issue is still happening.

What’s the exact error in the console, could you please share with us?

FYI: This is not right. The integer version of the Random.Range is exclusive on the max side, specifically for these use cases. This should be Random.Range(0, MaterialPeces.Count). Also see the documentation here: https://docs.unity3d.com/ScriptReference/Random.Range.html

@ thanks for your reply.

I’ll follow your recommendations for the Random.Range.

About the static issue, this is the complete message: CS0200: Property or indexer ‘GameObject.transform’ cannot be assigned to – it is read only

And what did you try to do? That’s always readonly since transforms are mandatory and cannot be removed or changed (only its properties). Maybe you’re missing a .position there?

I’m trying to parent all the created prefabs to the gameobject with the script.

Delete this line: fish.transform = gameObject.transform;
Replace this line: var fish = Instantiate(PrefabPez, pos, Quaternion.Euler(0, 0, 0)); with this line: var fish = Instantiate(PrefabPez, pos, Quaternion.identity, gameObject);.
I think this should work.

2 Likes

Nice, thanks a lot, It work just perfect.

Or, in case you use a ancient Unity version where the Instantiate method didn’t have that additional parent argument, you would have to do

fish.transform.parent = gameObject.transform;

Thanks a lot, all of you. You solved my problem. Now the program works just fine.