- Home /
Deactivate current object in array, activate next one?
Hello, I am trying to create a bit of code that will "turn the pages" of a "book" that is being presented on my canvas (currently saved as an array) Effectively what I want to do is this: 1. Find the page my player is currently reading 2. Set that to be inactive 3. Find the page that comes after the current page 4. Set that to be active 5. Set the new page to be my current page Could someone give me some help in achieving this?
Answer by cbjunior · Aug 08, 2018 at 03:03 PM
Your question is a little general, but I will do my best to provide a decent example of how to accomplish this.
private Page[] pages = new Page[numOfPages];
private int currentPage;
private float timeSinceLastTurn;
void Start()
{
for (int i = 0; i < numOfPages; i++)
{
//Do whatever you need to initialize the pages
pages[i].SetActive(false);
}
currentPage = 0;
timeSinceLastTurn = 0.0f;
pages[0].SetActive(true);
}
void Update()
{
timeSinceLastTurn += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.RightArrow) && timeSinceLastTurn >= 5.0f) // or whatever input you're using and delay you want between turns
{
if (currentPage < numOfPages - 1)
{
pages[currentPage].SetActive(false);
currentPage++;
pages[currentPage].SetActive(true);
timeSinceLastTurn = 0.0f;
}
}
//Repeat above code but inverted in order to handle turning back a page
}
You will of course need to have some Page class defined derived from MonoBehaviour, but that part I'll leave up to you.
Answer by FernandoHC · Aug 08, 2018 at 03:03 PM
I will consider you have a Page class array of, which extends Monobehaviour. If not, then i'd suggest doing so. Regarding your questions list:
You ideally should have an index of the current page, so create an int currentPage and use it.
Do array[currentPage].gameObject.SetActive(false);, or even better have a method on Page that does that and more if needed.
currentPage++, if you have sequential pages.
array[currentPage].gameObject.SetActive(true);
This has already been done on step 3.
Your answer
Follow this Question
Related Questions
What is the best way to instatiate an array of connected GameObjects? 0 Answers
GameObject to Array/List or whatever fits best 0 Answers
How to select an Game Object from an Item List 0 Answers
How to drag and drop any object to any empty space? 0 Answers
How to create an array of Transforms 1 Answer