Why i'm getting null exception when trying to GetComponent? - c#

Both scripts are attached to the same empty GameObject in the hierarchy.
First the SpawnObjects script is attached then the MoveObjects.
This is the script with the exception.
The exception is on the line:
mover.minXPos = minXPos;
The exception message:
NullReferenceException: Object reference not set to an instance of an object
SpawnObjects.RandomSpawn () (at Assets/MyScripts/SpawnObjects.cs:28)
SpawnObjects.Start () (at Assets/MyScripts/SpawnObjects.cs:18)
My code:
using UnityEngine;
using System.Collections;
public class SpawnObjects : MonoBehaviour {
public GameObject PrefabToSpawn;
public int MaximumObjects = 100;
public int minXPos = -1000;
public int maxXPos = 1000;
public int minYPos = 50;
public int maxYPos = 150;
public int minZPos = -1000;
public int maxZPos = 1000;
// Use this for initialization
void Start () {
RandomSpawn();
}
private void RandomSpawn()
{
for (int i = 0; i < MaximumObjects; i++)
{
Vector3 spawnLocation = new Vector3(Random.Range(minXPos, maxXPos), Random.Range(minYPos, maxYPos), Random.Range(minZPos, maxZPos));
GameObject spawned = (GameObject)Instantiate(PrefabToSpawn, spawnLocation, Quaternion.identity);
MoveObjects mover = spawned.GetComponent<MoveObjects>();
mover.minXPos = minXPos;
mover.maxXPos = maxXPos;
mover.minYPos = minYPos;
mover.maxYPos = maxYPos;
mover.minZPos = minZPos;
mover.maxZPos = maxZPos;
}
}
}
And this is the script of the MoveObjects
using UnityEngine;
using System.Collections;
public class MoveObjects : MonoBehaviour {
public int minXPos = -1000;
public int maxXPos = 1000;
public int minYPos = 50;
public int maxYPos = 150;
public int minZPos = -1000;
public int maxZPos = 1000;
public float speed = 30;
private Vector3 destinationLocation;
private float midX;
private float midY;
private float midZ;
void Start()
{
midX = (minXPos + maxXPos) / 2;
midY = (minYPos + maxYPos) / 2;
midZ = (minYPos + maxYPos) / 2;
GenerateNewDestinationPoint();
}
void Update()
{
Move();
if (ArrivedAtLocation())
GenerateNewDestinationPoint();
}
private void Move()
{
transform.LookAt(destinationLocation);
transform.Translate(transform.forward * speed * Time.deltaTime);
}
private bool ArrivedAtLocation()
{
return (Vector3.Distance(transform.position, destinationLocation) < 1);
}
private void GenerateNewDestinationPoint()
{
float newX = (transform.position.x < midX) ? Random.Range(midX, maxXPos) : Random.Range(minXPos, midX);
float newY = (transform.position.y < midY) ? Random.Range(midY, maxYPos) : Random.Range(minYPos, midY);
float newZ = (transform.position.z < midZ) ? Random.Range(midZ, maxZPos) : Random.Range(minZPos, midZ);
destinationLocation = new Vector3(newX, newY, newZ);
}
}

It is a possibility that your spawned object doesn't have the component attached that you are trying to access. So its always safe to check for null before using it.
MoveObjects mover = spawned.GetComponent<MoveObjects>();
if(mover == null)
{
// your prefab doesn't have the component attached. maybe add it.
mover = spawned.AddComponent<MoveObject>();
}
mover.minXPos = minXPos;
mover.maxXPos = maxXPos;
mover.minYPos = minYPos;
mover.maxYPos = maxYPos;
mover.minZPos = minZPos;
mover.maxZPos = maxZPos;

Related

Unity exploded view script does not seem to work but is also not turning up any errors

