When I try and use Destroy(); in my C# script it gives me the error Destroying assets is not permitted to avoid data loss. But destroy works in any of my javascript scripts? Here’s the C# script I’m trying to use it in.
using UnityEngine;
using System.Collections;
public class obstacle_generation : MonoBehaviour {
public GameObject obstacle;
float x = 0;
float z = -3.802516f;
void Update () {
float y = Random.Range(3.042949f, 6.350356f);
if(x < 10) {
Instantiate(obstacle, new Vector3(x * 7.5f, y, z),Quaternion.identity);
x++;
}
if (obstacle.transform.position.x > -8) {
Destroy(obstacle);
}
}
}
This is because the variable obstacle is referencing the asset. What you need to do, is change
Instantiate(obstacle, new Vector3(x * 7.5f, y, z),Quaternion.identity);
to
obstacle = (GameObject) Instantiate(obstacle, new Vector3(x * 7.5f, y, z),Quaternion.identity);
Instead of destroying the instantiated object you were trying to destroy, you were actually attempting to destroy the original due to not assigning obstacle as the instantiated object.
void Update()
{
if (Input.GetKeyDown (KeyCode.Space)) {
prefabCopy = Instantiate (prefab, new Vector3 (0.0f, 1.0f, i * 1.0f), Quaternion.identity);
Destroy (prefabCopy, 2.0f);
i++;
}
}
}
I do something like this… And work perfectly…
If you Don’t want to Destroy Object From variable but destroy object in game Do this.
Instantiate(particlefx, .transform.position , Quaternion.identity);
Destroy(GameObject.FindGameObjectWithTag("Particle"), 1.5f);