Вы находитесь на странице: 1из 17

Controlling GameObjects using Components

Controlling GameObjects
using components
• Accessing components
• Accessing other objects
• Linking GameObjects with variables
• Finding GameObjects by Name or Tag
• Exercise (Game Setting)

Taufiqurrakhman NH, S.Kom., M.Cs. 1
Controlling GameObjects using Components

controlling GameObjects
using components

Controlling GameObjects using components

Controlling GameObjects using components


• In the Unity Editor, you make changes to Component properties using the
Inspector

• For the most part, scripting is also about modifying Component properties to
manipulate GameObjects

• The difference, though, is that a script can vary a property’s value gradually
over time or in response to input from the user

Taufiqurrakhman NH, S.Kom., M.Cs. 2
Controlling GameObjects using Components

accessing components

accessing components

accessing components
• The simplest and most common case is where a script needs access to other
Components attached to the same GameObject

• a Component is actually an instance of a class

• to get a reference to the Component instance you want to work with, this is
done with the GetComponent function

Taufiqurrakhman NH, S.Kom., M.Cs. 3
Controlling GameObjects using Components

accessing components

PlayerController (Script)
implements
Player (GameObject) PlayerController (Script) MonoBehaviour (Base Class)
has
implements
private Rigidbody rb; Behaviour (Components that can be enabled or disabled)
has implements
implements
public void AddForce(Vector3 force);
has Component 
void Start() (Base Class for everything attached to GameObjects)
{ has
Rigidbody rb = GetComponent<Rigidbody>();
} public T GetComponent<T>();

has type implements


void FixedUpdate() Object (Base Class for all objects Unity can reference)
{

rb.AddForce (movement * speed);
}

accessing other objects

Taufiqurrakhman NH, S.Kom., M.Cs. 4
Controlling GameObjects using Components

accessing other objects

accessing other objects


• Although they sometimes operate in isolation, it is common for scripts to keep
track of other objects

linking GameObjects with variables

Taufiqurrakhman NH, S.Kom., M.Cs. 5
Controlling GameObjects using Components

linking GameObjects with variables

linking GameObjects with variables


• The most straightforward way to find a related GameObject is to add a public
GameObject variable to the script

accessing other objects

accessing other objects


public class CameraController : MonoBehaviour
{
public GameObject player;
private Vector3 offset;

// Start is called before the first frame update
void Start()
{
offset = transform.position ‐ player.transform.position;
}

// Update is called once per frame
void LateUpdate()
{
transform.position = player.transform.position + offset;
}
}

Taufiqurrakhman NH, S.Kom., M.Cs. 6
Controlling GameObjects using Components

accessing other objects

accessing other objects

accessing other objects

accessing other objects


