- Home /
Array of buttons not displaying in game
I am trying to take an array of images and display them in buttons. Depending on the size of the array, it is suppose to create a button per image. The problem is that when i try to run the code I get this error:
NullReferenceException: Object reference not set to an instance of an object Boo.Lang.Runtime.RuntimeServices.InvokeBinaryOperator (System.String operatorName, System.Object lhs, System.Object rhs) NewBehaviourScript.DrawButtons () (at Assets/NewBehaviourScript.js:13) NewBehaviourScript.Update () (at Assets/NewBehaviourScript.js:8)
My question is what am I doing wrong? this is the code:
var numberOfButtonsWide = 6;
var topLeft = Vector2(100,100);
var width = 800;
var buttonHeight = 60;
var myList : Texture[];
function Start(){
DrawButtons();
}
function DrawButtons()
{
var buttonWidth = width/numberOfButtonsWide;
for(var x =0; x < myList.Count; x++)
{
if(GUI.Button(
Rect(topLeft.x + (x % numberOfButtonsWide) * buttonWidth,
topLeft.y + Mathf.FloorToInt(x / numberOfButtonsWide) * buttonHeight,buttonWidth,buttonHeight),
GUIContent (myList[x])))
{
}
}
}
Are you version constrained? The new UI tools in 4.6 are much more effective and easier to use then the legacy OnGUI methods.
Answer by zharik86 · Dec 13, 2014 at 08:18 AM
GUI method use only into OnGUI() function. And use Texture2D instead of Texture:
function Start(){
}
function OnGUI(){
DrawButtons();
}
I hope that it will help you.
still does not work I get the same error even if I call it from the OnGUI(){} is looks like the error is co$$anonymous$$g from the for loop, but I dont know why.
@darkcookie Of course, you get error. Your variable "myList" declare as Array, but in loop "for" you use it as List. Try:
function DrawButtons() {
var buttonWidth = width/numberOfButtonsWide;
//Not use Count, use Length
for(var x:int = 0; x < myList.Length; x++) {
if(GUI.Button(
Rect(topLeft.x + (x % numberOfButtonsWide) * buttonWidth,
topLeft.y + $$anonymous$$athf.FloorToInt(x / numberOfButtonsWide) * buttonHeight,buttonWidth,buttonHeight),
GUIContent(myList[x])))
{
}
}
}
Your answer
Follow this Question
Related Questions
Adding a texture to array textures?! 1 Answer
Changing texture of pressed button in array 1 Answer
Trying to get an array to make working buttons. [Script Update] 2 Answers
Resources.Load Problem 1 Answer
Normal map strange shading lines. 0 Answers