How do I modify a game object component from a script attached to another game object?
Bare with me, I'm a beginner at both Unity and coding with Unity. I have two game objects, Player and Finish. When reaching the Finish I have a script called LevelTimer attached, where I use OnTriggerEnter2D to stop the timer, this works excellent. But how do I stop the Player object from moving from inside my LevelTimer-script attached to the Finish game object. I was thinking about setting gravity to 0 to accomplish this.
How do I write code to the modify the Player component RigidBody2D and set the Graivty Scale to 0 in the the LevelTimer script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LevelTimer : MonoBehaviour
{
private bool IsActive;
private float Timer;
private string ReadableTimerText;
public Text TimerText; // The visible timer
// Start is called before the first frame update
void Start()
{
IsActive = true;
Timer = 0f;
}
// Update is called once per frame
void Update()
{
// check if timer is running
if( IsActive == true)
{
Timer += Time.deltaTime;
if(TimerText != null) TimerText.text = "Time: " + FormatTimer();
Debug.Log( FormatTimer() );
}
}
private void StopTimer()
{
IsActive = false;
Debug.Log( "Score: " + FormatTimer() );
}
private string FormatTimer()
{
ReadableTimerText = "";
int minutes = Mathf.FloorToInt(Timer / 60f);
int seconds = Mathf.FloorToInt(Timer % 60f);
int milliseconds = Mathf.FloorToInt((Timer * 100f) % 100f);
ReadableTimerText = minutes.ToString("00") + ":" + seconds.ToString("00") + "." + milliseconds.ToString("000");
return ReadableTimerText;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
{
IsActive = false;
StopTimer();
}
}
}
Answer by Hellium · Aug 05, 2021 at 01:37 PM
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
{
IsActive = false;
StopTimer();
// Replace "PlayerScript" by the actual name of your player script
PlayerScript player = collision.gameObject.GetComponentInChildren<PlayerScript>();
if(player != null)
player.DisableControls();
}
}
Then, in your player script, implement the DisableControls
method with whatever is needed to disable the controls. Since you haven't shown how you did it, I can't help.
public void DisableControls()
{
// Do what is needed
// May be as simple as `this.enabled = false`
}
Just added code below to my Player script to test it out. Exactly what I was looking for. Thank you!
public void StopMove()
{
Debug.Log("Stop moving!");
}
and this to my leveltimer script
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Player")
{
IsActive = false;
StopTimer();
Player player = collision.gameObject.GetComponentInChildren<Player>();
if (player != null)
player.StopMove();
}
}