- Home /
How to know what random number is chosen
I'm using Random.Range to pick a random card from an array, I'd like to delete it from the array afterward, but how do I know which index number he picked at random?
var CurCard = Instantiate(P1Deck[Random.Range(0, P1Deck.Length)], CardLocations[LocationNumber].transform.position, CardLocations[LocationNumber].transform.rotation);
Well I've deter$$anonymous$$ed what the random is by declaring a variable like this:
var RandomPick = Random.Range(0, P1Deck.Length);
var CurCard = Instantiate(P1Deck[RandomPick], CardLocations[LocationNumber].transform.position, CardLocations[LocationNumber].transform.rotation);
But now the question is how to remove it. I've tried RemoveAt,
like this: P1Deck.RemoveAt(RandomPick),
but I'm getting this error:
'RemoveAt' is not a member of 'UnityEngine.GameObject[]'.
GameObject[] is a built-in array. One of its properties is that you've assigned it a size, and throughout the lifetime of your game, its size won't change.
If you need to have an array that has a changing length, you'll need to use some other kind of array, like a List. However, I suppose you could also just make that element of the array null:
P1Deck[RandomPick] = null;
But this may cause other issues with your code (such as trying later to pick a card out of the deck that doesn't exist). You'll need to make sure that null cards in your code are ignored later. I'd probably lean to making a List.
I can't really find anything about Lists though... How can I declare a list of gameobjects ins$$anonymous$$d of an array then?
Yes it does. Although the syntax is slightly different...
List.<int> //Unityscript
vs
List<int> //C#
Almost everything in the $$anonymous$$SDN docs for .NET applies to Unityscript (and Boo for that matter).
Answer by Eric5h5 · Aug 02, 2012 at 07:06 PM
You can't use RemoveAt with arrays. Use List instead.
Oh yes, I've got it working now.
If found this very helpful for those whom are interested. http://forum.unity3d.com/threads/79760-How-to-use-generics-in-unity-javascript
Answer by Jerdak · Aug 02, 2012 at 07:10 PM
Question needs more code. At the very least include P1Deck's declaration.
But since you're getting a 'not a member of GameObject[]' error it sounds like maybe P1Deck was implemented like:
var P1Deck: GameObject[] = new GameObject[1];
In which case you would need to modify it in to a Javascript array that does support RemoveAt.
Your answer
Follow this Question
Related Questions
Store multiple random integers in an array? 4 Answers
[Beginner] Using Random.Range in initial game object position 1 Answer
pick a random int with the value of 1 from an array 2 Answers
Selection list from Array Unity - Random - GameObjects array 1 Answer
My sprite doesn't render on scene view and game view 2 Answers