Problem with Instantiated clones
Hi, I have a spawner with the following code: using UnityEngine; using System.Collections;
public class Spawn : MonoBehaviour {
public GameObject[] enemies;
public int amount;
private Vector3 spawnPoint;
void Start() {
amount = 2;
}
void Update () {
enemies = GameObject.FindGameObjectsWithTag ("Enemy");
amount = enemies.Length;
if (amount < 100) {
InvokeRepeating ("spawnEnemy",1,100f);
}
}
void spawnEnemy() {
spawnPoint.x = Random.Range (-20,20);
spawnPoint.y = 0.5f;
spawnPoint.z = Random.Range (-20,20);
Instantiate (enemies[Random.Range(0, enemies.Length -1)], spawnPoint, Quaternion.identity);
CancelInvoke();
}
}
I also have the code to make the enemies move, which looks like this:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class EnemyMove : MonoBehaviour {
public Transform track;
private float moveSpeed = 3;
public int score;
public Text scoreText;
public int health;
public Color damageColor = Color.red;
Renderer rend;
void Start() {
PlayerPrefs.GetInt ("scorePref");
score = PlayerPrefs.GetInt ("scorePref");
health = 1000;
rend = GetComponent<Renderer> ();
rend.material.color = Color.white;
}
void Update () {
float move = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, track.position, move);
PlayerPrefs.SetInt ("scorePref", score);
if (scoreText.name == "Score") {
scoreText.text = "Score: " + score;
}
}
void OnTriggerEnter(Collider col) {
if (col.gameObject.tag == "Bullet") {
PlayerPrefs.SetInt ("scorePref", score);
rend.material.color = damageColor;
health -= 100;
print ("I've lost health!");
if (health <= 0) {
Destroy (GetComponent<MeshRenderer> ());
Destroy (GetComponent<BoxCollider> ());
Destroy (gameObject, 5);
}
}
if (col.gameObject.tag == "Player") {
Destroy (gameObject);
Debug.Log ("Outch");
}
}
}
When the object "Bullet" collides with the Enemy, the material changes to red. However, I sometimes get an error which says that some of my clones don't have a Renderer attached to them, even though the prefab "Enemy" which is being spawned does have a Renderer.
As well as this, does anyone know how to use PlayerPrefs to add to the score in the code?
Answer by RayCastX · Jun 06, 2016 at 07:01 PM
hmmm.. Maybe the bullets are colliding with other gameobjects without renderer. For example, terrain..
try to add this..
if(rend != null) //do something
or
if(this.GetComponent() != null)// do something.
@RayCastX There is nothing else it could have collided with though. Any ideas?
Your answer
Follow this Question
Related Questions
Make a collision check when spawning with Instantiate 1 Answer
Instantiate spawn problem 1 Answer
Spawn a random object on more than one position 1 Answer
Spawn enemies so they aren't instantiated on top of each other (C#) 2 Answers
What is the most efficient way to spawn in a lot of cubes, like 10k? [c#] 2 Answers