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:
- Find the page my player is currently reading
- Set that to be inactive
- Find the page that comes after the current page
- Set that to be active
- Set the new page to be my current page
Could someone give me some help in achieving this?
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*.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.
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.