I have been working with some script which is supposed to cause the childmeshes of an object move away from their center by a certain distance on wake, Unfortunately while I am not getting any errors, the script also doesnt seem to work no matter what values I adjust. I tried to debug but am still struggling a bit, Any advice would be appreciated.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Interactions
{
public class ExplodedViewPart
{
public Vector3 StartPosition { get; }
public Vector3 Destination;
public float MoveDistance
{
set => Destination = m_meshCenter * value;
}
private readonly Vector3 m_meshCenter;
public ExplodedViewPart(Vector3 startPosition, Vector3 meshCenter, float moveDistance)
{
m_meshCenter = meshCenter;
StartPosition = startPosition;
Destination = meshCenter * moveDistance;
}
}
public class ExplodedView : MonoBehaviour
{
[Range(0.0f, 1.0f)]
[SerializeField] private float m_percentage;
[SerializeField] private float m_moveDistance = 3f;
private float m_oldMoveDistance = 3f;
private readonly List<ExplodedViewPart> m_parts = new List<ExplodedViewPart>();
private readonly List<Transform> m_partTransforms = new List<Transform>();
private void Awake()
{
foreach (var component in GetComponentsInChildren<MeshRenderer>())
{
Transform partTransform = component.transform;
m_partTransforms.Add(partTransform);
m_parts.Add(new ExplodedViewPart(partTransform.position, component.bounds.center, m_moveDistance));
}
}
private void ChangeMaxDistance(float value)
{
for (int i = 0; i < m_partTransforms.Count; i++)
{
m_parts[i].MoveDistance = value;
}
}
private void OnValidate()
{
if (Math.Abs(m_oldMoveDistance - m_moveDistance) > float.Epsilon)
{
ChangeMaxDistance(m_moveDistance);
m_oldMoveDistance = m_moveDistance;
}
Explode(m_percentage);
}
public void Explode(float percentage)
{
for (int i = 0; i < m_partTransforms.Count; i++)
{
m_partTransforms[i].position = (1 - percentage) * m_parts[i].StartPosition +
percentage * m_parts[i].Destination;
}
}
}
}

