- Home /
pass a keycode to a function as parameter
Hi,
What I am trying to do is, get the key pressed and pass it to a function which instantiates a prefab. (I have a prefab for each letter, so I'd rather not do a if/else structure with 30 clauses)
here's what I have got:
function spawn(letter) {
var newObject:GameObject;
newObject = Instantiate(letter,transform.position,Quaternion.identity);
}
now the "letter" variable is to be given by the user how? My search lead me into Events and other dark places :) I also hope that Instantiate() can take in chars or strings as a parameter, or all this would be in vain.
Thanks in advance.
Answer by duck · Feb 16, 2010 at 05:37 PM
Yes I think you're on the right track looking into Events. Something like this might work:
function OnGUI()
{
if( Event.current.type == EventType.KeyDown)
{
spawn(Event.current.character);
}
}
Your 'spawn' method would then be sent a character in the 'letter' argument variable.
However, then you need some way to tie your gameobject prefabs to the character code pressed. There are a number of ways to do this, none of them are particularly fun to implement.
One method would be to put your prefabs into the Resources folder. This allows you to reference them directly by name. If you put them in the Resources folder, and call them "Letter_a" through to "Letter_z", you could use code like this to instantiate them:
var prefab : GameObject = (Resources.Load("Letter_"+letter) as GameObject);
var newObject : GameObject = Instantiate(obj, position, rotation);
Hope this helps!
(untested, please report any errors)
Hi Duck, Thanks for the great explonatoray response :) I get an error saying: "An instance of type 'UnityEngine.Event' is required to access non static member 'character'." The Resources info is amazing, thank you, even though I could not get it to work :)
Sorry, that should have been "Event.current.character" rather than "Event.character"
If you have more specific problems using "Resources", have a search of this site, or failing that, post a new question describing it in more detail!