public class PlayerController : MonoBehaviour
{
public float speed;
private Rigidbody rb;

private int count;

public Text countText;
public Text winText;
...

Taufiqurrakhman NH, S.Kom., M.Cs. 7
Controlling GameObjects using Components

accessing other objects

accessing other objects

accessing other objects

accessing other objects


• You can now drag an object from the scene or Hierarchy panel onto this
variable to assign it

• The GetComponent function and Component access variables are available for
this object as with any other

Taufiqurrakhman NH, S.Kom., M.Cs. 8
Controlling GameObjects using Components

finding GameObjects by Name or Tag

finding GameObjects by Name or Tag

finding GameObjects by Name or Tag


• It is always possible to locate GameObjects anywhere in the Scene hierarchy as
long as you have some information to identify them

• Individual objects can be retrieved by name using


the GameObject.Find function:

• An object or a collection of objects can also be located by their tag using the
GameObject.FindWithTag and GameObject.FindGameObjectsWithTag functions

Taufiqurrakhman NH, S.Kom., M.Cs. 9
Controlling GameObjects using Components

finding GameObjects by Name or Tag

finding GameObjects by Name or Tag


GameObject player;

void Start() 
{
player = GameObject.Find("MainHeroCharacter");
}

finding GameObjects by Name or Tag

finding GameObjects by Name or Tag


GameObject player;
GameObject[] enemies;

void Start() 
{
player = GameObject.FindWithTag("Player");
enemies = GameObject.FindGameObjectsWithTag("Enemy");
}

Taufiqurrakhman NH, S.Kom., M.Cs. 10
Controlling GameObjects using Components

exercise

Controlling GameObjects using components

GameObject Main Camera

Taufiqurrakhman NH, S.Kom., M.Cs. 11
Controlling GameObjects using Components

Controlling GameObjects using components

CameraController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour


{
public GameObject player;
private Vector3 offset;

// Start is called before the first frame update
void Start()
{
offset = transform.position ‐ player.transform.position;
}

// Update is called once per frame
void LateUpdate()
{
transform.position = player.transform.position + offset;
}
}

Controlling GameObjects using components

GameObject Player

Taufiqurrakhman NH, S.Kom., M.Cs. 12
Controlling GameObjects using Components

PlayerController_GameSetting.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController_GameSetting : MonoBehaviour


{
private Rigidbody rb;

public GameSetting gameSetting;

// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}

PlayerController_GameSetting.cs
// Called before performing any physics calculation void OnTriggerEnter(Collider other)
void FixedUpdate() {
{ if (other.gameObject.CompareTag("Pick Up"))
if (gameSetting.status == "play") {
{
other.gameObject.SetActive(false);
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical"); gameSetting.PickUpCount();
}
bool jumpDown = Input.GetKeyDown("space"); if (other.gameObject.CompareTag("Obstacle"))
Vector3 movement; {
gameSetting.HealhtCount();
if (jumpDown)
{ }
movement = new Vector3(moveHorizontal,  }
gameSetting.playerJump, moveVertical);
}
else
{
movement = new Vector3(moveHorizontal, 0.0f, 
moveVertical);
}

rb.AddForce(movement * gameSetting.playerSpeed);
}
}

Taufiqurrakhman NH, S.Kom., M.Cs. 13
Controlling GameObjects using Components

Controlling GameObjects using components

Prefab Pick Up

Controlling GameObjects using components

Prefab Pick Up

Taufiqurrakhman NH, S.Kom., M.Cs. 14
Controlling GameObjects using Components

Controlling GameObjects using components

PickUpController_GameSetting.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PickUpController_GameSetting : MonoBehaviour


{
private GameObject gameSetting;
private float pickUpXRotation;
private float pickUpYRotation;
private float pickUpZRotation;

void Start()
{
gameSetting = GameObject.Find("Game Setting");
pickUpXRotation = gameSetting.GetComponent<GameSetting>().pickUpXRotation;
pickUpYRotation = gameSetting.GetComponent<GameSetting>().pickUpYRotation;
pickUpZRotation = gameSetting.GetComponent<GameSetting>().pickUpZRotation;
}

// Update is called once per frame
void Update()
{
transform.Rotate(new Vector3(pickUpXRotation, pickUpYRotation, pickUpZRotation) * Time.deltaTime);
}
}

Controlling GameObjects using components

GameObject Game Setting (Empty GameObject)

Taufiqurrakhman NH, S.Kom., M.Cs. 15
Controlling GameObjects using Components

GameSetting.cs
using System.Collections; public class GameSetting : MonoBehaviour

using System.Collections.Generic; {
public int numberOfLives;
using UnityEngine; private int health;
using UnityEngine.UI;
public int targetNumberOfPickUps;
using UnityEngine.SceneManagement; private int count;

public Text countText;
public Text healthText;
public Text statusText;

public bool pause;


public string status;

public float countdown;


public string nextScene;
public string loseScene;

public float playerSpeed;


public float playerJump;

public float pickUpXRotation;


public float pickUpYRotation;
public float pickUpZRotation;

GameSetting.cs
// Start is called before the first frame update public void PickUpCount()
void Start() {
{ count++;
count = 0; SetCountText();
SetCountText(); if (count >= targetNumberOfPickUps)
{
health = numberOfLives;
status = "win";
SetHealthText();
}
pause = !pause; }
PauseScene();

status = "play"; public void HealhtCount()


} {   
if (health > 0)
{
private void SetCountText() health = health ‐ 1;
{ }
countText.text = "Count : " + count.ToString(); if (health <= 0)
} {
status = "lose";
}
private void SetHealthText() SetHealthText();
{ }
healthText.text = "Health : " + health.ToString();
}

Taufiqurrakhman NH, S.Kom., M.Cs. 16
Controlling GameObjects using Components

GameSetting.cs
// Update is called once per frame private void ExitGame()
void Update() {
{ #if UNITY_EDITOR
if (Input.GetKeyDown("escape")) UnityEditor.EditorApplication.isPlaying = false;
{ #else
ExitGame(); Application.Quit();
} #endif
}
if (Input.GetKeyDown("p"))
{
PauseScene(); public void PauseScene()
}
{
if (status == "win") if (pause)
{ {
string message = "Congratulation !!! You Win !!!\nGoing to next scene  Time.timeScale = 1;
in " + countdown.ToString("0") + " seconds"; statusText.text = "";
SetCountDown(message, nextScene);
pause = false;
}
}
else
if (status == "lose")
{
{
string message = "You Lose !!!\nGoing to restart in " +  Time.timeScale = 0;
countdown.ToString("0") + " seconds"; statusText.text = "Pause";
SetCountDown(message, loseScene); pause = true;
} }
} }

GameSetting.cs
private void SetCountDown(string message, string scene) public void ChangeScene(string sceneDestination)

{ {
if (countdown > 0) SceneManager.LoadScene(sceneDestination);
{ }
statusText.text = message;
countdown ‐= Time.deltaTime;
}
if (countdown <= 0)
{
ChangeScene(scene);
}
}

Taufiqurrakhman NH, S.Kom., M.Cs. 17

Вам также может понравиться