Quantcast
Channel: Questions in topic: "missingreferenceexception"
Viewing all 208 articles
Browse latest View live

Why does my Bullet prefab go missing from my gun script when destroyed?

$
0
0
In my First Person Shooter game, I want my bullets to get destroyed every 5 seconds. Instead of destroying itself from the scene, it just gets rid of the prefab on the variable Bullet in my gun script. Here is the error I get: MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:72) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:82) Gun+$Shoot$16+$.MoveNext () (at Assets/Gun.js:165) Here is the destroy script: #pragma strict function Start () { Destroy (this.gameObject, 5); } Thanks and please help!!!

Why does my bullet prefab get destroyed?

$
0
0
Hi. I'm making a first person shooter game. To shoot I have a gun script and it uses Instantiate. My var Bullet keeps going missing when ever my bullet is destroyed. If it doesn't make much sense here is the error: MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:72) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:82) Gun+$Shoot$16+$.MoveNext () (at Assets/Gun.js:165) Here is the bullet script and the destroy bullet script: //destroy bullet script function Update () { Destroy (this.gameObject, 5); } //Bullet script var BulletSpeed : float = 1500; function Start () { rigidbody.AddForce(transform.forward * BulletSpeed); } Did I do something wrong? Is there a better way to do this? Please help!!! Thanks, From, Anon.

after going to main menu my game wont play?

