Hello, I am trying to instantiate cube(block) depending on which of them is selected in List, but unity writes
"NullReferenceException: Object reference not set to an instance of an object
Building.BlockName () (at Assets/Scripts/Building.cs:33)
Building.Update () (at Assets/Scripts/Building.cs:21)
"
Building script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Building : MonoBehaviour {
private Transform _spawnPosition;
private string _blockName;
void Update() {
_blockName = BlockName();
if(Input.GetKeyUp(KeyCode.Mouse0)) {
Instantiate(Resources.Load(_blockName), _spawnPosition.position, Quaternion.identity);
}
}
string BlockName() {
MainBar mb = GetComponent<MainBar>();
return mb.blocks[mb.selectedItem].Name;
}
}
And here is MainBar script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MainBar : MonoBehaviour {
private float _barWidth;
private float _barHeight;
private int _offset;
private int _barSlots;
private float _iconSize;
private int _iconOffset;
public List<Block> blocks;
public int selectedItem;
// Use this for initialization
void Start () {
_barWidth = Screen.width;
_barHeight = Screen.height/10;
_offset = 100;
_barSlots = 3;
_iconOffset = 10;
_iconSize = _barHeight - _iconOffset;
blocks = new List<Block>();
selectedItem = 0;
//for now we want to add wooden, stone, bricks block to main bar
AddBlock("WoodenBlock", Icons.woodBlockIcon);
AddBlock("StoneBlock", Icons.stoneBlockIcon);
AddBlock("BricksBlock", Icons.bricksBlockIcon);
}
void AddBlock(string name, Texture2D icon) {
Block block = new Block(name, icon);
blocks.Add(block);
}
// Update is called once per frame
void Update () {
}
void OnGUI() {
GUI.Box(new Rect(_offset, Screen.height - _barHeight, _barWidth - 2*(_offset), _barHeight), string.Empty);
for(int i = 0; i < _barSlots; i++) {
if(GUI.Button(new Rect(_offset + i *(_iconOffset + _iconSize), Screen.height - _iconSize - _iconOffset/2, _iconSize, _iconSize), blocks*.Icon)) {*
selectedItem = i;
}
}
}
}
And very simple Block class:
using UnityEngine;
public class Block : MonoBehaviour {
private string _name;
private Texture2D _icon;
public Block(string name, Texture2D icon) {
_name = name;
_icon = icon;
}
#region Getters and Setters
public string Name {
get { return _name; }
set { _name = value; }
}
public Texture2D Icon {
get { return _icon; }
set { _icon = value; }
}
#endregion
}
I will be grateful for any help.