- Home /
Change Target from Script in GameObject with another Script
Hello, I create a SolarSystem Simulation and I want if I click on the Text over the Planet switch to the Planet. I have a script for zoom around the Sun. In this Script is a target for the orbiting for the camera and I don't know how to change the target to the Planet (GameObject)
I need a code to change the target from a script in a other script.
My idea:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickMercury : MonoBehaviour
{
void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.name == "MercuryText")
{
// Here is the Problem
GameObject.Find(MainCamera).GetComponent<ZoomCamera>().target = gameObject;
}
else
{
}
}
}
}
Thanks for help!
To give you more help on this I think we'd need 2 things:
Does the program reach the line that you've commented when you click on the mercury text? You can tell this by either putting a breakpoint on that line, attaching your IDE (visual studio/vscode/rider) to unity and then checking whether you hit that breakpoint - this is the pro way of checking this ;). Or alternatively, adding in a Debug.Log line next to that comment such as
Debug.Log($"Setting the zoom target to gameobject: {gameObject}");
The ZoomCamera code :) Then we can tell what happens when you assign a new value to target
Answer by logicandchaos · Jan 12, 2021 at 11:43 AM
GameObject.Find(MainCamera).GetComponent().target = gameObject; The gameObject in this line refers to the gameObject the script is on. You want the gameObject detected by the ray. hit.gameObject. using transform and gameObject is like using the this keyword, it references the object the script is attached to.
Your answer
Follow this Question
Related Questions
GameObject is already being activated or desactivated 2 Answers
The script doesn't work correctly 0 Answers
How to detect if two objects become a square ? 1 Answer
Please help my head is burning from this problem : i have multiple gameobject , same script 1 Answer
How to double spirte/gameobject/prefab and control the result on those items? 0 Answers