x


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.

more ▼

asked Feb 16 '10 at 05:24 PM

sulas gravatar image

sulas
111 5 5 11

(comments are locked)
10|3000 characters needed characters left

1 answer: sort newest

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)

more ▼

answered Feb 16 '10 at 05:37 PM

duck gravatar image

duck ♦♦
40.9k 92 148 415

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 :)

Feb 18 '10 at 07:17 AM sulas

Sorry, that should have been "Event.current.character" rather than "Event.character"

Feb 18 '10 at 03:15 PM duck ♦♦

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!

Feb 18 '10 at 03:15 PM duck ♦♦
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5049
x1667
x194

asked: Feb 16 '10 at 05:24 PM

Seen: 1709 times

Last Updated: Feb 16 '10 at 05:53 PM