What is missing reference exception in c#? - c#

I am making a game in unity 3d and I have missing reference exception.The error
don't appear in my script editor so I don't know what is this error related to.
Here is the Gamemanager script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Gamemanager : MonoBehaviour
{
public List<Character> Characters = new List<Character>();
public List <Item> AllItems = new List<Item> ();
bool ShowCharWheel;
public int SelectedCharacter;
int LastCharacter;
public static Gamemanager Instance;
public bool CanShowSwitch = true;
public Character CurrentCharacter;
void Awake()
{
foreach (Character c in Characters)
{
c.Instance = Instantiate(c.PlayerPrefab, c.HomeSpawn.position, c.HomeSpawn.rotation) as GameObject;
c.Instance.GetComponent<PlayerController> ().LocalCharacter = c;
}
ChangeCharacterStart(Characters[PlayerPrefs.GetInt("SelectedChar")]);
}
// Use this for initialization
void Start()
{
}
void ChangeCharacterStart(Character c)
{
LastCharacter = SelectedCharacter;
SelectedCharacter = Characters.IndexOf(c);
CurrentCharacter = c;
Characters [LastCharacter].Instance.GetComponent<PlayerController> ().CanPlay = false;
Characters[SelectedCharacter].Instance.GetComponent<PlayerController>().CanPlay = true;
Camera.main.GetComponent<SmoothFollow>().target = Characters[SelectedCharacter].Instance.transform;
PlayerPrefs.SetInt("SelectedChar", SelectedCharacter);
}
// Update is called once per frame
void Update()
{
if (CanShowSwitch) {
if (Input.GetKey (KeyCode.C)) {
ShowCharWheel = true;
} else if (Input.GetKey (KeyCode.V)) {
ShowCharWheel = false;
}
}
}
void ChangeCharacter(Character c)
{
c.Instance.GetComponent<AI> ().DoneHome = false;
if (Vector3.Distance (Characters [SelectedCharacter].Instance.transform.position, c.Instance.transform.position) > 10) {
sequencemanager.Instance.StartCoroutine ("DoCharSwitch", c);
CanShowSwitch = false;
LastCharacter = SelectedCharacter;
SelectedCharacter = Characters.IndexOf (c);
CurrentCharacter = c;
Characters [LastCharacter].Instance.GetComponent<PlayerController> ().CanPlay = false;
Characters [SelectedCharacter].Instance.GetComponent<PlayerController> ().CanPlay = true;
PlayerPrefs.SetInt ("SelectedChar", SelectedCharacter);
} else {
LastCharacter = SelectedCharacter;
SelectedCharacter = Characters.IndexOf(c);
CurrentCharacter = c;
Characters [LastCharacter].Instance.GetComponent<PlayerController> ().CanPlay = false;
Characters [SelectedCharacter].Instance.GetComponent<PlayerController> ().CanPlay = true;
PlayerPrefs.SetInt ("SelectedChar", SelectedCharacter);
Camera.main.GetComponent<SmoothFollow> ().target = Characters [SelectedCharacter].Instance.transform;
}
}
void OnGUI()
{
if (ShowCharWheel)
{
GUILayout.BeginArea(new Rect(Screen.width - 64, Screen.height - 256, 64, 208), GUIContent.none, "box");
foreach (Character c in Characters)
{
if (GUILayout.Button(c.Icon, GUILayout.Width(64), GUILayout.Height(64)))
{
ChangeCharacterStart(c);
}
}
GUILayout.EndArea();
}
}
}
[System.Serializable]
public class Character
{
public string Name;
public Texture2D Icon;
public GameObject PlayerPrefab;
public GameObject Instance;
public Transform HomeSpawn;
}
[System.Serializable]
public class Item
{
public string Name;
public Texture2D Icon;
public ItemInstance InstancePrefab;
}
The error is on line
c.Instance = Instantiate(c.PlayerPrefab, c.HomeSpawn.position, c.HomeSpawn.rotation) as GameObject;
This is my editor image with error.The main problem is when I start the game it destroy the gamemanager script.
And another important thing.I migrated this project.I had to reinstall windows.Before that the error didn't appeared.And now it do.And I am sure I took the whole pro

