Search code examples
c#unity-game-enginesliderinstantiation

Unity - How to instantiate prefab at slider`s specific value


I`m making a 2d game based on levels in which, each level, you have three checkpoints in the score tracking bar. The player must reach the lowest checkpoint to be able to pass to the next level, but will get a bonus if he reaches the 2nd and 3rd checkpoints.

I tought on using a Slider as the scoring bar. My question is:

Is there a way to store a specific value of the Slider's bar in the Start method and Instantiate a marker prefab at that position? Here's an example:

  • The Max Value of the Slider at Level 1 is 100.
  • I want to Instantiate the first marker, with some padding in the y, in the 50`s position of the slider, the second in the 75 position and the third in the 100 position.

My current logic is that I need to, somehow, get the value I want and find his Transform, but I can`t find a way to code this, I have no idea how to get the position I want.

Here are some images to illustrate what i`m trying to do:

Level 1 Image

Level 2 Image


Solution

  • i would get the width attribute of the slider, then divide that by sliderMax, the result will be the the width of a single % on the slider. you can then add or subract multiple of this to get a percentages place on the bar.

    example: slider.x=50 slider.width=200;

    increment = slider.width/100; //this will result in two, giving you two pixels per percent.

    so your 50 percent placement would be: sliderx+(increment*50);

    keep in mind this is all pseudo code, designed to give you an idea of how to acheive your desired result