Foundation game play

Verificado com a versão: 5.3

-

Dificuldade: Principiante

We now need to set up the functionality that happens when a player clicks one of our buttons.

To keep things simple, let’s start with assigning an "X" to the grid space when a player clicks a button and then "locking" that button to prevent any further changes.

To do this we will need a new script attached to the button prefab.

In the Project Window, create a new folder called "Scripts".

Select the Grid Space prefab in the Project Window.

With the Grid Space prefab selected,

... create and add a new Script called "GridSpace".

File the GridSpace script in the Scripts folder.

Open the GridSpace script for editing.

In this script, to be able to manipulate the local Button component and the associated Text component on the child GameObject, we will first need an appropriate Namespace to be able to use Unity's UI toolset, and then we will need references to the Button component and the associated Text component to set their properties. We will also need to hold the value of the current side, which for now will simply be an "X".

Add the UI Namespace to the top of the script.

using UnityEngine.UI;

For more information on namespaces, please see the information linked below.

Remove all of the sample code from the GridSpace class.

Create a public variable for the local Button component called "button".

Create a public variable for the Button’s associated Text component called "buttonText".

Create a public string variable for the "X" called "playerSide".

public Button button;
public Text buttonText;
public string playerSide;

UI Buttons can call a public functions in associated scripts. We need to create a public function to Do Something when the button is clicked.. In this function we want to set the value of "X" to the grid space and then disable the button functionality by making it non-interactable. A Button can be set to either accept or ignore input by using the Button component's interactable property.

... set the Player Side property to "X" (or any other string value you choose to test with).

This sets up the Grid Space component. Now we need to set up the Button itself.

Select the Grid Space prefab in the Project Window.

With the Grid Space prefab selected,

... add a new row to the On Click list in the Button component using the "+" button.

... drag the Grid Space prefab onto the Object field in the new row.

We are dragging the Grid Space GameObject onto itself, onto the Button component, as the Grid Space GameObject carries an instance of the GridSpace script and we want to call a public function from that instance of the GridSpace script.

"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.