Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How to instantiate a prefab randomly on an object

Hey! :) Im trying to instantiate that gold bar on random positions only on that three, not outside of it you understand. It seems to be a very easy fix to it but im not very talented in Unity and C# but im trying my best.


Thanks for your attention. I'm looking forward for any replies.

Answers

  • Try to instantiate the gold bar at this position


    Tree.transform.position - new Vector3(Random.Range(0,max),Random.Range(0,max),Random.Range(0,max));



    Now the max will depend on how wide the tree is

  • Unity has special random method to handle random positions in the range of a circle.

    var randomPosition = Random.insideUnitCircle * radius;
    goldPosition = treeCenterPosition + randomPosition;
    

    After that it will move gold to random position inside the tree. But if tree is not rounded like yours - it won't work properly.

  • First of all, let's put a script called spawner on the gold bar itself

    Then, calculate the x and y of the boundaries of the trees, or from where to where you want the gold bar to spawn.

    Let's store those two in 4 variables, let's say

    float leftX = (the leftmost point in the x axis of the tree)

    float topY = (the topmost point in the y axis of the tree)

    float rightX = (the rightmost point in the x axis of the tree)

    float bottomY = (the bottom point in the y axis of the tree)


    After this, let's create two more public floats storing the random numbers, something like this

    public float RandomX = Random.Range(leftX, rightX);

    public float RandomY = Random.Range(topY, bottomY);

    Then in the Start method, or whenever you want it to spawn do this :


    void Start()

    {

    transform.position = new Vector2(RandomX, RandomY);

    }


    This should spawn the gold bar in between the tree only, also MAKE SURE that the script is sitting on the gold bar and not any other object, especially not on the tree.

Sign In or Register to comment.