I just a junior developer without much of experience but your code looks messy. May be there is more null refs errors so most probably you did not assign/ save to prefab something or an object that you want to use is destroyed. Check [how to debug with monobehaviour] (https://unity3d.com/learn/tutorials/topics/scripting/monodevelops-debugger). So put some break point, and go through them one by one. When break point activated you can hover over variable and check if it has some value. I strongly suggest you make any assignment on separate line like this:
c.Instance = Instantiate(c.PlayerPrefab, c.HomeSpawn.position, c.HomeSpawn.rotation) as GameObject;
should be like this:
GameObject newGameObject = Instantiate(c.PlayerPrefab, c.HomeSpawn.position, c.HomeSpawn.rotation) as GameObject;
c.Instance = newGameObject;
In that case you can check if you really have newGameObject and so on.

Related

change scene upon reaching specific score

I'm very new to unity and coding so I have some doubt here. I'm current creating a multiple choice quiz game. can someone help w the coding for my question. My question here is I need to change scene upon reaching certain point. for example, when my score hits 30 I want winner page to appear and when my score hits 0 I want you lose page to appear. how?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class AnswerButtons : MonoBehaviour {
public GameObject answerAbackBlue; // blue is waiting
public GameObject answerAbackGreen; // green is correct
public GameObject answerAbackRed; // red is wrong answer
public GameObject answerBbackBlue; // blue is waiting
public GameObject answerBbackGreen; // green is correct
public GameObject answerBbackRed; // red is wrong answer
public GameObject answerCbackBlue; // blue is waiting
public GameObject answerCbackGreen; // green is correct
public GameObject answerCbackRed; // red is wrong answer
public GameObject answerDbackBlue; // blue is waiting
public GameObject answerDbackGreen; // green is correct
public GameObject answerDbackRed; // red is wrong answer
public GameObject answerA;
public GameObject answerB;
public GameObject answerC;
public GameObject answerD;
public AudioSource CorrectFX;
public AudioSource WrongFX;
public GameObject currentScore;
public int scoreValue;
void Update() {
currentScore.GetComponent<Text>().text = "SCORE: " + scoreValue;
if (scoreValue > 300)
SceneManager.LoadScene("WinnerPage");
if (scoreValue < 50)
SceneManager.LoadScene("LoserPage");
}
public void AnswerA() {
if (QuestionGenarate.actualAnswer == "A") {
answerAbackGreen.SetActive(true);
answerAbackBlue.SetActive(false);
CorrectFX.Play();
scoreValue += 10;
} else {
answerAbackRed.SetActive(true);
answerAbackBlue.SetActive(false);
WrongFX.Play();
scoreValue -= 5;
}
answerA.GetComponent<Button>().enabled = false;
answerB.GetComponent<Button>().enabled = false;
answerC.GetComponent<Button>().enabled = false;
answerD.GetComponent<Button>().enabled = false;
StartCoroutine(NextQuestion());
}
public void AnswerB() {
if (QuestionGenarate.actualAnswer == "B") {
answerBbackGreen.SetActive(true);
answerBbackBlue.SetActive(false);
CorrectFX.Play();
scoreValue += 10;
} else {
answerBbackRed.SetActive(true);
answerBbackBlue.SetActive(false);
WrongFX.Play();
scoreValue -= 5;
}
answerA.GetComponent<Button>().enabled = false;
answerB.GetComponent<Button>().enabled = false;
answerC.GetComponent<Button>().enabled = false;
answerD.GetComponent<Button>().enabled = false;
StartCoroutine(NextQuestion());
}
public void AnswerC() {
if (QuestionGenarate.actualAnswer == "C") {
answerCbackGreen.SetActive(true);
answerCbackBlue.SetActive(false);
CorrectFX.Play();
scoreValue += 10;
} else {
answerCbackRed.SetActive(true);
answerCbackBlue.SetActive(false);
WrongFX.Play();
scoreValue -= 5;
}
answerA.GetComponent<Button>().enabled = false;
answerB.GetComponent<Button>().enabled = false;
answerC.GetComponent<Button>().enabled = false;
answerD.GetComponent<Button>().enabled = false;
StartCoroutine(NextQuestion());
}
public void AnswerD() {
if (QuestionGenarate.actualAnswer == "D") {
answerDbackGreen.SetActive(true);
answerDbackBlue.SetActive(false);
CorrectFX.Play();
scoreValue += 10;
} else {
answerDbackRed.SetActive(true);
answerDbackBlue.SetActive(false);
WrongFX.Play();
scoreValue -= 5;
}
answerA.GetComponent<Button>().enabled = false;
answerB.GetComponent<Button>().enabled = false;
answerC.GetComponent<Button>().enabled = false;
answerD.GetComponent<Button>().enabled = false;
StartCoroutine(NextQuestion());
}
IEnumerator NextQuestion() {
yield return new WaitForSeconds(2);
answerAbackGreen.SetActive(false);
answerBbackGreen.SetActive(false);
answerCbackGreen.SetActive(false);
answerDbackGreen.SetActive(false);
answerAbackRed.SetActive(false);
answerBbackRed.SetActive(false);
answerCbackRed.SetActive(false);
answerDbackRed.SetActive(false);
answerAbackBlue.SetActive(false);
answerBbackBlue.SetActive(false);
answerCbackBlue.SetActive(false);
answerDbackBlue.SetActive(false);
answerA.GetComponent<Button>().enabled = true;
answerB.GetComponent<Button>().enabled = true;
answerC.GetComponent<Button>().enabled = true;
answerD.GetComponent<Button>().enabled = true;
QuestionGenarate.displayingQuestion = false;
}
}
It is hard to answer because you didn't show us the exact code where you count scores. But I will try to help you as much as I can.
Enter your code where you count scores (where you have that variable that stores scores). Now, above the code, among other "using" statements add
using UnityEngine.SceneManagement;
So you just added a scene manager into your script to have control over scenes. Now inside your Update() function add
if (score<0)
{
SceneManager.LoadScene("LoserPage"); //player lost
}
if (score>29)
{
SceneManager.LoadScene("WinnerPage"); //player won
}
In the code above score is a variable that stores your scores. Change that to whatever you have that does it. LoserPage and WinnderPage are the names of the scenes that you have created. Change their names to whatever you have to make it work. Don't forget to add your scenes in Build settings in the correct order.

Despite the name of the file and the name of the class being the same, Unity still can't find the class

Despite the many times I have rewritten the file and made sure the class and the file name match up unity is still saying it can't find the script class. I even made sure all the spelling important words were correct, and it still says it can't find the script class. The name of the file is BasicAI.cs This is what the file looks like.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityStandardAssets.Characters.ThirdPerson
{
public class BasicAI : MonoBehaviour
{
public UnityEngine.AI.NavMeshAgent agent;
public ThirdPersonCharacteracter character;
public enum State {
PATROL,
CHASE
}
public State state;
private bool alive;
//Patrolling
public GameObject[] markers;
private int markerID=0;
public float patrolSpeed=0.0f;
//Chasing
public float chaseSpeed=1f;
public GameObject target;
// Start is called before the first frame update
void Start()
{
agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
character = GetComponent<ThirdPersoncharacter>();
agent.updatePosition = true;
agent.updateRotation = false;
state = BasicAI.State.PATROL;
alive = true;
StartCoroutine("FiniteState");
}
IEnumerator FiniteState()
{
while(alive)
{
switch(state)
{
case State.PATROL:
Patrol();
break;
case State.CHASE:
Chase();
break;
}
yield return null;
}
}
void Patrol()
{
agent.speed = patrolSpeed;
if(Vector3.Distance(this.transform.position, markers[markerID].transform.position) >= 2)
{
agent.setDestionation(markers[markerID].transform.position);
character.move(agent.desiredVelocity, false, false);
}
else if(Vector3.Distance(this.transform.position, markers[markerID].transform.position) <= 2)
{
markerID += 1;
if(markerID>markers.Length)
{
markerID = 0;
}
}
else
{
character.move(Vector3.zero, false, false);
}
}
void Chase()
{
agent.speed = chaseSpeed;
agent.setDestionation(target.transform.position);
character.move(agent.desiredVelocity, false, false);
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
state = basicAI.State.CHASE;
target = other.GameObject;
}
}
}
}

