7.3 – Using userData

Every element and container in iGUI has a userData field. You can think userData field as an empty box, which you can put any object in it for later use. This object can be any type.For example string, int, GameObject or Rigidbody. For example create a scene with a plane(ground) and a light. Add 3 spheres named Ball1, Ball2, Ball3 to your scene. Add rigidbody to each sphere. Change iGUIRoot’s layout to Horizontal. We’ll add three buttons to the root at the iGUIRoot init event, which will bounce the corresponding ball. But we don’t want to write three different event methods for each button. We’ll write a method, which will use the userData field of each button to access the corresponding ball.

public void root1_Init(iGUIRoot caller){
    iGUIButton btn1 = root1.addElement<iGUIButton>();
    btn1.userData = GameObject.Find("Ball1");
    btn1.clickCallback += bounceBall;
   
    iGUIButton btn2 = root1.addElement<iGUIButton>();
    btn2.userData = GameObject.Find("Ball2");
    btn2.clickCallback += bounceBall;
   
    iGUIButton btn3 = root1.addElement<iGUIButton>();
    btn3.userData = GameObject.Find("Ball3");
    btn3.clickCallback += bounceBall;
}

public void bounceBall(iGUIElement caller){
    GameObject targetBall = (GameObject)caller.userData;
    targetBall.rigidbody.AddForce(Vector3.up * 200);
}
function root1_Init(caller : iGUIRoot){
    var btn1 = root1.addElement("iGUIButton");
    btn1.userData = GameObject.Find("Ball1");
    btn1.clickCallback = new iGUIEventCallback(bounceBall);
   
    var btn2 = root1.addElement("iGUIButton");
    btn2.userData = GameObject.Find("Ball2");
    btn2.clickCallback = new iGUIEventCallback(bounceBall);
   
    var btn3 = root1.addElement("iGUIButton");
    btn3.userData = GameObject.Find("Ball3");
    btn3.clickCallback = new iGUIEventCallback(bounceBall);
}

function bounceBall(caller: iGUIElement){
    var targetBall = caller.userData;
    targetBall.rigidbody.AddForce(Vector3.up * 200);
}



As you’ll notice, when accessing userData using C# , you have to cast it to the desired type.