Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question How can I make instatiated objects spawn with individual materials

Discussion in 'Getting Started' started by rhinojos, Mar 27, 2024.

  1. rhinojos

    rhinojos

    Joined:
    Feb 13, 2024
    Posts:
    1
    I am making the script for my spawner which is meant to drop objects in a certain range on the x axis, but I've been trying to make each new object spawn with a differen color that gets selected from a bunch of random ranges. I thought the following method would work:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Spawner : MonoBehaviour
    6. {
    7.     public GameObject pandita;
    8.     public Material material;
    9.     private Color customColor;
    10.     private int range_min;
    11.     private int range_max;
    12.  
    13.     void Start()
    14.     {
    15.        
    16.         range_min = 3;
    17.         range_max = 6;
    18.     }
    19.  
    20.     void Update()
    21.     {
    22.         Invoke("Spawn",Random.Range(range_min,range_max));
    23.        
    24.     }
    25.  
    26.     private void Spawn()
    27.     {
    28.         var position = new Vector3(Random.Range(-8.8f, 8.8f), 6, 0);
    29.         GameObject a = Instantiate(pandita, position, Quaternion.identity);
    30.         material = a.GetComponent<MeshRenderer>().material;
    31.         customColor = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f));
    32.         material.color = customColor;
    33.         CancelInvoke();
    34.     }
    35. }
    36.  
    But the materials won't change at all and I'm at a loss about what the problem might be, I'm a complete beginner and so I would like to ask for help if anyone knows how I could make this work. Thanks!