Hello every one,
I have a script named “changeCursonOnHover” which changes the cursor on mouse over.
I have attached the script at runtime, it works but the mouse dissapears and doesn’t display the Texture2D I have attached to to “changeCursonOnHover”.
function Start () {
var prefab:GameObject = Instantiate (myPrefab, Vector3(-38.2636,14.32397,64.41629), Quaternion.identity);
prefab.AddComponent("changeCursonOnHover");
}
The Texture2D is displayed when I attach changeCursonOnHover to a prefab in the inspector.
Is there a method to send arguments to the added component?
If your script requires a parameter when you add it at run time then you need to set that parameter. The component you’re adding will not have a Texture2D.
Is there some reason why you don’t just put that script on the prefab? If so then take the return value of AddComponent() and use it to set the texture.
Get a reference to the script added, then set the variable myCursor:
var cursorTexture: Texture2D; // assign this texture in the Inspector
function Start () {
var prefab:GameObject = Instantiate (myPrefab, Vector3(-38.2636,14.32397,64.41629) , Quaternion.identity);
// get a reference to the added script:
var script: changeCursorOnHover = prefab.AddComponent(changeCursonOnHover);
// set myCursor texture:
script.myCursor = cursorTexture;
}
But there’s also the easier way: just add the script changeCursorOnHover to the prefab and set myCursor in the Inspector: click the prefab in the Project view and add your script to it - the variable myCursor will appear as a field My Cursor in the Inspector, and you can select the desired texture. If you do that, remove the AddComponent instruction from your script: you will not need it anymore, since the prefab will born ready to use, with the script and the texture you’ve set in the prefab.