Why only from the second door the door close ? The first one stay opened

The first script and the second both attached to the doors.
In this case I have 12 doors.
No matter what the first door of the 12 the player controller or a NPC enter the door it will open but stay opened. The next door the player controller or the NPC will enter will open and then also will be closed and then all the doors.
But each time the first door never close. It's working only from the second door each time when running the game.
On this script HoriDoorManager I'm using public static flag exitedDoor and set it to true inside the OnTriggerExit:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class HoriDoorManager : MonoBehaviour
{
public static bool exitedDoor = false;
private bool doorLockState;
private List<DoorHori> doors = new List<DoorHori>();
private void Start()
{
if (transform.parent != null)
{
Transform parent = transform.parent;
var children = parent.GetComponentsInChildren<Transform>();
if(children != null)
{
foreach (Transform door in children)
{
if (door.name == "Door_Left" || door.name == "Door_Right")
doors.Add(door.GetComponent<DoorHori>());
}
}
}
}
void OnTriggerEnter()
{
if (doorLockState == false)
{
if (doors != null)
{
for(int i =0; i < doors.Count; i++)
{
doors[i].OpenDoor();
}
}
}
}
private void OnTriggerExit(Collider collide)
{
if (doorLockState == false)
{
exitedDoor = true;
}
}
public void ChangeLockState(bool lockState)
{
doorLockState = lockState;
}
}
In the second script I'm checking if the flag exitedDoor is true and then start closing the door: Inside the method WaitToClose:
using UnityEngine;
using System.Collections;
public class DoorHori : MonoBehaviour
{
public float translateValue;
public float easeTime;
public OTween.EaseType ease;
public float waitTime;
private Vector3 StartlocalPos;
private Vector3 endlocalPos;
private void Start()
{
StartlocalPos = transform.localPosition;
gameObject.isStatic = false;
}
public void OpenDoor()
{
OTween.ValueTo(gameObject, ease, 0.0f, -translateValue, easeTime, 0.0f, "StartOpen", "UpdateOpenDoor", "EndOpen");
GetComponent<AudioSource>().Play();
}
private void UpdateOpenDoor(float f)
{
Vector3 pos = transform.TransformDirection(new Vector3(1, 0, 0));
transform.localPosition = StartlocalPos + pos * f;
}
private void UpdateCloseDoor(float f)
{
Vector3 pos = transform.TransformDirection(new Vector3(-f, 0, 0));
transform.localPosition = endlocalPos - pos;
}
private void EndOpen()
{
endlocalPos = transform.localPosition;
StartCoroutine(WaitToClose());
}
private IEnumerator WaitToClose()
{
if (HoriDoorManager.exitedDoor == true)
{
yield return new WaitForSeconds(waitTime);
OTween.ValueTo(gameObject, ease, 0.0f, translateValue, easeTime, 0.0f, "StartClose", "UpdateCloseDoor", "EndClose");
GetComponent<AudioSource>().Play();
}
}
}
Try changing the OnTriggerEnter to this in your first script.
private void OnTriggerEnter(Collider collide){
if (doorLockState == false)
{
if (doors != null)
{
for(int i =0; i < doors.Count; i++)
{
doors[i].OpenDoor();
}
}
}
}
You are not using unity's defined method when you remove the parameters of the method, so it is no longer referencing the same OnTriggerEnter.
It can then also be used to check what is triggering the on enter flag, because I am assuming you don't want any collisions to trigger this logic.

