Select random object from list

Hi there,

I made an object list


import bge
from random import random

obj1 = scene.objects['obj1']
obj2 = scene.objects['obj2']
obj3 = scene.objects['obj3']

objectList = [obj1, obj2, obj3]

how can I now select randomly one of those three objects?
I want to spawn randomly one of them.

scene.addObject("RANDOM OBJECT", "Empty", 0)

thanks for help!
cheers

Hi! You can do that with randint function in random module:

from random import randint

scene.addObject(objectList[randint(0, 2)], "Empty", 0)

random.randint(a, b)

Return a random integer N such that a <= N <= b.

(objects in objectList must be in an inactive layer)

To get objects from inactive layers you can use that:

http://www.blender.org/api/blender_python_api_2_74_0/bge.types.KX_Scene.html?highlight=inactive#bge.types.KX_Scene.objectsInactive

myObj1 = scene.objectsInactive["TheNameOfMyObjectInInactiveLayer"]

If you want to add a random object from inactive objects list, you can do like this:

scene.addObject(scene.objectsInactive[randint(0, len(scene.objectsInactive)-1)], "Empty", 0)

import random
...
randomObject = random.choice(objectList)

Ah yes, I forgot random.choice… :slight_smile:

Thank you youle for your explenations, even though Monsters way is the easier solution, you helped me quite a bit to understand whats going on :slight_smile: Thanky also Monster for the solution.
Have a great day!
Sputi