$
0
0
hi so i have my main menu and i click the play game then i can play game then i die and i have a start game event that allows me to go and play again fine. but when i use the pause function and go back to the main menu i click play game but i get this error MissingReferenceException: The object of type 'SkylineFarAway' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Component.get_transform () SkylineFarAway.GameStart () (at Assets/Skyline/SkylineFarAway.cs:71) GameEventManager.TriggerGameStart () (at Assets/Managers/GameEventManager.cs:12) GUIManager.Update () (at Assets/Managers/GUIManager.cs:18) so i think i have to DontDestroyOnLoad but im not sure what, when and how as i have never used this before. here is a link to the game in a development build for you to see whats happening and when [https://dl.dropboxusercontent.com/u/190836296/Test%203/Test%203.html][1] here is the code i am using in refrence to what the error is saying, **SKYLINE FAR AWAY** using UnityEngine; using System.Collections.Generic; public class SkylineFarAway : MonoBehaviour { public Transform prefab; public int numberOfObjects; public float recycleOffset; public Vector3 minSize, maxSize, minGap, maxGap; public float minY, maxY; public Material[] materials; public PhysicMaterial[] physicMaterials; public Booster booster; private Vector3 nextPosition; private Queue objectQueue; void Awake() { DontDestroyOnLoad(this); } void Start () { GameEventManager.GameStart += GameStart; GameEventManager.GameOver += GameOver; objectQueue = new Queue(numberOfObjects); for(int i = 0; i < numberOfObjects; i++){ objectQueue.Enqueue((Transform)Instantiate(prefab, new Vector3(0f, 0f, -100f), Quaternion.identity)); } enabled = false; } void Update () { if(objectQueue.Peek().localPosition.x + recycleOffset < Runner.distanceTraveled){ Recycle(); } } private void Recycle () { Vector3 scale = new Vector3( Random.Range(minSize.x, maxSize.x), Random.Range(minSize.y, maxSize.y), Random.Range(minSize.z, maxSize.z)); Vector3 position = nextPosition; position.x += scale.x * 0.5f; position.y += scale.y * 0.5f; Transform o = objectQueue.Dequeue(); o.localScale = scale; o.localPosition = position; objectQueue.Enqueue(o); nextPosition += new Vector3( Random.Range(minGap.x, maxGap.x) + scale.x, Random.Range(minGap.y, maxGap.y), Random.Range(minGap.z, maxGap.z)); if(nextPosition.y < minY){ nextPosition.y = minY + maxGap.y; } else if(nextPosition.y > maxY){ nextPosition.y = maxY - maxGap.y; } } private void GameStart () { nextPosition = transform.localPosition; for(int i = 0; i < numberOfObjects; i++){ Recycle(); } enabled = true; } private void GameOver () { enabled = false; } } **GAME EVENT MANAGER** using UnityEngine; using System.Collections; public static class GameEventManager { public delegate void GameEvent(); public static event GameEvent GameStart, GameOver; public static void TriggerGameStart(){ if(GameStart != null){ GameStart(); } } public static void TriggerGameOver(){ if(GameOver != null){ GameOver(); } } } **GUIMANAGER** using UnityEngine; public class GUIManager : MonoBehaviour { public GUIText gameOverText, instructionsText, boostsText, distanceText; private static GUIManager instance; void Start () { instance = this; GameEventManager.GameStart += GameStart; GameEventManager.GameOver += GameOver; gameOverText.enabled = false; } void Update () { if(Input.GetButtonDown("Jump")){ GameEventManager.TriggerGameStart(); } } private void GameStart () { gameOverText.enabled = false; instructionsText.enabled = false; enabled = false; } private void GameOver () { gameOverText.enabled = true; instructionsText.enabled = true; enabled = true; } public static void SetBoosts(int boosts){ instance.boostsText.text = boosts.ToString (); } public static void SetDistance(float distance){ instance.distanceText.text = distance.ToString("f0"); } } [1]: https://dl.dropboxusercontent.com/u/190836296/Test%203/Test%203.html

when unity upgrade from v3.5.6 to v4.0.1,the strange problem of MissingReferenceException

$
0
0
This is a script of "loading" which is on the "loading' prefab ![alt text][1],i printed "this" on the function of "awake"、“start” and "showload".This picture show the result of using the loading prefab at the first time, it shows no error,but the second time i do the same thing,it show an error. ![alt text][2]and the error show in many places, i public the Variable and it show exist in unity inspector,but print null. In a word, when the existd component trying to get or using IEnumerator ,it shows null。 [1]: /storage/temp/13814-qq图片20130801170919.jpg [2]: /storage/temp/13813-qq图片20130801170926.jpg

MissingReferenceException after destroying a prefab?

$
0
0
I'm sure this gets asked all the time but I can't seem to find an answer that works. So, brand new to Unity and gave development in general. I've created a generic GameObject to act as a spawn point when the user left clicks for a projectile prefab that gets destroyed after 5 seconds. This works, except after 5 seconds if I try to fire to again I get a MissingReferenceException saying The object of type 'GameObject' has been destroyed but you are still trying to access it. Somehow, it's removing that same projectile prefab from my GameObject that spawns them. Recap: -"Empty" GameObject with a script attached that spawns a Projectile prefab on mouse up -Prefab has a script attached that destroys a designated gameObject -After the prefab is destroyed, my mouse up no longer works and throws a MissingeReferenceException Script #1 (attached to part of the player's model): var power: float = 1000; var bulletPrefab: GameObject; function Update () { if (Input.GetMouseButtonUp(0)){ var pos: Vector3 = transform.position; bulletPrefab = Instantiate(bulletPrefab, transform.position, transform.rotation); bulletPrefab.rigidbody.AddForce(Vector3.forward * power); audio.Play(); } } Script #2 (attached to prefab): var ttl = 5; var thingToDestroy: GameObject; function Awake() { Destroy(thingToDestroy,ttl); } In both scripts, the GameObject variable is the same prefab and I can only assume this is my problem... But I have no idea what I should be doing? Also, in script #2, if I try simply Destroy(this, ttl) it doesn't destroy the object the script is attached to?

Remove dead enemies from array

$
0
0
Hello everyone. I'm working on a script that is meant to get all of the game objects in the scene that are tagged "Enemy", and then get the closest one to the player. When the enemy is killed and destroyed, the script gives me a missing reference exception error. I've tried searching up several possible solutions, such as checking if the enemy is null, but when I try them it usually gives me a warning that states "This method could return default value implicitly." at (13, 10). Being still very new to unity and things such as lists and arrays, I am unsure how to go about removing an enemy from the array when it is killed without running into these errors. Any helpful advice and references are much appreciated. Here is the Script : #pragma strict var player : Transform; var enemyNear : boolean; var targetedEnemy : GameObject; var closest : GameObject; var gos : GameObject[]; gos = GameObject.FindGameObjectsWithTag("Enemy"); function FindClosestEnemy() : GameObject { var distance = Mathf.Infinity; for (var go : GameObject in gos) { var enemyHealth : EnemyHealth; enemyHealth = go.GetComponent(EnemyHealth); if(enemyHealth.dead == true) { Destroy(go, 3); } if(go != null){ var diff = (go.transform.position - player.position); var curDist = diff.sqrMagnitude; if(curDist < distance) { closest = go; distance = curDist; } } return closest; } } function EnemyNear() { if(Vector3.Distance(closest.transform.position, player.position) < 10) { enemyNear = true; } else{ enemyNear = false; } } function Start () { targetedEnemy = null; FindClosestEnemy(); } function Update () { EnemyNear(); FindClosestEnemy(); gos = GameObject.FindGameObjectsWithTag("Enemy"); } This is the portion of the EnemyHealth script that the previous script accesses : function Dead(){ if(currentHealth <= 0){ currentHealth = 0; dead = true; } else{ dead = false; } } When the enemy is killed, two missing reference exceptions show up, one at line 46, and one at line 63. Sorry if my post got a little lengthy, thanks for your time.

Unity thinks my animation is not attached, but it is.

$
0
0
I am currently trying to make a soldier play an animation for a third person view for my multiplayer game. I had just imported the BootCamp soldier in for a placeholder, along with all the animations. In my script, I had wrote: anim.animation.CrossFade("Standing"); And apparently the Unity Console tells me the animation 'Standing' is not attached to the anim GameObject, but it clearly is. The complete error is the following: The animation state Standing could not be played because it couldn't be found! Please attach an animation clip with the name 'Standing' or call this function only for existing animations. UnityEngine.Animation:CrossFade(String) MultiplayerMulti:UpdateAnimations() (at Assets/_Scripts/MultiplayerMulti.js:56) MultiplayerMulti:Update() (at Assets/_Scripts/MultiplayerMulti.js:35) MultiplayerMulti line 56 is just the line I had provided above. ![alt text][1] [1]: /storage/temp/16300-screenshot.png As you can see, it is CLEARLY attached to my Soldier object. And yes, the soldier object IS SET AS THE GameObject for the anim variable! Any idea what the real problem is is appreciated. Thanks in advance, william9518

Destroyed object not comparing to null

$
0
0
I read that once a GameObject is destroyed, comparing it to null will return true. But I have this line of code which yields a `MissingReferenceException` saying the object has been destroyed but I'm still trying to access it: if (shootTarget != null) { // something } else { distance = shootTarget.GetDistance(this.transform.position); } Any ideas why? Any other checks I can perform? **Update:** Ok I found the reason, but not a solution. `shootTarget` is not a MonoBehaviour per se, it's an interface I created, but the MonoBehaviour implements the interface and the actual value of shootTarget is a MonoBehaviour that's been destroyed, so comparing it to null doesn't yield true... Any ideas how to work around this?

Removing from a list

$
0
0
I have a list of Transforms of enemies that a healer will heal. However, at times the player will kill and enemy and then I need to remove him from the list. I attempted the following approach: if (canHeal && !playerWithinRange ) { CheckDistance (); if (enemyToHealDistance < distanceCanHeal) { CheckNullList(); _healTarget = healGroup[Random.Range (0, healGroup.Count)]; goblinAlertEnemyHeal.enemyToHeal = _healTarget.gameObject; StartCoroutine ("HealTiming"); } else { CheckNullList(); _healTarget = healGroup[Random.Range (0, healGroup.Count)]; goblinAlertEnemyHeal.enemyToHeal = _healTarget.gameObject; _state = State.GotoEnemyToHeal; } } } int _listCntr; void CheckNullList() { _listCntr = 0; foreach (Transform bob in healGroup) { Debug.Log (bob.name); if (bob != null) return; else { healGroup.Remove (bob); healGroup.RemoveAt (_listCntr); } } } I am thinking that when the player kills the enemy and destroys the object, that position in the list should be null. But, it doesn't turn null and I'm getting the error : "MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it." at goblinAlertEnemyHeal.enemyToHeal = _healTarget.gameObject; I have a few ideas that might take a while to get it working, but I thought this approach would be the easiest. Does anyone know how I can turn that missing reference into something I can check for and remove from the list? thanks

