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

Unity 5 scene next level scene wont load properly

$
0
0
So i tried to implement a script that changes level when you reach a certain goal in the previous one, but the level just wont load. here are the screenshots of what happens. ![alt text][1] ![alt text][2] Also an error alert comes up saying that the there's a nullreferenceexption in my Soundmanager script, here's the script. public class SoundManager : MonoBehaviour { public static SoundManager Instance = null; //inizializzatore per nuovo soundmanager //inizializzatore variabili dei suoni public AudioClip jump; public AudioClip getCoin; public AudioClip rockSmash; public AudioClip mannyDies; public AudioClip click; public AudioClip NewGameClick; public AudioClip EnemyDies; public AudioClip win; private AudioSource soundEffectAudio; void Start () { //per fare in modo che nessuno possa creare un nuovo suondmanager if (Instance == null) { Instance = this; } else if (Instance != this) { Destroy(gameObject); } AudioSource theSource = GetComponent(); soundEffectAudio = theSource; } public void PlayOneShot(AudioClip clip) { soundEffectAudio.PlayOneShot(clip); //says that the error is here! } } I would be very thankful if you could help me PS: sorry for my bad english [1]: /storage/temp/102326-screenshot-24.png [2]: /storage/temp/102325-screenshot-25.png

Can't drag variables between different scenes

$
0
0
Hi, I'm having an issue with SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive) I have a "Player Scene" which contains my Player, along with any managers for score, inventory ect. But, when a new scene gets loaded additively, all references to the Player are missing, and I cannot drag the references from the Player because it is in it's own separate scene. Originally, I had a clone of the Player in each separate scene, and I could just assign the variables from that Player, but now I want the Player to be persistent between scenes, so I removed the Player from all scenes besides the "Player Scene", but now all other scenes have "Missing reference exceptions". What is the solution to this? Any help is greatly appreciated! thanks.

Mob AI not immediately finding object it is looking for, and crashing when it eats food?

$
0
0
So I have a mob AI script that I am using on a slime model, but the problem is that I'm using Physics.OverlapSphere to find things eligible to eat, and it is picking up the terrain for most of its objects even though the terrain is only one thing, and it takes between 1-60 seconds to replace the gameobject that it has eaten with a new target, and sometimes it will crash due to its targeted food object being eaten by another slime. Any help on how to get it to not pick up the terrain as well as not crash when the food does not exist would be greatly appreciated. using System.Collections; using System.Collections.Generic; using UnityEngine; public class AI : MonoBehaviour { public GameObject Mob; public GameObject Cloned; public GameObject Food; GameObject Clone; public string FoodName; private float Speed; private int Timer; private int RandomSpeed = 1; private float Rotation; private int Growth; public float Size; private bool Growing; private bool Adult; private int Repoints; private int Cap; public int MinCap; public int MaxCap; private Color Colored; private float Mass; private bool Hungry; private float DistanceToFoodX; private float DistanceToFoodZ; private float Hunger; public float Radius; public Collider[] Colliders; private float DistanceToFood; private float DistanceToNewFoodX; private float DistanceToNewFoodZ; public GameObject Player; public int MoveSpeed; private bool FoodTargeted; public bool CanClone; void Start (){ FoodTargeted = false; DistanceToFood = DistanceToFoodX + DistanceToFoodZ; Speed = 1; Hunger = 50; Random.InitState (67); Growing = true; Adult = false; Cap = Random.Range (MinCap, MaxCap); Mob.transform.localScale = new Vector3 (0.5f * Size, 0.5f * Size, 0.5f * Size); Colored = new Color(Random.Range(0, 255), Random.Range(0, 255), Random.Range(0, 255)); } void Update () { Debug.Log (Hunger); //Make a collision sphere centered on Mob Colliders = Physics.OverlapSphere (transform.position, Radius); foreach(Collider Col in Colliders){ if (Col.gameObject.name == "Apple"){ DistanceToNewFoodX = Mathf.Abs (Col.gameObject.transform.position.x - Mob.gameObject.transform.position.x); DistanceToNewFoodZ = Mathf.Abs (Col.gameObject.transform.position.z - Mob.gameObject.transform.position.z); if (DistanceToNewFoodX + DistanceToFoodZ < DistanceToFoodX + DistanceToFoodZ) { Food = Col.gameObject; } } } //Flip Mob over when stuck Rotation = Mob.transform.eulerAngles.x; if (Rotation <= 350) { if (Rotation >= 10){ Mob.transform.Rotate (Vector3.left * Rotation); } } //Make Mob move towards food Hunger += -0.01f; if (Food != null) { FoodTargeted = true; } if (GameObject.Find ("Apple") != null & FoodTargeted == true) { DistanceToFoodX = (Food.transform.position.x - Mob.transform.position.x); DistanceToFoodZ = (Food.transform.position.z - Mob.transform.position.z); if (Hunger <= 90) { Hungry = true; } else { Hungry = false; } if (Hungry == true) { //Debug.Log (DistanceToFoodX); if (DistanceToFoodX > 0) { Mob.transform.Translate (Vector3.right * Speed * MoveSpeed * Time.deltaTime); } if (DistanceToFoodX < 0) { Mob.transform.Translate (Vector3.left * Speed * MoveSpeed * Time.deltaTime); } if (DistanceToFoodZ > 0) { Mob.transform.Translate (Vector3.forward * Speed * MoveSpeed * Time.deltaTime); } if (DistanceToFoodZ < 0) { Mob.transform.Translate (Vector3.back * Speed * MoveSpeed * Time.deltaTime); } } } //Make Mob grow if (Growing == true) { Growth += 1; Mob.transform.localScale += new Vector3 (0.0005f * Size, 0.0005f * Size, 0.0005f * Size); } if (Growth >= 1000.0){ Growth = 0; Adult = true; Growing = false; Mob.transform.localScale = new Vector3 (1f * Size, 1f * Size, 1f * Size); } //Make Mob wander around aimlessly when not hungry if (Hungry == false) { if (Speed == 0) { Mob.transform.Rotate (Vector3.up * 150 * Time.deltaTime); } Mob.transform.Translate (Vector3.forward * Speed * Time.deltaTime); Mob.transform.Translate (Vector3.right * Speed * Time.deltaTime); Timer += 1; if (Timer >= 50) { Timer = 0; Speed += Random.Range (-1, 1); } if (Speed >= 6 | Speed <= -6) { Speed = 0; } if (transform.position.y < 0) { Mob.transform.Translate (Vector3.up * -Mob.transform.position.y); } } //Make Mob able to create more of itself if (Adult == true && Hungry == false && CanClone == true && Hunger >= 60) { Repoints += 1; if (Repoints >= Cap){ Clone = Instantiate (Cloned, transform.position, Quaternion.identity) as GameObject; Cap = Random.Range (MinCap, MaxCap); Repoints = 0; Hunger += -20; } } //Make Mob die by starvation if (Hunger <= 0) { DestroyObject (Mob); } } //Make Mob consume Food when collided with void OnCollisionEnter(Collision EatFood){ if (EatFood.gameObject.name == "Apple") { DestroyObject (EatFood.gameObject); Food = GameObject.Find (FoodName); Hunger += 10; FoodTargeted = false; } } }

if (Something != null) not good enough

$
0
0
Hello, it seems that I have been having a problem multiple times where I might have a GameObject variable called "Target" which may or may not exist, so I first check by doing: if (Target != null){ //Something that requires Target to not be null will happen; } This is apparently not good enough though, because my game will randomly crash sometimes when apparently my check is ignored, and I get this 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. StatsManagerScript.Update () (at Assets/Scripts/StatsManagerScript.cs:52)

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

Missing built in enum reference?

$
0
0
Hello, I am trying to figure out why my build will not compile. I am getting the Error CS0246 saying I am missing an assembly or reference for 'NetworkDisconnection' which is a built in Unity enum. In the code I have the using UnityEngine and using System.Collections, which I know the 'NetworkDisconnection' enum is a part of. Any clue how to fix? This is the code that is throwing the error void OnDisconnectedFromServer( NetworkDisconnection cause ) { Destroy( gameObject ); }

MissingReferenceException on Inspector-assigned values after reloading scene

$
0
0
I have a level scene where gameplay takes place. In this scene, I have a canvas. I also have a PlayerGUI (manager object) that has Inspector-assigned references to the canvas elements it needs to enable/disable depending on the gameplay state. I enter the scene in gameplay and press the pause button to bring up the pause UI (PlayerGUI calls the SetActive(true) method on the GameObject reference to the panel of the pause UI). I then reload the scene using SceneManager.LoadScene, and try to open the pause UI again. This time, I'm given an exception: 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. The exception points to this line: PanelPauseMenu.SetActive(true); I am almost certain this has to be a bug in Unity. When checking the Hierarchy during gameplay, PlayerGUI has a live reference to the correct element (the reference can be double clicked, and the live, correct UI element is highlighted). Does anyone have any idea why this happens? Everything works fine the first time around, but completely fails if the level is loaded again -- it's like the references aren't updated when the level is reloaded, although they appear correct in the Inspector.

Can I check if this.gameObject was destroyed?

$
0
0
Here's a simple version of a coroutine that's running on one of my objects: public IEnumerator PulseOnGround() { while (gameObject.activeInHierarchy) { //do stuff yield return new WaitForFixedUpdate(); if (gameObject == null) yield break; } } This throws a MissingReferenceException when the object is destroyed from another script. It appears that the script keeps running after it's destroyed, but I can't find a way to check if the gameObject still exists from within the script. Is it possible to break this coroutine on destroy from within this script, without using StopCoroutine? Or do I need another script to keep track of whether this script is still alive and call StopCoroutine on any coroutines that might still be running? I'm trying to do this without StopCoroutine because I don't have references to every coroutine that's running, and I would want all of them to stop on destroy anyway.

Missing Reference.

$
0
0
switch (Input.field.text.ToLower()) { case "www.blahblah.saq": // do something when they hit up www.blahblah.saq break; case "www.microsoft.com": // do something else based off the www.microsoft.com URL break; default: // load up the browser image for any "WRONG" URL's break; } Having a bit of an issue, can't really seem to get this on either. It gives me this error, NullReferenceException: Object reference not set to an instance of an object Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.String cacheKeyName, System.Type[] cacheKeyTypes, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory) Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.Object[] args, System.String cacheKeyName, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory) Boo.Lang.Runtime.RuntimeServices.GetProperty (System.Object target, System.String name) UnityScript.Lang.UnityRuntimeServices.GetProperty (System.Object target, System.String name) Please help?

OnBecameInvisible() Throwing error when game stops

$
0
0
Hello, I tried and searched but did not found any solution to my problem. I call OnBecameInvisible() function from few different scripts. All of them are throwing errors. First one is this part of code: void OnBecameInvisible(){ if (transform.position.x < Camera.main.transform.position.x) { //do stuff } } It says "Assertion failed on expression: 'go.IsActive() && go.GetTag() != 0'". This happens only when I exit play mode. And there is another error on second line of this code: void OnBecameInvisible(){ if (transform.position.x < playerTransform.position.x) { //do stuff } } It says: "MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it." It happens whenever I exit the play mode. I had my Scene tab closed but nothing. What should I do?

Assigned variable returns null?

$
0
0
I have what I believe to be a very straightforward script that effectively just enabled gameobjects in the scene when certain actions are completed. I'm running into an issue where when i try to enable them they will occasionally evaluate to null and I will hit a missing reference exception as if the object has been deleted - but if i look at the object in the inspector I can see that it is definitely assigned (its a public variable.) stuff I've tried: - I made sure there isn't another instance of this class in the scene that hasn't been initialized properly. there is only one instance, and I can see that its gameobjects are assigned as anticipated. - Reassigning the game objects at runtime. I figured maybe something was weird about how they were assigned, so I tried assigning them manually at run time in the inspector but no joy, it still gives me a missing reference exception - Manually enabling it before trying to reference it. I figured maybe something weird could be happening where its having trouble retrieving a disabled gameobject but that still gave me a missing reference exception. I'll post the code thats enabling it below as well as what it looks like in the inspector but its really about as straightforward as it gets, maybe I'm missing something very simple though. Things that might make this weird : - This class and the objects its enabling are loaded into the scene via asset bundle. unity has historically had some weirdnesses associated with loading asset bundles so maybe theres a bug to do with that in play? - the function gets called as the result of an event being fired elsewhere. I'm not sure why this would matter since it doesnt seem like its a problem with the wrong function being called/the wrong parameter being passed but ive had troubled with events and listeners before. any help would be appreciated. *EDIT here is the stack trace 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. HFN.Ecomuve.TrailerMap.OnPlaceTracerPin (HFN.Ecomuve.TracerModule tracerModule) (at Assets/WisdomTools/Ecomuve/UGUI/Views/Tracer/TrailerMap.cs:32) HFN.Ecomuve.TracerTool.Update () (at Assets/WisdomTools/Ecomuve/UGUI/Views/Tracer/TracerTool.cs:149) ![alt text][1] [1]: /storage/temp/78229-inspector.jpeg using UnityEngine; using System.Collections; using HFN.Common; namespace HFN.Ecomuve { public class TrailerMap : MonoBehaviour { public GameObject farmTracerPin; public GameObject golfTracerPin; public GameObject neighborhood1TracerPin; public GameObject neighborhood2TracerPin; public GameObject toiletTracerPin; public void PlaceTracerPin(TracerModule tracerModule) { switch(tracerModule.tracerTypes) { case TracerId.Farm : Debug.Log(farmTracerPin); farmTracerPin.SetActive(true); break; case TracerId.GolfCourse : Debug.Log(golfTracerPin); golfTracerPin.SetActive(true); break; case TracerId.Neighborhood1 : Debug.Log(neighborhood1TracerPin); neighborhood1TracerPin.SetActive(true); break; case TracerId.Neighborhood2 : Debug.Log(neighborhood2TracerPin); neighborhood2TracerPin.SetActive(true); break; case TracerId.Toilet : Debug.Log(toiletTracerPin); toiletTracerPin.SetActive(true); break; } } public void PlaceTracerPin(Tracer tracer) { switch(tracer.tracerId) { case TracerId.Farm : farmTracerPin.SetActive(true); break; case TracerId.GolfCourse : golfTracerPin.SetActive(true); break; case TracerId.Neighborhood1 : neighborhood1TracerPin.SetActive(true); break; case TracerId.Neighborhood2 : neighborhood2TracerPin.SetActive(true); break; case TracerId.Toilet : toiletTracerPin.SetActive(true); break; } } private void Awake() { TracerTool.onSaveTracer += PlaceTracerPin; } } }

GameObject not in hierarchy missing reference to a script

$
0
0
I have a project in 5.5 beta that has a scene which has a ghost object. it does not show up in the editor hierarchy however if i double click the warning (missing script reference) the scene editor find an object called "GameDrawManager". which is not part of any prefabs nor is it part of the scene what so ever. even after deleting all objects in the scene, at run time there would be an empty hierarchy yet it still gives me the warning. I can also click on the warning which takes me to said invisible object. which is only a transform and a missing behaviour. i managed to get rid of it by creating a new scene and pasting all of the world objects to it

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

$
0
0
Hi all. I know many other have already asked this kind of question, but still I haven't found an answer which worked for me. The issue is: My game has 2 scenes so far: a **Main Menu** and a **Level 1**. Normally, when my character dies in the game, she just respawns at the latest checkpoint. But if I load Level 1 from the Main Menu, when she dies she respawns already dead with the Player Controller script disabled and I get this error: *"MissingReferenceException: The object of type 'Animator' has been destroyed but you are still trying to access it."* With "already dead" I mean that she gets stuck in the dead animation and the input doesn't work. I guess the input doesn't work because one of the scripts is disabled. And she gets stuck in the animation because the controller is destroyed. But what confuses me is that this happens only when playing this level loaded from the Main Menu. This is the code that runs when she dies: **PLAYER CONTROLLER SCRIPT:** public void Die() //death is called by a KillingObject event { m_bShootingAllowed = false; //to avoid spamming calls to this function KillingObject.OnKill -= Die; Instantiate (DieEffect, m_oTransform.position + DieEffectPosition, m_oTransform.rotation); Debug.Log("Player is dead"); m_oTimer.Start(deathAnimationLength + mk_fTimeToRespawn, Respawn, false, deathAnimationLength, HidePlayerModel); } private void HidePlayerModel() { Debug.Log("hiding player model"); Renderer[] rs = GetComponentsInChildren(); foreach (Renderer r in rs) r.enabled = false; } private void RestorePlayerModel() { Debug.Log("restoring player model"); Renderer[] rs = GetComponentsInChildren(); foreach (Renderer r in rs) r.enabled = true; } private void Respawn() { Debug.Log("Player respawned"); Debug.Log (GameModule.GetInstance().GetCheckpointManager().GetRespawnPosition()); m_oTransform.position = GameModule.GetInstance().GetCheckpointManager().GetRespawnPosition (); RestorePlayerModel(); OnRespawn (); //this is a delegate KillingObject.OnKill += Die; //can die again AllowShooting(); } **PLAYER ANIMATION SCRIPT:** void OnDie() { KillingObject.OnKill -= OnDie; //to avoid spamming calls to this function _animator.Play("Death"); source.clip = deathSounds[Random.Range(0, deathSounds.Length)]; source.volume = .2f; source.Play(); } void OnRespawn() { KillingObject.OnKill += OnDie; _animator.Play("Idle"); source.volume = 1f; } As you can see the player isn't destroyed on death, the model is disabled and enabled after a while (set by the Timer script). The scene is loaded with a simple LoadScene();. Thanks in advance for any help :(

Missing Reference Exception... please help, I am new to this!

$
0
0
I've been working on a 2D game and just finished the attacks and I'm trying to make it so that this works with multiple enemies on the field at the same time. I keep getting this error after I kill one and try to kill the other. Also when I try and hit the second one, it kills the first one. ERROR: MissingReferenceException: The object of type 'Animator' 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.Animator.SetBool (System.String name, Boolean value) (at C:/buildslave/unity/build/artifacts/generated/common/modules/Animation/AnimatorBindings.gen.cs:277) bruteDeath.bruteAnimDeath () (at Assets/Scripts/bruteDeath.cs:41) bruteHealth.Update () (at Assets/Scripts/bruteHealth.cs:36) My scripts: LevelController: using System.Collections; using System.Collections.Generic; using UnityEngine; public class LevelManager : MonoBehaviour { //Adds a defineable delay to the attack public float playerAtAnLength; //Says whether or not the player can attack private bool playerCanAttack; //Use this to reference the playerController script public playerController thePlayer; //Use this to reference the bruteController script public bruteController theBrute; public bruteDeath theBruteDeath; //Used to store the brutes last position. public Vector3 bruteLastPosition; public Vector3 bruteLastRotation; //Adds a defineable delay to the animation public float playerAtAnDelay; //Adds a defineable delay to the actual attack public float playerAcAtDelay; //Tracks the players velocity public float playerVelocity; //Allows you to define the amount that the attack should be moved left public double moveLeftDist; //Player Actual Attack Remove Time is the time that it takes for the attack collider to be removed public float playerAcAtReTi; //Allows me to set the object which would be spawned when the player is attacking public GameObject playerActualAttackCollider; //Is true if the last move was right public bool lastMoveRight; //Allows the conversion of the players position to a double public double playerTransformXDouble; //Allows you to set to players attack x location when looking left public Vector3 playerLocationLeft; //Allows you to define the players x position moved to the left public float playerAttackMovedLeft; // Use this for initialization void Start () { //Defines what thePlayer is in the playerController script thePlayer = FindObjectOfType(); theBruteDeath = FindObjectOfType(); theBrute = FindObjectOfType(); //Starts it out so that the player can attack playerCanAttack = true; } // Update is called once per frame void Update () { // // //All needed to flip the player attack when moving left // // theBruteDeath = FindObjectOfType(); theBrute = FindObjectOfType(); //Sets the playerVelocity to the live playerVelocity playerVelocity = thePlayer.playerVelocity; //Transfers the lastMoveRight variable to this script lastMoveRight = thePlayer.lastMoveRight; //Converts the position to a double playerTransformXDouble = thePlayer.transform.position.x; //Converts the double to a float playerAttackMovedLeft = (float)(playerTransformXDouble - moveLeftDist); //Sets the attack to the left of the player by a certain amount playerLocationLeft = new Vector3(playerAttackMovedLeft, thePlayer.transform.position.y, thePlayer.transform.position.z); } // // // //THIS CODE HAPPENS WHEN THE PLAYER ATTACKS OR ATTEMPTS TO ATTACK: // // // //Is able to be called from the playerController when the player attacks public void playerAttack() { //Will run if the player can attack if(playerCanAttack == true) { //Calls the playerAttackCo() to start StartCoroutine("playerAttackCo"); } } //The Co-routine to add the delay into the attack, so you cant spam attack. public IEnumerator playerAttackCo() { //Makes the player not able to spam the attack button playerCanAttack = false; //Starts both co-routines below StartCoroutine("playerAtAnCo"); //Will run if the player is moving right if(playerVelocity >= 0.1) { StartCoroutine("playerAcAtCoRight"); } //Will run if the player is still if(playerVelocity == 0) { StartCoroutine("playerAcAtCoStill"); } //Will run if the player is moving left if(playerVelocity <= -0.1) { StartCoroutine("playerAcAtCoLeft"); } //Sets the canMove variable in the playerController to false thePlayer.GetComponent().canMove = false; //Adds the actual delay for the number of seconds that playerAttackDelay is defined to. yield return new WaitForSeconds(playerAtAnLength); //Sets the canMove variable in the playerController to true thePlayer.GetComponent().canMove = true; //When the delay is over, the player can attack again. playerCanAttack = true; } //This Co-routine adds enough delay so that the actual animation is played only once public IEnumerator playerAtAnCo() { //Sets the isAttacking variable in the playerController to true thePlayer.GetComponent().isAttacking = 1; //Adds enough delay so that the animation is displayed yield return new WaitForSeconds(playerAtAnDelay); //Sets the isAttacking variable in the playerController to false thePlayer.GetComponent().isAttacking = 0; } //This Co-routine adds the actual damage part into the attack public IEnumerator playerAcAtCoRight() { //Sets the delay for the actual damage to be given yield return new WaitForSeconds(playerAcAtDelay); //Spawns the attack radius Instantiate(playerActualAttackCollider, thePlayer.transform.position, thePlayer.transform.rotation); } public IEnumerator playerAcAtCoLeft() { //Sets the delay for the actual damage to be given yield return new WaitForSeconds(playerAcAtDelay); //Still need to flip instantiate transform position Instantiate(playerActualAttackCollider, playerLocationLeft, thePlayer.transform.rotation); } public IEnumerator playerAcAtCoStill() { //Sets the delay for the actual damage to be given yield return new WaitForSeconds(playerAcAtDelay); //Will run if the last move was right if(lastMoveRight == true) { //Will run and place the attack radius on the right if the player is facing right Instantiate(playerActualAttackCollider, thePlayer.transform.position, thePlayer.transform.rotation); } //Will run if the last move is left if (lastMoveRight == false) { //Will run and place the attack radius on the left if is the player is facing left Instantiate(playerActualAttackCollider, playerLocationLeft, thePlayer.transform.rotation); } } // // // //Will run when brute dies // // // public void bruteActualDeath(){ bruteLastPosition = new Vector3(theBrute.transform.position.x, theBrute.transform.position.y, theBrute.transform.position.z ); theBruteDeath.addDeadBrute(); } } Brute Death: using System.Collections; using System.Collections.Generic; using UnityEngine; public class bruteDeath : MonoBehaviour { private bruteHealth theBrute; public Sprite deadBrute; private Animator myAnim; public float timeToEnd; public LevelManager theLevelManager; public Sprite bruteSprite; public Vector3 brutePosition; public Vector3 bruteRotation; public GameObject deadBody; // Use this for initialization void Start() { theLevelManager = FindObjectOfType(); theBrute = FindObjectOfType(); myAnim = GetComponent(); bruteSprite = GetComponent(); } // Update is called once per frame void Update() { } public void bruteAnimDeath() { myAnim.SetBool("bruteIsDead", true); } public void bruteDeathAnimDone() { myAnim.SetBool("bruteDeathAnimDone", true); theLevelManager.bruteActualDeath(); } public void addDeadBrute() { brutePosition = theLevelManager.bruteLastPosition; Destroy(gameObject); Instantiate(deadBody, brutePosition, theBrute.transform.rotation); } } Brute Health: using System.Collections; using System.Collections.Generic; using UnityEngine; public class bruteHealth : MonoBehaviour { //The health of the brute public float bruteHealthPoints; //References the playerController script private playerController thePlayer; private bruteDeath theBruteDeath; private float playerVelocity; private float playerAt1Dam; // Use this for initialization void Start() { theBruteDeath = FindObjectOfType(); //Actually finds the object with the playerController script thePlayer = FindObjectOfType(); //Sets the player Attack 1 Damage in this script to the defined amount in the playerController playerAt1Dam = thePlayer.playerAttack1Dam; } // Update is called once per frame void Update() { //Checks to see if the brute has run out of health if(bruteHealthPoints <= 0) { //If the brute has no health, then they are removed from the world. Eventually, add an Instantiate with particales theBruteDeath.bruteAnimDeath(); } } //Will run if the player attack 1 happens public void thePlayerAttack1BruteDamage() { //Takes the player attack 1 damage amount away from the brutes health. bruteHealthPoints = bruteHealthPoints - playerAt1Dam; } } I also have a playerController script and bruteController script if you need them. I've been working on this for a few hours and am getting frustrated. Please help!!!!!!!!

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

$
0
0
I have this script using UnityEngine; using UnityEditor; [CustomEditor( typeof(DoorPro) )] public class DoorProEditor : Editor { public override void OnInspectorGUI() { DrawDefaultInspector (); //Colors Color red = new Color(1F, 0F, 0F, 1F); Color green = new Color(0F,1F,0F,1F); bool PreviewActive = false; if(Selection.activeGameObject.GetComponent() == null) PreviewActive = false; else PreviewActive = true; if(PreviewActive == false) GUI.color = green; if(PreviewActive == true) GUI.color = red; if(GUILayout.Button("Preview Mode")) { if(PreviewActive == false) { Selection.activeGameObject.AddComponent(); } else { DestroyImmediate(Selection.activeGameObject.GetComponent()); } } } And it runs fine, but I still get the error: MissingReferenceException: The object of type 'Preview' has been destroyed but you are still trying to access it. Where did I go wrong?
Viewing all 208 articles
Browse latest View live


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