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

[Resolved: Had to remove messenger listeners]When Instantiating a prefab, after a previous clone of said prefab has been destroyed, I get a "MissingReferenceException".

$
0
0
So I have a savefile menu, which has a UI Panel with this script (called "SavePanel") on it: for(int i = 0; i < (GameController.current.saveFileNames.Count + 1); i++) { GameObject saveClone = Instantiate(saveFilePrefab); saveClone.transform.SetParent(gameObject.transform, false); //helps to use this when dealing with UI objects, as it avoids scaling issues. saveClone.GetComponent().slot = i; Messenger.Broadcast(Broadcasters.SetupSaveFile.ToString()); } inside the OnEnable() method. saveFilePrefab is a prefab which is basically a Button with this script (called "SaveFileBtn") on it: public string saveFileName; public int slot; public bool isLoadBtn; private Button btn; private void Awake() { btn = GetComponent

GameObject reference lost between functions

$
0
0
My gameobject reference gets lost between functions. The gameobject reference comes from a collider with a separate OnTriggerEnter script. That script works fine, and the info reaches the PlayerWarning function. After that, the target variable gets set back to null. I also tried putting the part that needs the reference in the PlayerWarning function, but then I got the error, that the NavMeshAgent was missing a reference to the object. The NPC still moved with the NavMeshAgent but it didn't register it in the function. using UnityEngine; using System.Collections; public class AIBasic : MonoBehaviour { public bool hostile; public bool shy; private Animation anim; private NavMeshAgent agent; private Vector3 destination; private Vector3 position; private float distToTar; [HideInInspector] public GameObject target = null; // Use this for initialization void Awake () { anim = GetComponent(); agent = GetComponent(); position = transform.position; InvokeRepeating ("NewTargetStandard", 1f, 4f); target = null; } // Update is called once per frame void Update () { if (agent.remainingDistance <= agent.stoppingDistance) { if (agent.hasPath || agent.velocity.sqrMagnitude == 0f) { if (!target) anim.Play("Idle"); } } if (hostile) { if (target) { Debug.Log (target.ToString()); distToTar = (Vector3.Distance(transform.position, target.transform.position)); CancelInvoke(); destination = target.transform.position; agent.destination = destination; if (distToTar >= 1.5f) anim.Play("Run"); } } else if (shy) { //hide from player until attacked } } void NewTargetStandard () { destination = new Vector3 (Random.Range(position.x - 13f, position.x + 13f), 0f, Random.Range(position.z - 13f, position.z + 13f)); agent.destination = destination; anim.Play ("Walk"); } public void PlayerWarning (GameObject player) { target = player; } public void StartUpProtocol (Vector3 pos) { position = pos; } } EDIT: Found a workaround to the problem by giving the NPC a collider, with which to detect the player inside the same script. It works and all, but I'll keep the problem here open, because someone else might need this info or something.

Odd collision behaviour with If/while statement

$
0
0
*//That boring intro* Hi I have a bit of a problem with a script, I have a cannon that fires 20 bullets per second, for a second and then stops. I've tested this with different amounts of rounds per second ranging from 1, to 2, up to 120 and I'm getting some weird behaviour from an if/while statement: var health : int; function OnCollisionEnter(col : Collision) { //print (col.gameObject); var primaryGun = gameObject.Find("bullet(Clone)"); while (col.gameObject == primaryGun) { var instance = col.gameObject.GetComponent(impact); var damage : int = instance.primaryBulletDamage; //print (damage); health = health - damage; print (health); yield; } if (health <= 0) { print ("I'm Dead"); } } *//The reason you hate me* The reason I'm using an if/while type statement is because I want to create different bullet types which are essentially duplicate prefabs with some additional style changes and the parameters are different including damage, hence why the script is asking what hit it for the damage int from the collision object. *//The actual problem* When I use the first print, outside of the while statement, without it's comment: print (col.gameObject); the correct amount of collisions is printed to the console per bullet fired. However in my While loop it repeats the print function multiple times. I think this is something to do with the game refreshing each frame producing all the console prints. Without the yield; the script crashes unity/the game, also, adding WaitForSeconds(0.1); helps but it's inaccurate and sometimes still throws a good 10 prints or so for each 1 collision. I've tried the If statement instead of while however this has the reverse effect, it only registers 1 hit per few seconds. In order for the hit to count I have to fire, wait for my original bullet(Clone) to destroy itself then it will count the next hit. Furthermore, my final error is that, "The object of type 'BoxCollider' has been destroyed but you are still trying to access it." I know this is to do with the bullet destroying script that deletes the clones over time. However I don't know how to get rid of this error, the log hints at telling the script to check for null. *//The afterword* I hope there is someone who can help me understand better why this is happening and if there is a fix and what it might be (: also, sorry for my poor sense of humour at this time in the morning with all the cheesy *//comments...* Thanks for reading -Axi5. EDIT: I just retried the first print as I mentioned earlier in this post and even though it gave 1-2 prints per 1 bullet (1 bullet sometimes counting as two or rarely, more collisions) it still didn't give nearly as many prints as while and yet it was still more than if. So I still consider this question valid despite my original test being a little off (I'll play with the collision boxes setup and see if it improves things).

Missing Reference Exception

$
0
0
Hi guys. I am trying to make a game object, in this case a battery, spawn around the room. i have created a cylinder with a battery texture and put it in the scene. using UnityEngine; using System.Collections; public class Battery_Script : MonoBehaviour { public Transform[] spawns; void Start () { InvokeRepeating("Spawn", 5 , 5); } void Spawn() { int i = Random.Range (0,spawns.Length); transform.position = spawns[i].position; transform.rotation = spawns[i].rotation; } } i have attached this script to it and i keep getting the error message "MissingReferenceException: The object of type 'Battery_Script' 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. UnityEditor.GenericInspector.GetOptimizedGUIBlock (Boolean isDirty, Boolean isVisible, UnityEditor.OptimizedGUIBlock& block, System.Single& height) (at C:/buildslave/unity/build/Editor/Mono/Inspector/GenericInspector.cs:19) UnityEditor.InspectorWindow.FlushOptimizedGUIBlock (UnityEditor.Editor editor) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1430)" i think its only being called once because collapse isn't checked on the console so i assume its happening on start. i don't destroy it at any point so i'm stumped. i'm sure i'm missing something obvious :) so thanks in advance.

Missing reference on loadLevel when the object exist...why? :(

$
0
0
When I call LoadLevel(level), every level have an object called Traveller, I suppose that on-loading, the last level was destroyed and new level load all object that contain the new scene, I dont undestand why getComponent cant find my script attached to my Traveller object, if this exist in the new scene. here is an screenshot: void Start () { traveller = GameObject.FindGameObjectWithTag("Traveller").transform; travellerController = traveller.GetComponent (); ![alt text][1] [1]: /storage/temp/54929-screenshot.jpg

A really odd MissingReferenceException

$
0
0
I was absent from Unity for a while now and I am currently doing the tutorials to get myself back into the game. When I was testing my scene, I encountered a MissingReferenceException. I check my codes for a few times but I just cannot get rid of the Exception. After much frustrations, I created a **DefaultScript** with no modification made on it; I ran the scene and the same error message pops back up again. ![alt text][1] Any thoughts on this issue? [1]: /storage/temp/55782-unityss-missingreferenceexception.png

Annoying MissingReferenceException with Interfaces and Monobehavior

$
0
0
So I am somehow getting a weird misisng reference exception. I have a script "Block" that doesn't inherit from Monobehavior, but it links to an "IBlockScript" interface which is also a Monobehavior. The issue here is that when the Monobehavior side is destroyed, the Interface side still isn't null. I can try to check if the Script is null (but that always returns false even if it was destroyed) public IBlockScript Script { get; private set;} public GameObject gameObject { get { //SOMEHOW Script is NEVER null even when it's Monobehavior is destroyed... //so this check is always false. // and the code pops an MissingRefenceException when it gets to Script.gameobject if(Script == null || ReferenceEquals(Script,null)) return null; try { return Script.gameObject; } catch(MissingReferenceException e) { return null; } } } public Transform transform { get { if(gameObject==null) return null; return gameObject.transform; } } I'm forced to using try/catch in order to return properly and I reeaaaallly don't like doing that, is there a better way of doing this? This error typically happens when I stop the player or load a new level (when the Iblockscripts are getting unloaded)

Receiving a missing reference exception error but everything is still there.

$
0
0
I keep getting the below error at the start of the game saying that I have destroyed a script but am trying to access it. But when I look in my hierarchy it's still there. I removed every script that wrote to that object but it's still giving me this error. ![alt text][1] [1]: /storage/temp/58650-error.png

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

$
0
0
Ok so lots and lots of instantiations are happening here... I'm making a 2D Star Wars themed game, and I have a lightsaber that is spawning drones (at random locations). The drones, then, are spawning lasers. I have it set so that the lasers stay on the screen until you deflect them, and then they are destroyed as soon as they hit an edge. Everything is working as I want it to, but for some reason it still throws me this error whenever I start or stop the program. Here's the code that spawns the lasers, which lies in each instantiation of the drones: using UnityEngine; using System.Collections; public class spawnLaser : MonoBehaviour { public GameObject originalLaser; public float minWaitTime = 5f; public float maxWaitTime = 15f; void Start(){ StartCoroutine(waitAndSpawn()); } void spawn () { GameObject clone = Instantiate (originalLaser); clone.SetActive (true); clone.transform.position = transform.position; } IEnumerator waitAndSpawn(){ while (true) { yield return new WaitForSeconds (Random.Range (minWaitTime, maxWaitTime)); spawn (); } } } And here's the code in each of the lasers (I've taken out some large, irrelevant chunks of code to make it easier to read) using UnityEngine; using System.Collections; public class laser : MonoBehaviour { public float speed; private float vertExtent; private float horzExtent; public GameObject self; public bool deflected; public bool destroyMe; void Awake () { deflected = false; destroyMe = false; } void Start () { vertExtent = Camera.main.orthographicSize; horzExtent = vertExtent * Screen.width / Screen.height; rotate(); } void OnCollisionEnter2D (Collision2D col) { if (col.gameObject.name == "Lightsaber") { //code to make it deflect here deflected = true; } } void Update () { //code to make it move in the right direction here checkWalls (); } void rotate (){ //a bunch of code went here } void checkWalls(){ if (transform.position.x > horzExtent) { if(deflected){ destroyMe = true; Destroy(self); } else { transform.position = new Vector2(-horzExtent, transform.position.y); } } //else if... for the other 3 walls } } Like I said, it's not really affecting anything as far as I can tell, but I don't want that error there and I just can't seem to find the source of the problem!

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

$
0
0
using UnityEngine; using System.Collections; using UnityStandardAssets.ImageEffects; public class GameMaster : MonoBehaviour { public static GameMaster gm; void Awake () { if (gm == null) { gm = GameObject.FindGameObjectWithTag ("GM").GetComponent(); } } public Transform playerPrefab; public Transform spawnPoint; public float spawnDelay = 2; public Transform spawnPrefab; public CameraShake cameraShake; void Start() { if (cameraShake == null) { Debug.LogError("No camera shake referenced in GameMaster"); } } public IEnumerator _RespawnPlayer () { GetComponent().Play (); yield return new WaitForSeconds (spawnDelay); Instantiate (playerPrefab, spawnPoint.position, spawnPoint.rotation); GameObject clone = Instantiate (spawnPrefab, spawnPoint.position, spawnPoint.rotation) as GameObject; Destroy (clone, 3f); } public static void KillPlayer (Player player) { Destroy (player.gameObject); gm.StartCoroutine(gm._RespawnPlayer()); } public static void KillEnemy (Enemy enemy) { gm._KillEnemy(enemy); } public void _KillEnemy(Enemy _enemy) { GameObject _clone = Instantiate(_enemy.deathParticles, _enemy.transform.position, Quaternion.identity) as GameObject; Destroy(_clone, 5f); cameraShake.Shake(_enemy.shakeAmt, _enemy.shakeLength); Destroy(_enemy.gameObject); } } **strong text** MY QUESTION : How to Fix? ERROR : 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.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineObjectBindings.gen.cs:63) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:80) GameMaster+c__Iterator10.MoveNext () (at Assets/Scripts/GameMaster.cs:34)

MissingReferenceException when locking inspector tab

$
0
0
If I lock the inspector on a gameobject with any script attached I get a "MissingReferenceException" whenever I enter or leave play mode. To be clear, the error occurs once when hitting play, and again when stopping play. If there is no script on the gameobject I do not get any error. The script does not matter. When I create a new, blank script I still get the error. I've tried restarting and using different gameobjects. Here is the error: > MissingReferenceException: The object> of type 'someScript' 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.> UnityEditor.GenericInspector.GetOptimizedGUIBlock> (Boolean isDirty, Boolean isVisible,> UnityEditor.OptimizedGUIBlock& block,> System.Single& height) (at> C:/buildslave/unity/build/Editor/Mono/Inspector/GenericInspector.cs:19)> UnityEditor.InspectorWindow.FlushOptimizedGUIBlock> (UnityEditor.Editor editor) (at> C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1430)> UnityEditor.InspectorWindow.FlushOptimizedGUI> () (at> C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1420)

Unity 5.1.0 Space Shooter Tutorial. Bolt object destroyed by boundary at start.

$
0
0
I've had no trouble following the tutorial up until I added the DestroyByBoundary object. The problem is, when the game first starts a single shot is fired from the ship. This makes since as velocity is added to the bolt at start. But then it is destroyed by the boundary and when I try to fire again 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:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineObjectBindings.gen.cs:60) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:80) PlayerController.Update () (at Assets/Scripts/PlayerController.cs:28)" I've double checked the scripts against the ones in the "Done" folder, but everything seems as it should be. Why is that first shot firing and destroying the bolt object? Why can I not clone further shots?

Weird MissingReferenceException

$
0
0
Iam getting a weird error that i cannot figure out; **The error** MissingReferenceException: The object of type 'RUI_ArrayButton' 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. RUI_ArrayButton.ChangeImage (UnityEngine.Texture2D _newimage) (at Assets/Resources/RUI/Scripts/RUI_ArrayButton.cs:17) RUI_TabController.RefreshSprite () (at Assets/Resources/RUI/Scripts/RUI_TabController.cs:88) RUI_TabController.RefreshTabamount () (at Assets/Resources/RUI/Scripts/RUI_TabController.cs:137) RUI_TabEditor.TabamountEditor (.RUI_TabController _tabcontroller) (at Assets/Scripts/Editor/RUI/RUI_TabEditor.cs:65) RUI_TabEditor.OnInspectorGUI () (at Assets/Scripts/Editor/RUI/RUI_TabEditor.cs:20) **When does this happen?** When i decrease the tabamount by any amount it throws this error. Other than this error everything seems to be working fine but i dont think unity throws this error for nothing. **The code thats causing this error:** public void ChangeImage(Texture2D _newimage){ if (ButtonImage == null) { Debug.Log (gameObject); ButtonImage = gameObject.GetComponent (); } ButtonImage.texture = _newimage; gameObject.GetComponent ().sizeDelta = new Vector2 (_newimage.width, _newimage.height); } **Some more code (RUI_TabController class)** public void RefreshTabamount(){ if (Tabobjects.Length != Tabamount) { RefreshCheck (); if (Tabobjects.Length > Tabamount) { int AmountToDestroy = Tabobjects.Length - Tabamount; for (int i = 0; i < AmountToDestroy; i++) { DestroyImmediate (Tabobjects [i]); } Tabobjects = gameObject.GetAllChildren (); } if (Tabobjects.Length < Tabamount) { int AmountToInstantiate = Tabamount - Tabobjects.Length; for (int i = 0; i < AmountToInstantiate; i++) { GameObject tab = new GameObject (); GameObject text = new GameObject (); tab.transform.SetParent (gameObject.transform); text.transform.SetParent (tab.transform); tab.name = "Tab" + i; text.name = "Text"; tab.AddComponent (); Text tabtext = text.AddComponent (); tabtext.raycastTarget = false; RectTransform tabrect = tab.GetComponent (); tabrect.localScale = new Vector3 (1, 1, 1); tabrect.anchorMax = new Vector2 (0, 0); tabrect.anchorMin = new Vector2 (0, 0); RectTransform textrect = text.GetComponent (); textrect.anchoredPosition = new Vector2 (0.0f, -0.75f); } Tabobjects = null; Tabobjects = gameObject.GetAllChildren (); RA = null; RA = new RUI_ArrayButton[Tabobjects.Length]; for (int i = 0; i < Tabobjects.Length; i++) { RA [i] = Tabobjects [i].GetComponent (); } } RefreshSpacing (); RefreshText (); RefreshSprite (); } } **More code (the custom editor function that is called from the OnInspectorGUI method)** private void TabamountEditor(RUI_TabController _tabcontroller){ GUILayout.BeginHorizontal (); EditorGUILayout.LabelField ("Tabs",GUILayout.Width (60)); EditorGUI.BeginChangeCheck(); _tabcontroller.Tabamount = EditorGUILayout.IntSlider (_tabcontroller.Tabamount,1,100, GUILayout.Width (200)); GUILayout.EndHorizontal (); if (EditorGUI.EndChangeCheck ()) { _tabcontroller.RefreshTabamount (); } }

missing reference exception random maze generator

$
0
0
im getting a null reference exception when ever i destroy my gameobject then respawn it. i have a random maze generator which i made from a tutorial and made a few alteration to it the first being that it can increase it size and the second is that i can make alteration in the game manager rather then going directly to the maze prefab which is later instantiated in and destroy when i reset the maze. using UnityEngine; using System.Collections; public class GameManager : MonoBehaviour { public Maze mazePrefab; private Maze mazeInstance; public IntVector2 sizeGM; public GameObject mazeGO; public Maze script; private float mazeScale; public float scaleUp = 5f; void Start () { StartCoroutine(BeginGame ()); } void OnDestroy(){ StopAllCoroutines (); } private IEnumerator BeginGame(){ while(true){ mazeInstance = Instantiate (mazePrefab) as Maze; mazeGO = GameObject.FindGameObjectWithTag ("MazeSetup"); script = mazeGO.GetComponent ("Maze") as Maze; script.size = (sizeGM); StartCoroutine (mazeInstance.Generate ()); while (!Input.GetKeyDown (KeyCode.Space) && !mazeInstance.IsFinished()) { yield return null; } Debug.Log ("startScale"); Vector3 mazeScale = mazeGO.transform.localScale; mazeScale.x += scaleUp; mazeScale.y += scaleUp; mazeScale.z += scaleUp; mazeGO.transform.localScale = mazeScale; Debug.Log ("finishScale"); Destroy (mazeInstance.gameObject); } } } it also destroy and recreate the maze endlessly but doesnt scale the maze up

gameobject has been destroyed you are still trying to access it

$
0
0
im getting this message and im sure its because when my player gets hit he loses all his gems, the gems flash and then there destroyed, following this message i get an odd message about matrix stack full depth reached but i cant see how theyre related, any how im instantiating a prefab making it flash using materials for a couple seconds and then destroying themso my error is because the flashing is still happening after there destroyed but i am already checking if the gameobject is null can anybody give me a hand? here is half the code to make the gems flash void coinFlash() { newCoins = GameObject.FindGameObjectsWithTag("newcoins"); if (newCoins != null) { for (var i = 0; i < newCoins.Length; i++) { //coinPrefab.GetComponent().sharedMaterial.color = new Color32(250, 250, 210, 0); coinPrefab.GetComponent().sharedMaterial = goldtrans; } } }

Destroying GameObject while in Inspector = MissingReferenceException

$
0
0
I have a behaviour that just acts as a data container that's on one of my models. If I select that game object so that the script is displayed in the behaviour, and tweak the model import settings and click "Apply" I get an error (thrown repeatedly until I make the inspector focus on another object). MissingReferenceException: The object of type 'MyComponent' 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. UnityEditor.Editor.IsEnabled () (at C:/buildslave/unity/build/Editor/Mono/Inspector/Editor.cs:589) UnityEditor.InspectorWindow.DrawEditor (UnityEditor.Editor editor, Int32 editorIndex, Boolean rebuildOptimizedGUIBlock, System.Boolean& showImportedObjectBarNext, UnityEngine.Rect& importedObjectBarRect) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1151) UnityEditor.InspectorWindow.DrawEditors (UnityEditor.Editor[] editors) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1028) UnityEditor.InspectorWindow.OnGUI () (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:352) System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:222) Now, my asset processor is updating a prefab, copying that component, and then calling DestroyImmediate, which I'm sure is why the error is being generated. However, I can find no way to protect against this. Perhaps some way to just clear the selected object so that the inspector isn't on it?

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 .

$
0
0
I am trying to carry over the player over to the next scene. I am having a problem. The player is going over to the scene to soon and I notice this message displays at the bottom 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_rotation () (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineTransformBindings.gen.cs:94) Opsive.ThirdPersonController.ControllerHandler.FixedUpdate () (at Assets/Third/Scripts/Character/ControllerHandler.cs:249) I help on trying to stop the scene switching . Here is my script : using UnityEngine; #if ENABLE_MULTIPLAYER using UnityEngine.Networking; #endif using Opsive.ThirdPersonController.Abilities; using Opsive.ThirdPersonController.Input; using System.Collections.Generic; namespace Opsive.ThirdPersonController { /// /// Acts as an interface between the user input and the RigidbodyCharacterController. /// [RequireComponent(typeof(RigidbodyCharacterController))] #if ENABLE_MULTIPLAYER public class ControllerHandler : NetworkBehaviour #else public class ControllerHandler : MonoBehaviour #endif { private enum AimType { Down, Toggle, None } [Tooltip("Specifies if the character should aim when the button is down, toggled, or not at all")] [SerializeField] private AimType m_AimType; // Internal variables private float m_HorizontalMovement; private float m_ForwardMovement; private Quaternion m_LookRotation; private List m_AbilityInputComponents; private List m_AbilityInputNames; private bool m_AllowGameplayInput = true; private List m_AbilityInputName; private List m_AbilityInputEvent; // SharedFields private SharedMethod m_IsAI = null; // Component references private GameObject m_GameObject; private Transform m_Transform; private CapsuleCollider m_CapsuleCollider; private RigidbodyCharacterController m_Controller; private Camera m_Camera; private Transform m_CameraTransform; /// /// Cache the component references and register for any network events. /// private void Awake() { m_GameObject = gameObject; m_Transform = transform; m_CapsuleCollider = GetComponent(); m_Controller = GetComponent(); DontDestroyOnLoad(gameObject); #if ENABLE_MULTIPLAYER EventHandler.RegisterEvent("OnNetworkStopClient", OnNetworkDestroy); #endif } /// /// Register for any events that the handler should be aware of. /// private void OnEnable() { m_Controller.RootMotionForce = Vector3.zero; m_Controller.RootMotionRotation = Quaternion.identity; EventHandler.RegisterEvent(m_GameObject, "OnDeath", OnDeath); } /// /// Unregister for any events that the handler was registered for and stop the character from moving. /// private void OnDisable() { EventHandler.UnregisterEvent(m_GameObject, "OnDeath", OnDeath); } /// /// Initializes all of the SharedFields and default values. /// private void Start() { SharedManager.InitializeSharedFields(m_GameObject, this); EventHandler.RegisterEvent(m_GameObject, "OnAllowGameplayInput", AllowGameplayInput); EventHandler.RegisterEvent(m_GameObject, "OnAbilityRegisterInput", RegisterAbilityInput); EventHandler.RegisterEvent(m_GameObject, "OnAbilityUnregisterInput", UnregisterAbilityInput); if (!m_IsAI.Invoke()) { InitializeCamera(); } // An AI Agent does not use PlayerInput so Update does not need to run. PointClick is updated within the PointClickControllerHandler. enabled = !m_IsAI.Invoke() && m_Camera != null && m_Controller.Movement != RigidbodyCharacterController.MovementType.PointClick; } /// /// Initializes the camera components. /// Tue if the camera initialized successfully. /// public bool InitializeCamera() { m_Camera = Utility.FindCamera(); if (m_Camera == null) { return false; } m_CameraTransform = m_Camera.transform; CameraMonitor cameraMonitor; if ((cameraMonitor = m_Camera.GetComponent()) != null) { #if ENABLE_MULTIPLAYER // While in a networked game, only assign the camera's character property if the current instance is the local player. Non-local players have their own // cameras within their own client. if (cameraMonitor.Character == null && isLocalPlayer) { #else if (cameraMonitor.Character == null) { #endif cameraMonitor.Character = gameObject; } } return true; } /// /// Accepts input and will perform an immediate action (such as crouching or jumping). /// private void Update() { #if ENABLE_MULTIPLAYER if (!isLocalPlayer) { return; } #endif if (!m_AllowGameplayInput) { m_HorizontalMovement = m_ForwardMovement = 0; return; } // Detect horizontal and forward movement. if (m_Controller.Movement != RigidbodyCharacterController.MovementType.PointClick) { m_HorizontalMovement = PlayerInput.GetAxisRaw(Constants.HorizontalInputName); m_ForwardMovement = PlayerInput.GetAxisRaw(Constants.ForwardInputName); } // Should the controller aim? if (m_AimType == AimType.Down) { if (PlayerInput.GetButtonDown(Constants.AimInputName, true)) { m_Controller.Aim = true; } else if (m_Controller.Aim && !PlayerInput.GetButton(Constants.AimInputName, true)) { m_Controller.Aim = false; } } else if (m_AimType == AimType.Toggle) { if (PlayerInput.GetButtonDown(Constants.AimInputName)) { m_Controller.Aim = !m_Controller.Aiming; } } #if ENABLE_MULTIPLAYER if (isLocalPlayer) { CmdSetInputParameters(m_HorizontalMovement, m_ForwardMovement, m_LookRotation); } #endif // Abilities can have their own input. if (m_AbilityInputName != null) { for (int i = 0; i < m_AbilityInputName.Count; ++i) { if (PlayerInput.GetButtonDown(m_AbilityInputName[i])) { #if ENABLE_MULTIPLAYER CmdExecuteAbilityEvent(m_AbilityInputEvent[i]); // Execute the method on the local instance. Use isClient instead of isServer because the client and server may be the same instance // in which case the method will be called with the Rpc call. if (!isClient) { #endif EventHandler.ExecuteEvent(m_GameObject, m_AbilityInputEvent[i]); #if ENABLE_MULTIPLAYER } #endif } } } // Start or stop the abilities. if (m_AbilityInputComponents != null) { for (int i = 0; i < m_AbilityInputComponents.Count; ++i) { if (PlayerInput.GetButtonDown(m_AbilityInputNames[i])) { // Start the ability if it is not started and can be started when a button is down. Stop the ability if it is already started and // the stop type is button toggle. A toggled button means the button has to be pressed and released before the ability can be stopped. if (!m_AbilityInputComponents[i].IsActive && m_AbilityInputComponents[i].StartType == Ability.AbilityStartType.ButtonDown) { #if ENABLE_MULTIPLAYER CmdTryStartAbility(i); // Execute the method on the local instance. Use isClient instead of isServer because the client and server may be the same instance // in which case the method will be called with the Rpc call. if (!isClient) { #endif m_Controller.TryStartAbility(m_AbilityInputComponents[i]); #if ENABLE_MULTIPLAYER } #endif } else if (m_AbilityInputComponents[i].StopType == Ability.AbilityStopType.ButtonToggle) { #if ENABLE_MULTIPLAYER CmdTryStopAbility(i); // Execute the method on the local instance. Use isClient instead of isServer because the client and server may be the same instance // in which case the method will be called with the Rpc call. if (!isClient) { #endif m_Controller.TryStopAbility(m_AbilityInputComponents[i]); #if ENABLE_MULTIPLAYER } #endif } } else if (PlayerInput.GetButtonUp(m_AbilityInputNames[i])) { // Stop the ability if the ability can be stopped when the button is up. if (m_AbilityInputComponents[i].StopType == Ability.AbilityStopType.ButtonUp) { #if ENABLE_MULTIPLAYER CmdTryStopAbility(i); // Execute the method on the local instance. Use isClient instead of isServer because the client and server may be the same instance // in which case the method will be called with the Rpc call. if (!isClient) { #endif m_Controller.TryStopAbility(m_AbilityInputComponents[i]); #if ENABLE_MULTIPLAYER } #endif } } else if (PlayerInput.GetDoublePress()) { // Start the ability if the ability should be started with a double press. if (m_AbilityInputComponents[i].StartType == Ability.AbilityStartType.DoublePress && !m_AbilityInputComponents[i].IsActive) { m_Controller.TryStartAbility(m_AbilityInputComponents[i]); } } } } } /// /// Call Move directly on the character. A similar approach could have been used as the CameraController/Handler where the RigidbodyCharacterController /// directly checks the input storage variable but this would not allow the RigidbodyCharacterController to act as an AI agent as easily. /// private void FixedUpdate() { #if ENABLE_MULTIPLAYER if ( isLocalPlayer) { #endif if (m_Controller.Movement == RigidbodyCharacterController.MovementType.Combat || m_Controller.Movement == RigidbodyCharacterController.MovementType.Adventure) { m_LookRotation = m_CameraTransform.rotation; } else if (m_Controller.Movement == RigidbodyCharacterController.MovementType.TopDown || m_Controller.Movement == RigidbodyCharacterController.MovementType.Pseudo3D) { if (PlayerInput.UseMouse()) { var direction = (Vector3)PlayerInput.GetMousePosition() - m_Camera.WorldToScreenPoint(m_Transform.position + m_CapsuleCollider.center); // Convert the XY direction to an XYZ direction with Y equal to 0. direction.z = direction.y; direction.y = 0; m_LookRotation = Quaternion.LookRotation(direction); } else { var direction = Vector3.zero; if (PlayerInput.IsControllerConnected()) { direction.x = PlayerInput.GetAxisRaw(Constants.ControllerHorizontalRightThumbstick); direction.z = -PlayerInput.GetAxisRaw(Constants.ControllerVerticalRightThumbstick); } else { // No controller is connected and not using a mouse so must be mobile. direction.x = PlayerInput.GetAxisRaw(Constants.YawInputName); direction.z = PlayerInput.GetAxisRaw(Constants.PitchInputName); } if (direction.sqrMagnitude > 0.01f) { m_LookRotation = Quaternion.LookRotation(direction); } else { m_LookRotation = m_Transform.rotation; } } } else if (m_Controller.Movement == RigidbodyCharacterController.MovementType.RPG) { if (PlayerInput.IsDisabledButtonDown(false)) { m_LookRotation = m_CameraTransform.rotation; if (PlayerInput.IsDisabledButtonDown(true)) { m_ForwardMovement = 1; } } else if (!PlayerInput.IsDisabledButtonDown(true)) { if (m_ForwardMovement != 0 || m_HorizontalMovement != 0) { m_LookRotation = m_CameraTransform.rotation; } m_HorizontalMovement = 0; } } #if ENABLE_MULTIPLAYER } #endif m_Controller.Move(m_HorizontalMovement, m_ForwardMovement, m_LookRotation); } #if ENABLE_MULTIPLAYER /// /// Set the input parameters on the server. /// /// -1 to 1 value specifying the amount of horizontal movement. /// -1 to 1 value specifying the amount of forward movement. /// The direction the character should look or move relative to. [Command(channel = (int)QosType.Unreliable)] private void CmdSetInputParameters(float horizontalMovement, float forwardMovement, Quaternion lookRotation) { m_HorizontalMovement = horizontalMovement; m_ForwardMovement = forwardMovement; m_LookRotation = lookRotation; RpcSetInputParameters(horizontalMovement, forwardMovement, lookRotation); } /// /// Set the input parameters on the client. /// /// -1 to 1 value specifying the amount of horizontal movement. /// -1 to 1 value specifying the amount of forward movement. /// The direction the character should look or move relative to. [ClientRpc(channel = (int)QosType.Unreliable)] private void RpcSetInputParameters(float horizontalMovement, float forwardMovement, Quaternion lookRotation) { // The parameters would have already been set if a local player. if (isLocalPlayer) { return; } m_HorizontalMovement = horizontalMovement; m_ForwardMovement = forwardMovement; m_LookRotation = lookRotation; } /// /// Try to start an ability on the server. /// /// The index of the ability. [Command] private void CmdTryStartAbility(int abilityIndex) { m_Controller.TryStartAbility(m_AbilityInputComponents[abilityIndex]); RpcTryStartAbility(abilityIndex); } /// /// Try to start an ability on the client. /// /// The index of the ability. [ClientRpc] private void RpcTryStartAbility(int abilityIndex) { m_Controller.TryStartAbility(m_AbilityInputComponents[abilityIndex]); } /// /// Try to stop an ability on the server. /// /// The index of the ability. [Command] private void CmdTryStopAbility(int abilityIndex) { m_Controller.TryStopAbility(m_AbilityInputComponents[abilityIndex]); RpcTryStopAbility(abilityIndex); } /// /// Try to start an ability on the client. /// /// The index of the ability. [ClientRpc] private void RpcTryStopAbility(int abilityIndex) { m_Controller.TryStopAbility(m_AbilityInputComponents[abilityIndex]); } /// /// Execute an ability event on the server. /// /// The name of the event. [Command] private void CmdExecuteAbilityEvent(string eventName) { EventHandler.ExecuteEvent(eventName); RpcExecuteAbilityEvent(eventName); } /// /// Execute an ability event on the client. /// /// The name of the event. [ClientRpc] private void RpcExecuteAbilityEvent(string eventName) { EventHandler.ExecuteEvent(eventName); } #endif /// /// The abilities will register themselves with the handler so the handler can start or stop the ability. /// /// /// public void RegisterAbility(Ability ability, string inputName) { // The ability doesn't need to be registered with the handler if the ability can't be started or stopped by the handler. if (ability.StartType == Ability.AbilityStartType.Automatic && ability.StopType == Ability.AbilityStopType.Automatic) { return; } // Create two lists that will have an index that will point to the ability and its button input name. if (m_AbilityInputComponents == null) { m_AbilityInputComponents = new List(); m_AbilityInputNames = new List(); } m_AbilityInputComponents.Add(ability); m_AbilityInputNames.Add(inputName); } /// /// An ability no longer needs to listen for input events. /// /// The ability reference. public void UnregisterAbility(Ability ability) { if (m_AbilityInputComponents != null) { var index = m_AbilityInputComponents.IndexOf(ability); if (index != -1) { m_AbilityInputComponents.RemoveAt(index); m_AbilityInputNames.RemoveAt(index); } } } /// /// The character has died. Disable the handler. /// private void OnDeath() { m_HorizontalMovement = m_ForwardMovement = 0; enabled = false; EventHandler.RegisterEvent(m_GameObject, "OnRespawn", OnRespawn); } /// /// The character has respawned. Enable the handler. /// private void OnRespawn() { enabled = true; EventHandler.UnregisterEvent(m_GameObject, "OnRespawn", OnRespawn); } /// /// Is gameplay input allowed? An example of when it will not be allowed is when there is a fullscreen UI over the main camera. /// /// True if gameplay is allowed. private void AllowGameplayInput(bool allow) { m_AllowGameplayInput = allow; } /// /// Adds a new input that the handler should listen for. /// /// The input name which will trigger the event. /// The event to trigger when the button is down. private void RegisterAbilityInput(string inputName, string eventName) { if (m_AbilityInputName == null) { m_AbilityInputName = new List(); m_AbilityInputEvent = new List(); } m_AbilityInputName.Add(inputName); m_AbilityInputEvent.Add(eventName); } /// /// Removes an input event that the handler should no longer for. /// /// The input name which will trigger the event. /// The event to trigger when the button is down. private void UnregisterAbilityInput(string inputName, string eventName) { // The input name and event list will always correspond to the same abilitie's input event. for (int i = m_AbilityInputName.Count - 1; i >= 0; --i) { if (inputName.Equals(m_AbilityInputName[i]) && eventName.Equals(m_AbilityInputEvent[i])) { m_AbilityInputName.RemoveAt(i); m_AbilityInputEvent.RemoveAt(i); break; } } } #if ENABLE_MULTIPLAYER /// /// The client has left the network game. Tell the camera not to follow the character anymore. /// public override void OnNetworkDestroy() { base.OnNetworkDestroy(); if (isLocalPlayer && m_Camera != null) { m_Camera.GetComponent().Character = null; } // The event will be registered again if the character joins the game again. EventHandler.UnregisterEvent("OnNetworkStopClient", OnNetworkDestroy); } #endif } }

Each bullet forms clone of the last

$
0
0
Hi, firstly I am relatively new to unity and C# in general but I am trying to create a simple 3D ball rolling platform game with a turret that shoots the player. Currently the turret will wake up once the player is within shooting range and continue to shoot cannonballs are regular intervals. However, each cannonball forms a clone of the last one fired so it shows this in the hierarchy; cannonballs(clone) cannonballs(clone)(clone) cannonballs(clone)(clone)(clone) cannonballs(clone)(clone)(clone)(clone) etc. http://imgur.com/OSFP8BE I created a cannonball destroy script to remove the cannonball clones from the game after a set amount of time and attached this script to the cannonballs prefab as seen here; public class CannonBallDestroy : MonoBehaviour { public float DeathTime; void Update() { Destroy(gameObject, DeathTime); } } However, with this script in place a new error appears in the console each time the turret tries to shoot a cannonball; 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. http://imgur.com/hhUjS5k As far as I understand, it appears to be destroying the prefab instead of the cannonball clones?? I am not sure what I am doing wrong here and any help would be greatly appreciated. I have tried incorporating the destroy game object into the main turretAI script and I have tried destroying the gameobject by name instead but I have had no luck and I am very confused. Here is the main turretAI script; public class TurretAI : MonoBehaviour { //floats public float distance; public float wakeRange; public float LastShotTime = float.MinValue; public float fireRate; //turretspin public float turretSpeed; //booleans public bool awake = false; //references public GameObject Cannonballs; public Transform target; public Animator anim; public GameObject BulletSpawn; void Awake() { anim = gameObject.GetComponent(); } void Update() { anim.SetBool("Awake", awake); RangeCheck(); if (awake) { { //Rotate turret to look at player. Vector3 relativePos = target.position - (transform.position); Quaternion rotation = Quaternion.LookRotation(relativePos); rotation.x = 0; rotation.z = 0; transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * turretSpeed); } } //fire rate if (distance < wakeRange && Time.time > LastShotTime + (3.0f / fireRate)) { LastShotTime = Time.time; launchBullet(); } } void launchBullet() { Cannonballs = Instantiate(Cannonballs, BulletSpawn.transform.position, BulletSpawn.transform.rotation) as GameObject; Cannonballs.GetComponent().AddForce(transform.forward * 500); } void RangeCheck() { distance = Vector3.Distance(transform.position, target.transform.position); if (distance < wakeRange) { awake = true; } if (distance > wakeRange) { awake = false; } } Thanks for reading

Unknown problem with MissingReferenceException

$
0
0
Ok, so my code is only this: #pragma strict var speed : float; var rb : Rigidbody2D; function Start () { rb = GetComponent(Rigidbody2D); } function Update () { rb.velocity.y = Input.GetAxis("Vertical") * speed; } My scene has only one sprite(with rigidbody2D) & the camera. This is the error I get. What's going on? MissingReferenceException: The object of type 'Object' 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. UnityEditor.Editor.IsEnabled () (at C:/buildslave/unity/build/Editor/Mono/Inspector/Editor.cs:589) UnityEditor.InspectorWindow.DrawEditor (UnityEditor.Editor editor, Int32 editorIndex, Boolean rebuildOptimizedGUIBlock, System.Boolean& showImportedObjectBarNext, UnityEngine.Rect& importedObjectBarRect) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1151) UnityEditor.InspectorWindow.DrawEditors (UnityEditor.Editor[] editors) (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:1028) UnityEditor.InspectorWindow.OnGUI () (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:352) System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:222)

Texture2D variable causes MissingReferenceException

$
0
0
I've suffered a MissReferenceException when using Texture2D. With below code, public abstract class TestBase { protected readonly Texture2D texture; public TestBase() { texture = new Texture2D(100, 100, TextureFormat.RGB24, false); } public abstract void UseTexture(); } public class Test : TestBase { public Test () : base() { } public override void UseTexture() { // others texture.Resize(80, 80); // others code } } public class TestWindow : EditorWindow { private static TestBase base; [MenuItem("Tools/Test")] private static void Init() { // Initialization } public void OnGUI() { if (base == null) { base = new Test(); } base.UseTexture(); } public void OnDestroy() { // others Resources.UnloadUnusedAssets; } } we can get a Editor Window. With the steps below, I can get MissingReferenceException, and the "texture" will be "null". 1. The "TestWindow" will be opened automatically at Play Mode; 2. Exit Play Mode, the "TestWindow" will be closed automatically; 3. Open the window from the Menu, then the Exception occurs. Someone told me that set the hideFlags of Texture2D to be "DontSave", such as: public abstract class TestBase { ... public TestBase() { texture = new Texture2D(100, 100, TextureFormat.RGB24, false) { hideFlags = HideFlags.DontSave }; } ... } The error is fixed. But I cannot actually get why. Could someone explain it? Thanks
Viewing all 208 articles
Browse latest View live


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