- Home /
help with instantiating gameobject at random postition from a target gameobject?
Hello all. I recently discovered that i cannot directly do a particle system with unity ui using screen space overlay, and i made some custom sparkle animations which will be done as an animated ui image using screen space overlay. what I am trying to do is to randomly instantiate that animated image at random positions around a ui image of a gem, that way it would replicate the effect of a sparkle which would otherwise be done with the particle system. How can I code this so that the spark prefabs get instantiated at random areas around the ui image (in screen space overlay) in contrast to being instantiated at vector2.zero?
Answer by callen · Jan 21, 2016 at 05:31 PM
It sounds like the real question is "how to spawn objects at random locations within a UI.Image"?
Try this:
void spawnSparkles(GameObject sparkleSource, RectTransform image, int count) {
for(int i=0;i<count;i++) {
float x = Mathf.Lerp(image.rect.min.x, image.rect.max.x, Random.value);
float y = Mathf.Lerp(image.rect.min.y, image.rect.max.y, Random.value);
Instantiate(sparkleSource, new Vector3(x, y, 0), Quaternion.identity);
}
}
Let me know if it works! (or if I misunderstood what you're asking)