Getting NullReferenceException: Object reference not set to an instance of an object error after upgrading to unity 2021.1.26f1 [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
I am following a Unity tutorial and faced this problem
NullReferenceException: Object reference not set to an instance of an object
PieceSpawner.Spawn () (at Assets/Script/PieceSpawner.cs:25)
Segment.Spawn () (at Assets/Script/Segment.cs:30)
LevelManager.SpawnSegment () (at Assets/Script/LevelManager.cs:94)
LevelManager.GenerateSegment () (at Assets/Script/LevelManager.cs:69)
LevelManager.Update () (at Assets/Script/LevelManager.cs:58)
and
NullReferenceException: Object reference not set to an instance of an object
Segment.Awake () (at Assets/Script/Segment.cs:22)
UnityEngine.Object:Instantiate(GameObject)
LevelManager:GetSegment(Int32, Boolean) (at Assets/Script/LevelManager.cs:121)
LevelManager:SpawnSegment() (at Assets/Script/LevelManager.cs:84)
LevelManager:GenerateSegment() (at Assets/Script/LevelManager.cs:69)
LevelManager:Update() (at Assets/Script/LevelManager.cs:58)
. This game is a subway surfers type of game that generates endless objects as you go on. Why is this error happening? Is it related to an unity object or the code? I think happened after updating to 2021.1.26f1. Here is the code, what should I change?
PieceSpawner.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PieceSpawner : MonoBehaviour {
public PieceType type;
private Piece currentPiece;
public void Spawn()
{
int amtObj = 0;
switch(type)
{
case PieceType.jump:
amtObj = LevelManager.Instance.jumps.Count;
break;
case PieceType.slide:
amtObj = LevelManager.Instance.slides.Count;
break;
case PieceType.longblock:
amtObj = LevelManager.Instance.longblocks.Count;
break;
case PieceType.ramp:
amtObj = LevelManager.Instance.ramps.Count;
break;
}
currentPiece = LevelManager.Instance.GetPiece (type, Random.Range(0, amtObj));
currentPiece.gameObject.SetActive (true);
currentPiece.transform.SetParent (transform, false);
}
public void Despawn()
{
currentPiece.gameObject.SetActive (false);
}
}
LevelManager.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelManager : MonoBehaviour {
public bool SHOW_COLLIDER = true; //$$
public static LevelManager Instance { set; get;}
// Level spawning
private const float DISTANCE_BEFORE_SPWAN = 100f;
private const int INITIAL_SEGMENT = 10;
private const int MAX_SEGMENT_ON_SCREEN = 15;
private Transform cameraContainer;
private int amountOfActiveSegment;
private int continiousSegments;
private int currentSpawnZ;
private int currentLevel;
private int y1, y2, y3;
// List of pieces
public List<Piece> ramps = new List<Piece>();
public List<Piece> longblocks = new List<Piece>();
public List<Piece> jumps = new List<Piece>();
public List<Piece> slides = new List<Piece>();
[HideInInspector]
public List<Piece> pieces = new List<Piece>(); // All pieces on the pool
// List of segments
public List<Segment> availableSegments = new List<Segment>();
public List<Segment> availableTransition = new List<Segment>();
[HideInInspector]
public List<Segment> segments = new List<Segment> ();
// Gameplay
private bool isMoving;
private void Awake()
{
cameraContainer = Camera.main.transform;
currentSpawnZ = 0;
currentLevel = 0;
}
private void Start()
{
for (int i = 0; i < INITIAL_SEGMENT; i++) {
GenerateSegment ();
}
}
private void Update()
{
if (currentSpawnZ - cameraContainer.position.z < DISTANCE_BEFORE_SPWAN)
{
GenerateSegment ();
}
if (amountOfActiveSegment >= MAX_SEGMENT_ON_SCREEN) {
segments [amountOfActiveSegment - 1].DeSpawn();
amountOfActiveSegment--;
}
}
private void GenerateSegment()
{
SpawnSegment ();
if (Random.Range (0f, 1f) < (continiousSegments * 0.25f)) {
SpawnTransition ();
continiousSegments = 0;
} else {
continiousSegments++;
}
}
private void SpawnSegment()
{
List<Segment> possibleSegments = availableSegments.FindAll (x => x.beginY1 == y1 || x.beginY2 == y2 || x.beginY3 == y3);
int id = Random.Range (0, possibleSegments.Count);
Segment s = GetSegment (id, false);
y1 = s.endY1;
y2 = s.endY2;
y3 = s.endY3;
s.transform.SetParent (transform);
s.transform.localPosition = Vector3.forward * currentSpawnZ;
currentSpawnZ += s.lenght;
amountOfActiveSegment++;
s.Spawn ();
}
private void SpawnTransition()
{
List<Segment> possibleTransition = availableTransition.FindAll (x => x.beginY1 == y1 || x.beginY2 == y2 || x.beginY3 == y3);
int id = Random.Range (0, possibleTransition.Count);
Segment s = GetSegment (id, true);
y1 = s.endY1;
y2 = s.endY2;
y3 = s.endY3;
s.transform.SetParent (transform);
s.transform.localPosition = Vector3.forward * currentSpawnZ;
currentSpawnZ += s.lenght;
amountOfActiveSegment++;
s.Spawn ();
}
public Segment GetSegment(int id, bool transition)
{
Segment s = null;
s = segments.Find (x => x.SegID == id && x.transition == transition && !x.gameObject.activeSelf);
if (s == null) {
GameObject go = Instantiate (transition ? availableTransition [id].gameObject : availableSegments [id].gameObject) as GameObject;
s = go.GetComponent<Segment> ();
s.SegID = id;
s.transition = transition;
segments.Insert (0, s);
} else {
segments.Remove (s);
segments.Insert (0, s);
}
return s;
}
public Piece GetPiece(PieceType pt, int visualIndex)
{
Piece p = pieces.Find(x => x.type == pt && x.visualIndex == visualIndex && !x.gameObject.activeSelf);
if (p == null) {
GameObject go = null;
switch (pt) {
case PieceType.ramp:
go = ramps [visualIndex].gameObject;
break;
case PieceType.longblock:
go = longblocks [visualIndex].gameObject;
break;
case PieceType.jump:
go = jumps [visualIndex].gameObject;
break;
case PieceType.slide:
go = slides [visualIndex].gameObject;
break;
}
go = Instantiate (go);
p = go.GetComponent<Piece> ();
pieces.Add (p);
}
return p;
}
}
You are not making reference for your public static LevelManager Instance in LevelManager.cs.
In Awake() make a reference -
private void Awake()
{
if(Instance == null)
Instance = this;
else
Destroy(gameObject);
cameraContainer = Camera.main.transform;
currentSpawnZ = 0;
currentLevel = 0;
}

Having problem with the Dictionary in unity

I am currently programming a game in which an infinite procedural city is generated. so far everything works but because it leads to laggs if there are too many objects in the scene I wanted to make a script in which objects only appear near the player. I watched this video for help:https://www.youtube.com/watch?v=xlSkYjiE-Ck. When I tried to link this to my script (GenerateBuilding script) this error came:ArgumentException:
An item with the same key has already been added. Key: (0.0, 1.0)
System.Collections.Generic.Dictionary...
I need help to make the script work in which the houses are generated as well as the planes do, they should only be showed when the player is nearby
---Relevant Lines---
(Endless City)
calling updateChunk function in update()(updateChunk/building function is in GenerateBuilding script)
public void UpdateBuildings()
{
for (int i = 0; i < buildingObjects.Count; i++)
{
buildingObjects[i].SetVisible(false);
}
buildingObjects.Clear();
}
adding to dictionary line 68-80(UpdateVisibleChunks function)
if (building.cityChunkDictionary.ContainsKey(viewedChunkCoord))
{
building.cityChunkDictionary[viewedChunkCoord].UpdateCityChunk(viewerPosition, viewedChunkCoord, chunkSize, maxViewDst);
if (building.cityChunkDictionary[viewedChunkCoord].IsVisible())
{
building.buildingObjects.Add(building.cityChunkDictionary[viewedChunkCoord]);
}
}
else
{
building.AddTest(viewedChunkCoord, chunkSize);
}
EndlessCity, CityChunk class
CityChunk function, sending position to GenerateBuilding script to instantiate buildings in right position.
building.requestBuildingSquad(positionV3);
GenerateBuilding relevant lines
builderH function, instantiates the buildings
public float builderH(GameObject[] obj, float Height, Vector3 position)
{
Transform objTrans = obj[Random.Range(0, obj.Length)].transform;
//Instantiate house Object
GameObject objekt = Instantiate(objTrans.gameObject, position + new Vector3(xOfsset * spaceBetween, Height, zOfsset * spaceBetween), transform.rotation);
float height = Test.transform.localScale.y;
objectsss.Add(objekt);
return height;
}
AddTest function, adds instantiates objects from builderH to a dictionary
public void AddTest(Vector2 viewedChunkCoord, float chunkSize)
{
for (int i = 0; i < objectsss.Count; i++)
{
cityChunkDictionary.Add(viewedChunkCoord, new Testing(objectsss[i]));
}
}
Testing class, testing function, adds objects to class
public Testing(GameObject obj)
{
MeshObject = obj;
}
that should be all relevant lines
full scripts(really similar)
EndlessCity Script(this scripts generates the planes and gives position for GenerateBuilding script)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class EndlessCity : MonoBehaviour
{
public const float maxViewDst = 10;
public Transform viewer;
private GenerateBuilding building;
public static Vector2 viewerPosition;
int chunkSize;
int chunksVisibleInViewDst;
Dictionary<Vector2, CityChunk> terrainChunkDictionary = new Dictionary<Vector2, CityChunk>();
List<CityChunk> terrainChunksVisibleLastUpdate = new List<CityChunk>();
void Start()
{
chunkSize = 8 - 1;
chunksVisibleInViewDst = Mathf.RoundToInt(maxViewDst / chunkSize);
}
void Update()
{
viewerPosition = new Vector2(viewer.position.x, viewer.position.z);
UpdateVisibleChunks();
}
void UpdateVisibleChunks()
{
building = FindObjectOfType<GenerateBuilding>();
building.UpdateBuildings();
for (int i = 0; i < terrainChunksVisibleLastUpdate.Count; i++)
{
terrainChunksVisibleLastUpdate[i].SetVisible(false);
}
terrainChunksVisibleLastUpdate.Clear();
int currentChunkCoordX = Mathf.RoundToInt(viewerPosition.x / chunkSize);
int currentChunkCoordY = Mathf.RoundToInt(viewerPosition.y / chunkSize);
for (int yOffset = -chunksVisibleInViewDst; yOffset <= chunksVisibleInViewDst; yOffset++)
{
for (int xOffset = -chunksVisibleInViewDst; xOffset <= chunksVisibleInViewDst; xOffset++)
{
Vector2 viewedChunkCoord = new Vector2(currentChunkCoordX + xOffset, currentChunkCoordY + yOffset);
if (terrainChunkDictionary.ContainsKey(viewedChunkCoord))
{
terrainChunkDictionary[viewedChunkCoord].UpdateTerrainChunk();
if (terrainChunkDictionary[viewedChunkCoord].IsVisible())
{
terrainChunksVisibleLastUpdate.Add(terrainChunkDictionary[viewedChunkCoord]);
}
}
else
{
terrainChunkDictionary.Add(viewedChunkCoord, new CityChunk(viewedChunkCoord, chunkSize, transform));
}
if (building.cityChunkDictionary.ContainsKey(viewedChunkCoord))
{
building.cityChunkDictionary[viewedChunkCoord].UpdateCityChunk(viewerPosition, viewedChunkCoord, chunkSize, maxViewDst);
if (building.cityChunkDictionary[viewedChunkCoord].IsVisible())
{
building.buildingObjects.Add(building.cityChunkDictionary[viewedChunkCoord]);
}
}
else
{
building.AddTest(viewedChunkCoord, chunkSize);
}
}
}
}
public class CityChunk
{
private GenerateBuilding building;
public GameObject meshObject;
public Vector3 positionV3;
Vector2 position;
Bounds bounds;
public CityChunk(Vector2 coord, int size, Transform parent)
{
building = FindObjectOfType<GenerateBuilding>();
position = coord * size;
bounds = new Bounds(position, Vector2.one * size);
positionV3 = new Vector3(position.x, 0, position.y);
int xPosition = building.xLength / 2;
int zPosition = building.zLength / 2;
float xOfsset = building.xOfsset;
float zOfsset = building.zOfsset;
float spaceBetween = building.spaceBetween;
//Instantiate plane
meshObject = Instantiate(building.groundObject, positionV3 + new Vector3((xPosition + xOfsset) * spaceBetween, -.5f, (xPosition + 1 + zOfsset) * spaceBetween), Quaternion.identity);
SetVisible(false);
building.requestBuildingSquad(positionV3);
}
public void UpdateTerrainChunk()
{
float viewerDstFromNearestEdge = Mathf.Sqrt(bounds.SqrDistance(viewerPosition));
bool visible = viewerDstFromNearestEdge <= maxViewDst;
SetVisible(visible);
}
public void SetVisible(bool visible)
{
meshObject.SetActive(visible);
}
public bool IsVisible()
{
return meshObject.activeSelf;
}
}
}
GenerateBuilding(this script generates Buildings on the planes)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateBuilding : MonoBehaviour
{
public int minHeight = 2;
public int maxHeight = 8;
public int cubeTileX;
public int cubeTileZ;
public int xLength;
public int zLength;
public float spaceBetween;
public float xOfsset;
public float zOfsset;
public GameObject TesObject;
public GameObject[] Base;
public GameObject[] secondB;
public GameObject[] roof;
public GameObject groundObject;
public List<GameObject> objectsss;
public Dictionary<Vector2, Testing> cityChunkDictionary = new Dictionary<Vector2, Testing>();
public List<Testing> buildingObjects = new List<Testing>();
public GameObject Test;
void Start()
{
//requestBuildingSquad(this.transform.position);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.I))
{
//
}
}
public void requestBuildingSquad(Vector3 position)
{
//*getting the middle of the city squad
int xPosition = xLength / 2;
int zPosition = zLength / 2;
//*
for (int z = 0; z < zLength; z++)
{
zOfsset++;
for (int x = 0; x < xLength; x++)
{
GenerateBuildings(position);
}
xOfsset = 0;
}
zOfsset = 0;
}
public void GenerateBuildings(Vector3 position)
{
int bHeight = Random.Range(minHeight, maxHeight);
float bOfsset = 0;
bOfsset += builderH(Base, bOfsset, position);
for (int i = 0; i < bHeight; i++)
{
bOfsset += builderH(secondB, bOfsset, position);
}
bOfsset += builderH(roof, bOfsset, position);
xOfsset++;
}
public float builderH(GameObject[] obj, float Height, Vector3 position)
{
Transform objTrans = obj[Random.Range(0, obj.Length)].transform;
//Instantiate house Object
GameObject objekt = Instantiate(objTrans.gameObject, position + new Vector3(xOfsset * spaceBetween, Height, zOfsset * spaceBetween), transform.rotation);
float height = Test.transform.localScale.y;
objectsss.Add(objekt);
return height;
}
public void AddTest(Vector2 viewedChunkCoord, float chunkSize)
{
for (int i = 0; i < objectsss.Count; i++)
{
cityChunkDictionary.Add(viewedChunkCoord, new Testing(objectsss[i]));
}
}
public void UpdateBuildings()
{
for (int i = 0; i < buildingObjects.Count; i++)
{
buildingObjects[i].SetVisible(false);
}
buildingObjects.Clear();
}
public class Testing
{
public GameObject MeshObject;
Vector2 position;
Bounds bounds;
public Testing(GameObject obj)
{
MeshObject = obj;
}
public void SetVisible(bool visiblee)
{
MeshObject.SetActive(visiblee);
}
public bool IsVisible()
{
return MeshObject.activeSelf;
}
public void UpdateCityChunk(Vector3 viewerPosition, Vector2 coord, int size, float maxViewDst)
{
position = coord * size;
bounds = new Bounds(position, Vector2.one * size);
float viewerDstFromNearestEdge = Mathf.Sqrt(bounds.SqrDistance(viewerPosition));
bool visible = viewerDstFromNearestEdge <= maxViewDst;
SetVisible(visible);
}
}
}
The problem is that you are trying to add twice elements with the same key.
here is the documentation of the Add method for dictionaries, and as it states, trying to add an existing key throws an error.
You can either use the TryAdd method, which adds an item only if the key doesn't exist already in the dictionary, or update the value with the existing key as you can see here.

NullReferenceException: Object reference not set to an instance of an object. By Unity tutorial [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
In Unity (C#), why am I getting a NullReferenceException and how do I fix it? [duplicate]
(1 answer)
Closed 1 year ago.
I follow a Unity Tutorial to program a version of flappy bird but I get the error NullReferenceException: Object reference not set to an instance of an object
Parallaxer.Shift () (at Assets/scripts/Parallaxer.cs:130)
Parallaxer.Update () (at Assets/scripts/Parallaxer.cs:75)
uijk,hfgmjdcfmhfc,ghvkmbgµfhj,ddgxngsdfaf
This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parallaxer : MonoBehaviour
{
class PoolObject
{
public Transform transform;
public bool inUse;
public PoolObject(Transform t) { transform = t; }
public void Use() { inUse = true; }
public void Dispose() { inUse = false; }
}
[System.Serializable]
public struct YSpawnRange
{
public float min;
public float max;
}
public GameObject Prefab;
public int poolSize;
public float shiftSpeed;
public float spawnRate;
public YSpawnRange ySpawnRange;
public Vector3 defaultSpawnPos;
public bool spawnImmediate;
public Vector3 immediateSpawnPos;
public Vector2 targetAspectRatio;
float spawnTimer;
float targetASpect;
PoolObject[] poolObjects;
GameManager game;
private void Awake()
{
}
private void Start()
{
game = GameManager.Instance;
}
private void OnEnable()
{
GameManager.OnGameOverConfirmed += OnGameOverConfirmed;
}
private void OnDisable()
{
GameManager.OnGameOverConfirmed -= OnGameOverConfirmed;
}
void OnGameOverConfirmed()
{
for (int i = 0; i < poolObjects.Length; i++)
{
poolObjects[i].Dispose();
poolObjects[i].transform.position = Vector3.one * 1000;
}
if (spawnImmediate)
{
SpawnImmediate();
}
}
void Update()
{
if (game.GameOver) return;
Shift();
spawnTimer += Time.deltaTime;
if (spawnTimer > spawnRate)
{
Spawn();
spawnTimer = 0;
}
}
void Configure()
{
targetASpect = targetAspectRatio.x / targetAspectRatio.y;
poolObjects = new PoolObject[poolSize];
for (int i = 0; i < poolObjects.Length; i++)
{
GameObject go = Instantiate(Prefab) as GameObject;
Transform t = go.transform;
t.SetParent(transform);
t.position = Vector3.one * 1000;
poolObjects[i] = new PoolObject(t);
}
if (spawnImmediate)
{
SpawnImmediate();
}
}
void Spawn()
{
Transform t = GetPoolObject();
if (t == null) return;
Vector3 pos = Vector3.zero;
pos.x = defaultSpawnPos.x;
pos.y = Random.Range(ySpawnRange.min, ySpawnRange.max);
t.position = pos;
}
void SpawnImmediate()
{
Transform t = GetPoolObject();
if (t == null) return;
Vector3 pos = Vector3.zero;
pos.x = immediateSpawnPos.x;
pos.y = Random.Range(ySpawnRange.min, ySpawnRange.max);
t.position = pos;
Spawn();
}
void Shift()
{
for (int i = 0; i < poolObjects.Length; i++)
{
poolObjects[i].transform.position += -Vector3.right * shiftSpeed * Time.deltaTime;
CheckDisposeObject(poolObjects[i]);
}
}
void CheckDisposeObject(PoolObject poolObject)
{
if (poolObject.transform.position.x < -defaultSpawnPos.x)
{
poolObject.Dispose();
poolObject.transform.position = Vector3.one * 1000;
}
}
Transform GetPoolObject()
{
for (int i = 0; i < poolObjects.Length; i++)
{
if (!poolObjects[i].inUse)
{
poolObjects[i].Use();
return poolObjects[i].transform;
}
}
return null;
}
}
Thank you for your help.
I think you need to call Configure in Start or Awake. Otherwise the poolObjects array doesn't get initialized and trying to access poolObjects[i] in Shift will cause the NullRefrence error.

Unity C# Object reference not set to an instance of an object

I keep getting the error Object reference not set to an instance of an object on line 64 and I can't figure out what I need to do
Everything is working like the lives are showing up and the timer and the score is but the score isn't increasing if you can tell me what is wrong I would be so thankful
Here's my code:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
private CountdownTimer myTimer;
private int score = 0;
private int lives = 3;
private int DEATH_Y = -10;
public Texture2D LivesLeft1;
public Texture2D LivesLeft2;
public Texture2D LivesLeft3;
public int GetScore(){
return score;
}
public int GetLives()
{
return lives;
}
private void Start()
{
myTimer = GetComponent<CountdownTimer>();
}
private void Update()
{
float y = transform.position.y;
if (y < DEATH_Y) {
MoveToStartPosition();
lives--;
}
if (score == 10)
{
Application.LoadLevel("Level2");
}
if (lives == 0)
{
Application.LoadLevel("GameOver");
}
}
private void OnGUI()
{
GUILayout.BeginHorizontal ();
DisplayLives();
int secondsLeft = myTimer.GetSecondsRemaining();//this is line 64
string timeMessage = "Seconds left = " + secondsLeft;
GUILayout.Label(timeMessage);
string scoreMessage = "Score = " + score;
GUILayout.Label (scoreMessage);
}
private void DisplayLives()
{
int playerLives = GetLives();
if (1 == playerLives) {
GUILayout.Label(LivesLeft1);
}
if (2 == playerLives)
{
GUILayout.Label(LivesLeft2);
}
if(3 == playerLives){
GUILayout.Label(LivesLeft3);
}
}
private void MoveToStartPosition()
{
Vector3 startPosition = new Vector3(0,5,0);
transform.position = startPosition;
}
/**
* what increases the score
* anything with the tag Hidden
*/
private void OnTriggerEnter(Collider c)
{
string tag = c.tag;
if("Hidden" == tag)
{
score++;
}
}
}
Are you sure that your GameObject have the Component called CountdownTimer?
Also, change the Start function to Awake, because that line is not depending on anything else.

Categories

Resources