Dear,
I have a code that worked in 5.5, but now that I’ve updated, I get the following error:
“Enabling or adding a Renderer during rendering; this is not allowed. Renderer ‘fireBall (1)(Clone)’ will not be added.
UnityEngine.Object:Instantiate(GameObject, Vector3, Quaternion)
fireBall:OnBecameInvisible() (at Assets/Scripts/fireBall.cs:27)”
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fireBall : MonoBehaviour
{
private Rigidbody2D espinhoRb;
private int atrito;
public int atritoMaximo, atritoMinimo;
public Vector3 posicao;
public GameObject fireBallPrefab;
// Use this for initialization
void Start()
{
espinhoRb = GetComponent<Rigidbody2D>();
atrito = Random.Range(atritoMinimo, atritoMaximo);
espinhoRb.drag = atrito;
posicao = transform.position;
}
void OnBecameInvisible()
{
Instantiate(fireBallPrefab, posicao, transform.localRotation);
pontuacao.pontos += 1;
Destroy(this.gameObject);
}
}
Instantiation of Renderer components is no longer allowed in some contexts that happen after the scene culling is defined.
I assume that your prefab has a Sprite on it. As such, the Sprite component is a Renderer on itself.
A workaround to that is changing your code to actually certify that the instantiation is happening on another context. Update should work just fine.
Quick and shoddy code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fireBall : MonoBehaviour
{
private Rigidbody2D espinhoRb;
private int atrito;
public int atritoMaximo, atritoMinimo;
public Vector3 posicao;
public GameObject fireBallPrefab;
//this bool var tells us if we should do the instantiation or not
private doInstantiation = false;
// Use this for initialization
void Start()
{
espinhoRb = GetComponent<Rigidbody2D>();
atrito = Random.Range(atritoMinimo, atritoMaximo);
espinhoRb.drag = atrito;
posicao = transform.position;
}
void Update()
{
//this guarantees us that we are only actually instantiating the prefab during Update
if(doInstantiation)
InstantiatePrefab()
}
void OnBecameInvisible()
{
InstantiatePrefab();
pontuacao.pontos += 1;
Destroy(this.gameObject);
}
void InstantiatePrefab()
{
//code to not actually instantiate, but to delay it till Update
if(doInstantiation){
Instantiate(fireBallPrefab, posicao, transform.localRotation);
doInstantiation = false;
}
else doInstantiation = true;
}
}
I have same issue. I solved my Problem with this.
IEnumerator OnBecameVisible () {
yield return new WaitForEndOfFrame();
Instantiate(starPrefab,position, transform.localRotation);
}