'How do I change properties of a new spawned in object?
I'm fairly new to programming and right now I'm working on a 2D-Game for Android with Unity. The basic concept right now is that a object moves to the middle of the screen and it needs to "touch" an other object so you can press on a button and the moving object is getting destroyed. After it got destroyed I want another to spawn in and keep that cycle going. There is my problem. I have the (moving) object as a prefab and added it as the public GameObject "RedTriangle". The object is getting spawned in and moves to the center of the screen but it doesn't change the layer of the new objects when I press the button (I guess because its not the same object as the "RedTriangle" object). I really don't know how to change the Layer of new spawned in objects and hope I can get help here. Thanks already for all responses.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Red : MonoBehaviour, IPointerClickHandler
{
public GameObject RedTriangle;
public GameObject FalseTriangle;
public Transform spawnPos;
public float spawnT;
private void Start()
{
GameObject newTriangle = Instantiate(RedTriangle, spawnPos.position, Quaternion.identity);
}
IEnumerator touchCD()
{
while (true)
{
yield return new WaitForSeconds(0.1f);
if (RedTriangle == null)
{
}
else if (RedTriangle != null)
{
Debug.Log("!= null");
RedTriangle.layer = 0;
}
}
}
public void Update()
{
if (RedTriangle == null)
{
spawnT = Random.Range(1, 4);
if (spawnT == 3)
{
GameObject newTriangle = Instantiate(FalseTriangle, spawnPos.position, Quaternion.identity);
}
else
{
GameObject newFalseTriangle = Instantiate(RedTriangle, spawnPos.position, Quaternion.identity);
}
}
}
public void OnPointerClick(PointerEventData eventData)
{
RedTriangle.layer = 7;
Debug.Log("button");
StartCoroutine(touchCD());
}
Solution 1:[1]
Assuming you want to change the layer of the object immediately after spawning, just do exactly that. For example:
GameObject newTriangle = Instantiate(FalseTriangle, spawnPos.position, Quaternion.identity);
newTriangle.layer = 0;
If you want to change the current (MonoBehaviour) object's own layer from its own attached component script e.g. when a certain event occurs, you don't need to keep the reference in your own variable as you can just use for example:
gameObject.layer = 0;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sven Viking |