Instantiate inside nested for loops does not do what it is intended to

I have been working on a minecraft clone game in Unity 2017.3 and C# and i started all right but when i worked on the super flat world generation system there began a problem. Inside the World mono behaviour, in the Generate void, there are three nested for loops which should generate a new dirt block on every possible position between 0 and 5
But it only makes a line of dirt block stretching along the Z axis.
Here is the code for PlaceableItem(attached to dirtPrefab) and World(attached to World)
Placeable Item class
using UnityEngine;
using System.Collections;
public class PlaceableItem : MonoBehaviour
{
public string nameInInventory = "Unnamed Block";
public int maxStack = 64;
public bool destructible = true;
public bool explodesOnX = false;
public bool abidesGravity = false;
public bool isContainer = false;
public bool canBeSleptOn = false;
public bool dropsSelf = false;
private Rigidbody rb;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (abidesGravity) {
rb.useGravity = true;
} else {
rb.useGravity = false;
}
}
private void OnDestroy()
{
if (dropsSelf) {
//Drop this gameObject
}
}
public void Explode() {
if (!explodesOnX)
return;
}
public void OnMouseDown()
{
if (isContainer && !canBeSleptOn) {
//Open the container inventory
} else if (canBeSleptOn && !isContainer) {
//Make the character sleep on the item
}
}
private void OnMouseOver()
{
if (Input.GetMouseButtonDown(1) && destructible) {
Destroy(gameObject);
}
}
}
World class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class World : MonoBehaviour {
public GameObject dirtPrefab;
public bool generateAutomatically = true;
// Use this for initialization
void Start () {
if (generateAutomatically) {
Generate();
}
}
// Update is called once per frame
void Update () {
}
void Generate() {
for (int x = 0; x <= 5; x++) {
for (int y = 0; y <= 5; y++) {
for (int z = 0; z <= 5; z++) {
Instantiate(dirtPrefab, new Vector3(x, y, z), Quaternion.identity);
}
}
}
}
void RemoveAllBlocks() {
foreach (PlaceableItem placeableItem in GetComponentsInChildren<PlaceableItem>()) {
Destroy(placeableItem.gameObject);
}
}
}
Thanks in advance, fellow developers!
Hope this is not a stupid question!
[SOLVED] I realised i had a recttransform somehow attached to my dirt prefab. Removing it and adding a transform instead helped.