Confusing "MissingReferenceException"

$
0
0
Fairly new to Unity, so I'm trying understand why I'm getting the following exception: MissingReferenceException: The object of type 'Missile' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Component.get_gameObject () (at C:/BuildAgent/work/d3d49558e4d408f4/artifacts/EditorGenerated/UnityEngineComponent.cs:171) Missile.GetCollider () (at Assets/Scripts/Projectiles/Missile.cs:108) Missile.Update () (at Assets/Scripts/Projectiles/Missile.cs:30) Here is the offending code: if(target != null) { Collider tc = target.GetCollider(); // This is line 30 from the exception ... And here is the GetCollider() method, line 108: public Collider GetCollider() { if(gameObject == null) return null; return gameObject.collider; } What's causing the exception?I thought a destroyed object should == null.

MissingReferenceException: The variable m_AnimatorController of 'AnimatorControllerTool' doesn't exist anymore.

$
0
0
How do I fix this error? I think I know why it keeps saying that, and it's probably because I deleted all of my animations and animators. Problem is, I don't know how to fix it. It's not really affecting anything in my game, but everytime I run it, this error just keeps popping up, and it's kind of annoying. Full error: MissingReferenceException: The variable m_AnimatorController of 'AnimatorControllerTool' doesn't exist anymore. You probably need to reassign the m_AnimatorController variable of the 'AnimatorControllerTool' script in the inspector. UnityEditor.Graphs.AnimationStateMachine.TransitionInspector.OnEnable () (at C:/BuildAgent/work/d3d49558e4d408f4/Editor/Graphs/UnityEditor.Graphs/AnimationStateMachine/TransitionInspector.cs:74) Thanks :)

MissingReferenceException sometimes causes long freeze before error message

$
0
0
MissingReferenceExceptions are sometimes causing Unity to freeze for a good while before showing an error message. This happens when I'm playing the game from within unity, not a build. I have run into this issue many many times over the past year. Basically, sometimes, if it encounters one of these errors while I'm playing, the game will freeze for a good long while. No mouse or interactivity with Unity at all. I just have to wait a minute or so, and then everything will suddenly un-freeze and continue as normal (with the error message showing up in the console). This does not happen every time for the same error. I encountered one today the caused the freeze. I then reproduced the exact same error again many times without the freeze. What is causing this temporary freezing, and is there a way for me to keep it from happening?

Pass a copy of a GameObject as variable to another script?

$
0
0
Hello... I'm trying to set up a teleport system that destroys the original object and then spawns a clone of that object at the exit portal. I don't want to just instantiate a prefab, as I want to keep changes to the object that happen during gameplay, and I don't want to simply move the object, because I have a spawner object that has a few useful functions like a delay and clearing the area of obstructions, etc. I want to pass the object in its current state as a variable, destroy the original, then have the spawner instantiate a clone after a delay. However, I'm getting the error: "MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object." Here is the code for my warp entrance object: #pragma strict var on : boolean = true; var teleportTarget : GameObject; var ballSpawn : GameObject; var yieldBefore : float = 00; var yieldAfter : float = 00; var preserveVelocity : boolean = true; var holdDuringDelay : boolean = true; var affectTag : String = "Ball"; private var teleporting : boolean = false; private var teleportedObject : GameObject; private var initialPosition : Vector3; private var incomingVelocity : Vector3; function Start () { } function Update () { if (teleporting && holdDuringDelay) { teleportedObject.transform.position = initialPosition; } } function OnTriggerEnter(objectCollision : Collider) { if ((objectCollision.gameObject.tag == affectTag) && (teleportedObject != objectCollision.gameObject) && (on)) { initialPosition = objectCollision.gameObject.transform.position; incomingVelocity = objectCollision.gameObject.rigidbody.velocity; teleport(objectCollision.gameObject); } } function teleport(object : GameObject) { teleporting = true; teleportedObject = object; yield WaitForSeconds(yieldBefore); var instantiatedObject = Instantiate(ballSpawn, teleportTarget.transform.position, teleportTarget.transform.rotation); if (instantiatedObject.GetComponentInChildren(BallSpawn)) { instantiatedObject.GetComponentInChildren(BallSpawn).spawnOnStart = true; instantiatedObject.GetComponentInChildren(BallSpawn).ball = teleportedObject; instantiatedObject.GetComponentInChildren(BallSpawn).spawnDelay = this.yieldAfter; instantiatedObject.GetComponentInChildren(BallSpawn).destroyAfterSpawn = true; if (preserveVelocity) { instantiatedObject.GetComponentInChildren(BallSpawn).spawnWithVelocity = this.incomingVelocity; } } teleportedObject = null; teleporting = false; DestroyOriginal(object); } function DestroyOriginal(object : GameObject) { Destroy(object); } Thanks in advance, smart people.

Missing reference exception

$
0
0
I've been reading though the forums, and haven't found anything that points to my particular issue... this is seriously killing me. I get this message in the console: "MissingReferenceException: The variable strafeleft of 'Asteroidlvl10' doesn't exist anymore. You probably need to reassign the strafeleft variable of the 'Asteroidlvl10' script in the inspector. UnityEngine.Transform.get_localPosition () Asteroidlvl10.Update () (at Assets/Scripts/Asteroidlvl10.js:98)" here is the snippet of code that it points too: if(Input.GetButton("a")) { mark = 0; speed = (movespeed/100) * distance; movedirection = strafeleft.localPosition * distance; movedirection.y = -12; movedirection.x = movedirection.x * 10; movedirection.z = movedirection.z * 10; transform.position = Vector3.MoveTowards(transform.position, movedirection, speed*Time.deltaTime); timerdrift = speed; speed1 = speed; } I have created an asteroid prefab, and added a strafeleft empty gameobject to my ship. this is also a prefab. when the game starts asteroids are instantiated infront of the ship off screen. They fly past the screen based on the speed dictated in another line of script. The problem is that when the a key is depressed instead of the asteroid moving towards the strafeleft position it complains that the refernce doesn't exist. in the instantiated clones of the asteroid prefab the gameobject strafeleft is missing. I assure you that the reference was made between the two prefabs and the prefabs are still intact in the project window. for the life of me I can't figure out why the asteroid prefab drops strafeleft, but doesn't drop any of the other references including ship which is a gameobject reference for the parent of strafeleft. I hope that makes sense, but I really need help with this one. I've been messing with it for a couple of days and can't figure it out.

MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.

$
0
0
I've a problema with my script, when player colision on contact with enemy it stop and says in console. MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. UnityEngine.Transform.get_position () (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/MetroEditorExtensionsGenerated/UnityEngineTransform.cs:28) FollowPlayerScript.Update () (at Assets/Scripts/FollowPlayerScript.cs:23) This is my script. using UnityEngine; using System.Collections; public class FollowPlayerScript : MonoBehaviour { public Transform Objetivo; public float Velocidad= 3; //Desactivado por ser utilizado en 2D //public float velocidadRotacion= 3; public Transform myTransform; void Awake (){ myTransform = transform; } void Start (){ Objetivo = GameObject.FindWithTag("Player").transform; } void Update (){ //rotacion para mirar al jugador myTransform.position = Vector2.MoveTowards(myTransform.position,Objetivo.position, Velocidad * Time.deltaTime); //Se mueve directo al jugador myTransform.position += myTransform.forward * Velocidad * Time.deltaTime; } }

How to make MonoDevelop to break when a MissingReferenceException occurs?

$
0
0
I have an script that creates and deletes objects, I also have a coroutine that makes changes on those objects over a period of time. In theory at least, it is not possible for an object to be deleted before the coroutine finishes with it... Everything works fine during a variable period of time, however sporadically I'm getting a **MissingReferenceException**... mening 2 posibilites: 1) the object being processed in the coroutine was deleted... or 2) under some circumstances I'm passing a wrong value to the coroutine... The problem is I won't be able to tell unless I can make MonoDevelop to stop exactly when the exception occurs. In the **Exceptions** window (accesible from Run/Exceptions...) I cannot see something like: "**UnityEngine.MissingReferenceException**" or "**System.MissingReferenceException**" or anything a like... so how do I tell it to stop on this particular exception??? The only other possibilty I see right now would be to test with a function that detects deleted objects or wrong references, but... does such function exist???

How do you destroy a prefab, but not the original object?

$
0
0
I've been working on a mobile game for a little while, and up until recently my game had been working correctly. For some reason, however, the enemies (which are supposed to be prefabs) have started to destroy *original* gameObject instead of themselves. The enemies are disappearing like they should, but when I try to create a new enemy, the console is logging: MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. This is the code where the enemies are destroyed: void Update () { time = time + Time.deltaTime; gameObject.GetComponent().color = new Color(current.r, current.g, current.b, current.a * (1 - (time / 5))); if (time >= 5) { Destroy(gameObject); score.GetComponent().StreakEnd(); } } public void DestroySelf () { Destroy(gameObject); } I create new enemies by calling `Instantiate(enemy)`, and during runtime I can see the original enemy being removed. I'm not that used to Unity or c#, so could you be thorough with your answer? Thanks in advance!

Game Unit with Multiple Child Objects - "Garage Scene"

$
0
0
Hello ladies & gents, Let's say I have a TANK unit (for in-game use) with the following object hierarchy: Tank Body (GameObject) |__ Turret Mount (empty) |__ Turret (GameObject) |__ Gun Mount (empty) |__ Gun (GameObject) So, this Tank unit has three moving (and visible) parts to it; namely, Tank Body, Turret, and Gun. And I want the 3D representation of this tank shown in a garage-like setting where the player can pick and choose from an array of different parts. Of course, the player's selection will be immediately be reflected to the 3D tank model on the same screen. Now, I got it to a point where the tank is showing up just fine. But, choosing a different option for, say, the turret (or any other part of the tank) has proven to be more challenging than I expected. The main problem is that when I display the newly selected mesh, the mesh from the previous selection remains in place. So, I used the Destroy method to get rid of the previous mesh. But then, I ran into this error - "MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it." And I have been trying to find a workaround to no avail. Is there a cleaner/smarter way to cycle through different meshes and display only one at any given time? Just to mind you, if I am dealing with one-part mesh, it wouldn't have been an issue. My problem is rather unique in the way that the Tank unit is structured in a hierarchical manner as already mentioned above. Any insight/help will be much appreciated!

GameObject still destroyed after reloading level.

$
0
0
I'm on a team that's making a short game that consists of two scenes: the start screen, and the game itself. The start screen has a Play button that when clicked, loads the scene that contains the game. When the game ends (on a win, loss, etc.) the main menu is loaded again. If you click Play a second time however, I get the following error:"MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it." I don't understand how this is possible. I thought that when you load a level, everything is restored to its initial state. Is that not the case? And if it is, why would it work the first time, but not the second time? We never explicitly tell Unity to destroy the gameobject, so I'm assuming it's getting destroyed (along with everything else) when we load the main menu scene, and then for some reason it isn't getting recreated when we load the game scene the second time. The weird thing is though, when I pause the game and look at the scene, the gameobject in question is still there in the hierarchy. Does anyone know what could be causing this? Thanks!

When the original enemy dies, the spawns stop (javascript)

$
0
0
Ok I'm not sure what is going on here. Although I am fairly new to this stuff, so thats most likely the problem. So this is how my project is set up right now. I have a Game Object Cube with tag "enemy" that acts as the enemy, its script is to chase after the player. I also have a Game Object Empty with tag "spawnpoint" that spawns copies of the enemy object. The problem is that when I kill the original object is stops spawning the enemies from the spawn points and I get a MissingReference Transform Destroyed error. It also happens when if I shot the enemy (it takes 2 shots to kill) and then leave it alone all the spawns only have to be shot once to be killed. I initially thought that all I had to do was create an enemy prefab, but that doesn't work because one of the enemies variables is for searching for the player GameObject, so I can't (more like don't know how) to pass that into the prefab. So I started thinking it may just be the code that needs to be changed, but I'm not exactly sure what to change to get it to work. Below are my EnemyScript and SpawnScript.EnemyScript var player : GameObject; var speed : float = .5; public var enemyHealth : int = 2; function Start() { player = GameObject.FindGameObjectWithTag("Player"); //if(!player) //Debug.Log("Could Not Find The Player"); } function Update() { if(!player) return; var distance = Vector3.Distance(player.transform.position, transform.position); if(distance < 100) { //Debug.Log("Player is close by"); var delta = player.transform.position - transform.position; delta.Normalize(); var moveSpeed = speed * Time.deltaTime; transform.position = transform.position + (delta * moveSpeed); } else { //Debug.Log("Not close enough" + distance); } if(enemyHealth <= 0) { Level1InfoScript.playerScore += 100; Destroy(gameObject); } } function OnCollisionEnter(otherObject : Collision) { if(otherObject.gameObject.tag == "bullet") { enemyHealth --; } }
SpawnScript var enemyPrefab: Transform; var maxEnemiesAlive: int = 1; var maxEnemies: int = 30; private var totalEnemies: int; private var spawnPoints: GameObject[]; private var player: Transform; var fNextSpawn : float = 0.0; var fSpawnInterval : float = 5.0; var iMaxEnemies : int = 10; var iTotalEnemies : int = 0; function Start() { fNextSpawn = Time.time + fSpawnInterval; spawnPoints = GameObject.FindGameObjectsWithTag("spawnpoint"); player = GameObject.FindWithTag("Player").transform; totalEnemies = maxEnemies; // define how many enemies the level has } function Update() { if(Time.time > fNextSpawn && iTotalEnemies < iMaxEnemies) { fNextSpawn = Time.time + fSpawnInterval; spawnEnemy(); } // when some enemy is killed and total enemies isn't zero yet... if (transform.childCount < maxEnemiesAlive && totalEnemies > 0) { // draw a random spawn point: var pos = spawnPoints[Random.Range(0, spawnPoints.length)].transform.position; // find a rotation to look at the player: var rot = Quaternion.LookRotation(player.position - pos); // create the new enemy facing the player: var enemy = Instantiate(enemyPrefab, pos, rot); // child it to Enemies (this object): enemy.parent = transform; totalEnemies--; // decrement the remaining enemies } } function spawnEnemy() { Instantiate(enemyPrefab, transform.position, Quaternion.identity); iTotalEnemies++; }
Viewing all 208 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>