Script for activating next GameObject after first one has been found/tracked (Vuforia)
Hi guys/gals,
I'm making a small mobile application using Vuforia. It's supposed to be this sort of tour around my school, consisting out of multiple stations (6 so far). Upon detection of station 1, the button to station 1 appears for as long as station is being tracked on screen (Using the OnTrackingFound in DefaultTrackableEventHandler) and station 2 -> button 2 and so on... But since I want people to go from 1 -> 2 -> 3 etc. instead of random numbers I need all of them (except station 1) to be completely deactived at the start of the app, and then after Station 1 has been found, the next one is activated (including all parent objects and the buttons preferably). Im fairly new to scripting but any explanation/ help would be highly appreciated and I'll try my best to understand it. If any questions arise or something is unclear, feel free to ask and I'll try to elaborate more
Thanks in advance and with kind regards
Answer by hallidev · Dec 08, 2017 at 03:07 PM
This script should do the trick for you:
using UnityEngine;
public class GameObjectActivator : MonoBehaviour
{
public GameObject[] GameObjects;
private int _activeObjectIndex;
public void Start ()
{
// Set first GameObject active by default
setActiveGameObject(0);
}
public void Update ()
{
// This is your trigger for rotating through the active objects.
// I picked "T" for "Toggle". It seems you'll be using OnTrackingFound.
// I'm not familiar with Vuforia, but as long as you increment _activeObjectIndex
// and call setActiveGameObject(_activeObjectIndex), this should work for you.
if (Input.GetKeyDown(KeyCode.T))
{
// Increment to next GameObject
_activeObjectIndex++;
// If we're on the last GameObject, wrap around back
// to the first GameObject
if (_activeObjectIndex > GameObjects.Length - 1)
{
_activeObjectIndex = 0;
}
setActiveGameObject(_activeObjectIndex);
}
}
private void setActiveGameObject(int index)
{
for (int i = 0; i < GameObjects.Length; i++)
{
GameObjects[i].SetActive(i == index);
}
}
}
How to use:
Create an Empty GameObject at your root. Name it GameObjectActivator or something similar.
Attach this script
Set the "GameObjects" property array size to the number of GameObjects you want to rotate through. I see 7 "Station" GameObjects in your screenshot.
Drag each GameObject into a slot in the "GameObjects" property.
Run the game and press "T" to toggle through them for testing.
You'll need to modify the script a bit to have it trigger when you want.
Hope this helps!