How to make an object slide left and right automaticly in Unity 5.6? [duplicate]

This question already has an answer here:
Move GameObject back and forth
(1 answer)
Closed 5 years ago.
I'm currently developing a game in Unity 3D with c#. I developed some levels, and now I want to make some levels with auto moving cubes(the thematic of the game is cubes). I searched a lot on the internet but I don't find nothing wich satisfy me. Can someone help me? I really need help. Sorry if there are some grammare errors.
Create a new Script an name it SimpleTranslator.cs then copy and paste the below code.
using UnityEngine;
namespace TransformUtility
{
public class SimpleTranslator : MonoBehaviour
{
[Tooltip("The local target position towards we translate this gameObject. A red line is drawn.")]
public Vector3 m_localTargetPosition = new Vector3(0, 0, 5);
public float speed = 1;
public bool pingPong;
public bool translateOnAwake = true;
public new AudioSource audio;
Vector3 m_initialPosition, m_targetPosition;
Transform m_transform;
void Awake()
{
m_transform = transform;
m_initialPosition = m_transform.position;
SetTargetPosition(m_localTargetPosition);
enabled = translateOnAwake;
}
void FixedUpdate()
{
if (audio && !audio.isPlaying)
audio.Play();
m_transform.position = Vector3.MoveTowards(m_transform.position, m_targetPosition, speed * Time.deltaTime);
if (m_transform.position == m_targetPosition)
{
if (pingPong)
{
SwitchDirection();
}
else
{
enabled = false;
if (audio)
audio.Stop();
}
}
}
public bool isTranslating
{
get
{
return enabled;
}
}
public void SwitchDirection()
{
enabled = true;
if (m_transform.position == m_initialPosition)
{
SetTargetPosition(m_localTargetPosition);
}
else
{
m_targetPosition = m_initialPosition;
}
}
public void MoveToTargetPosition()
{
enabled = true;
SetTargetPosition(m_localTargetPosition);
}
public void MoveToInitialPosition()
{
m_targetPosition = m_initialPosition;
enabled = true;
}
public bool isInInitialPosition
{
get
{
return m_transform.position == m_initialPosition;
}
}
public bool isInTargetPosition
{
get
{
return m_transform.position == m_initialPosition + m_transform.TransformDirection(m_localTargetPosition);
}
}
private void SetTargetPosition(Vector3 localPosition)
{
m_targetPosition = m_initialPosition + transform.TransformDirection(localPosition);
#if UNITY_EDITOR
m_endPositionDebug = m_targetPosition;
#endif
}
#if UNITY_EDITOR
Vector3 m_endPositionDebug;
void OnDrawGizmos()
{
if (!Application.isPlaying)
{
Debug.DrawRay(transform.position, transform.TransformDirection(m_localTargetPosition), Color.red);
}
else
{
Debug.DrawLine(m_initialPosition, m_endPositionDebug, Color.red);
}
}
#endif
}
}

Categories