Unity Character movement issue - c#

I'm new to Unity, I'm using it to make 2D games for Android, when I hold the right button or left button, it doesn't continue moving , it just moves once, What I want to do is when I hold the right button or left button, I want the character to continue moving until I release the button. Could someone please help? I would greatly appreciate it! The tutorial is here
Here's the code for botonDerScript.cs:
using UnityEngine;
using System.Collections;
public class botonDerScript : MonoBehaviour {
private PersonajeScript personaje;
private CircleCollider2D presionar;
void Start()
{
presionar = this.gameObject.GetComponent<CircleCollider2D>();
}
// Update is called once per frame
void Update()
{
tocandoPantalla();
}
private void tocandoPantalla()
{
int numPresiones = 0;
foreach (Touch toque in Input.touches)
{
if (toque.phase != TouchPhase.Ended && toque.phase != TouchPhase.Canceled)
numPresiones++;
}
if (numPresiones > 0 | Input.GetMouseButtonDown(0))
{
Vector3 posicionTap = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 posicionTap2D = new Vector2(posicionTap.x, posicionTap.y);
bool presiono = presionar.OverlapPoint(posicionTap2D);
if (presiono)
{
personaje = this.transform.parent.gameObject.GetComponent<PersonajeScript>();
personaje.MoverJugadorDerecha();
}
}
}
}
Here's the code for botonIzqScript.cs:
using UnityEngine;
using System.Collections;
public class botonIzqScript : MonoBehaviour {
private PersonajeScript personaje;
private CircleCollider2D presionar;
void Start()
{
presionar = this.gameObject.GetComponent<CircleCollider2D>();
}
// Update is called once per frame
void Update()
{
tocandoPantalla();
}
private void tocandoPantalla()
{
int numPresiones = 0;
foreach (Touch toque in Input.touches)
{
if (toque.phase != TouchPhase.Ended && toque.phase != TouchPhase.Canceled)
numPresiones++;
}
if (numPresiones > 0 | Input.GetMouseButtonDown(0))
{
Vector3 posicionTap = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 posicionTap2D = new Vector2(posicionTap.x, posicionTap.y);
bool presiono = presionar.OverlapPoint(posicionTap2D);
if (presiono)
{
personaje = this.transform.parent.gameObject.GetComponent<PersonajeScript>();
personaje.MoverJugadorIzquierda();
}
}
}
}
Here's the code for PersonajeScript.cs :
using UnityEngine;
using System.Collections;
public class PersonajeScript : MonoBehaviour {
private JugadorScript[] jugadores;
void Start () {
jugadores = GetComponentsInChildren<JugadorScript>();
}
// Update is called once per frame
void Update () {
}
public void MoverJugadorIzquierda()
{
foreach (JugadorScript jugador in jugadores)
if (jugador != null) {
jugador.moverIzquierda();
}
}
public void MoverJugadorDerecha()
{
foreach (JugadorScript jugador in jugadores)
if (jugador != null) {
jugador.moverDerecha();
}
}
}
And finally, here's the code for JugadorScript.cs:
using UnityEngine;
using System.Collections;
public class JugadorScript : MonoBehaviour
{
public float velocidad = -10f;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void moverIzquierda()
{
transform.Translate(Vector2.right * velocidad * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 0);
}
public void moverDerecha()
{
transform.Translate(Vector2.right * velocidad * Time.deltaTime);
transform.eulerAngles = new Vector2(0, 180);
}
}

In your botonIzqScript.cs you have the if statement
if (numPresiones > 0 | Input.GetMouseButtonDown(0))
{
...
}
Change the | in the conditional to ||. | is a binary operator. || is the "OR" operator.
Do the same in your botonDerScript.cs script
Update
To stop moving when the mouse button is released, add the following if statement:
if (Input.GetMouseButtonUp(0) || (Input.touchSupported && numPresiones == 0))
{
// stop moving
}

Related

How could i solve this problem with photon game

I have followed this tutorial multiplayer fps serie from Expressed Unity especially this episode "https://youtu.be/j9PC9RhurRI?list=PLD4OdGjxbaByCEOH3fOJ4MgOdROHHBKUo" and i need some help with it.
I have followed the video till 23:30 and then all sort of things are broken. I get error saying "Can not Instantiate before client joined/created a room. State: Joining." and i dont know what i should to do.
I have checked all the codes and everything but for nothing. Do you have solution? I don't which code have the problem so i copy all three of the codes i have edited following this video.
MpManager script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.SceneManagement;
public class MPManager : MonoBehaviourPunCallbacks
{
public GameObject[] EnableObjectsOnConnect;
public GameObject[] DisableObjectsOnConnect;
// Start is called before the first frame update
void Start()
{
PhotonNetwork.ConnectUsingSettings();
//PhotonNetwork.ConnectToRegion("eu");
}
public override void OnConnectedToMaster()
{
foreach(GameObject obj in EnableObjectsOnConnect)
{
obj.SetActive(true);
}
foreach(GameObject obj in DisableObjectsOnConnect)
{
obj.SetActive(false);
}
Debug.Log("Connected to photon");
}
public void JoinFFA()
{
PhotonNetwork.AutomaticallySyncScene = true;
PhotonNetwork.JoinRandomRoom();
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
CreateFFA();
}
public void CreateFFA()
{
PhotonNetwork.AutomaticallySyncScene = true;
RoomOptions ro = new RoomOptions { MaxPlayers = 10, IsOpen = true, IsVisible = true };
PhotonNetwork.CreateRoom("defaultFFA", ro, TypedLobby.Default);
SceneManager.LoadScene("FFA");
}
}
Movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon;
using Photon.Pun;
public class Movement : MonoBehaviourPun
{
public KeyCode Left;
public KeyCode Right;
public KeyCode Forward;
public KeyCode Backward;
[SerializeField]
private float MoveSpeed = 50;
private Rigidbody body;
private GameObject cam;
// Start is called before the first frame update
void Start()
{
body = GetComponent<Rigidbody>();
cam = gameObject.transform.GetChild(0).gameObject;
if (photonView.IsMine)
{
cam.SetActive(true);
}
}
// Update is called once per frame
void Update()
{
if (photonView.IsMine)
{
float x = Input.GetAxis("Mouse X");
float y = Input.GetAxis("Mouse Y");
if (Input.GetKey(Left))
{
body.AddRelativeForce(Vector3.left * MoveSpeed, ForceMode.Impulse);
}
if (Input.GetKey(Right))
{
body.AddRelativeForce(Vector3.left * -MoveSpeed, ForceMode.Impulse);
}
if (Input.GetKey(Forward))
{
body.AddRelativeForce(Vector3.forward * MoveSpeed, ForceMode.Impulse);
}
if (Input.GetKey(Backward))
{
body.AddRelativeForce(Vector3.forward * -MoveSpeed, ForceMode.Impulse);
}
gameObject.transform.Rotate(new Vector3(0, x, 0));
cam.transform.Rotate(new Vector3(-y, 0, 0));
}
}
}
FFa script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon;
using Photon.Pun;
public class FFA : MonoBehaviourPun, IPunObservable
{
public float SpawnTime;
float timer;
bool HasPlayerSpawned = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if(timer >= SpawnTime)
{
if (!HasPlayerSpawned)
{
PhotonNetwork.Instantiate("Player", Vector3.zero, Quaternion.identity, 0);
HasPlayerSpawned = true;
}
timer = 0;
}
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if(stream.IsWriting)
{
}else if (stream.IsReading)
{
}
}
}
Sorry if I had typos my english not good.
Solution found! i just made the spawntime to 1 second instead of 0 so the player had time to join room before instantiating.

First Person Shooter box collider problem

I'm creating a FPS game and I have the following issue:
Sometimes, when I shoot at the enemies the hit is not recognized, even if the player is shooting in front of them. However, when they attack the player, the hit is recognized normally.
They have a box collider and a rigidbody attached to them.
This script is attached to the player:
using System.Collections.Generic;
using UnityEngine;
public class DisparaArma : MonoBehaviour
{
private GerenciaArma gerenciaArma;
public float nDisparo = 15f;
private float TempoProximoDisparo;
public float damage = 20f;
private Animator ZoomCameraIn;
private bool zoomed;
private Camera Maincamera;
private GameObject mira;
// Start is called before the first frame update
void Start()
{
gerenciaArma = GetComponent<GerenciaArma>();
ZoomCameraIn = transform.Find(Tags.LOOK_ROOT).transform.Find(Tags.ZOOM_CAMERA).GetComponent<Animator>();
mira = GameObject.FindWithTag(Tags.MIRA);
Maincamera = Camera.main;
}
// Update is called once per frame
void Update()
{
Atira();
ZoomInAndOut();
}
void Atira()
{
if (Input.GetMouseButtonDown(0))
{
if(gerenciaArma.SelecionaArma().tipoBala == WeaponBulletType.BULLET)
{
gerenciaArma.SelecionaArma().AnimacaoTiro();
DisparaBala();
}
}
}
void ZoomInAndOut()
{
if (gerenciaArma.SelecionaArma().mira_tipo == TipoMira.AIM)
{
if (Input.GetMouseButtonDown(1))
{
ZoomCameraIn.Play(Animacoes.ZOOM_IN_ANIM);
// gerenciaArma.SelecionaArma().Aim(true);
mira.SetActive(false);
print("VaiZoom");
}
if (Input.GetMouseButtonUp(1))//
{
ZoomCameraIn.Play(Animacoes.ZOOM_OUT_ANIM);
//gerenciaArma.SelecionaArma().Aim(false);
mira.SetActive(true);
}
}
}
void DisparaBala()
{
RaycastHit hit;
if(Physics.Raycast(Maincamera.transform.position, Maincamera.transform.forward, out hit))
{
if (hit.transform.tag == Tags.ENEMY_TAG)
{
hit.transform.GetComponent<ScriptVida>().DanoAplicado(damage);
}
}
}
}
And this one is attached to the enemies:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class ScriptVida : MonoBehaviour
{
private IndioAnimações indio_Anim;
private NavMeshAgent navAgent;
private IndioController indio_Controller;
public float vida = 100f;
public bool is_Player, is_Cannibal, is_Tiger;
private bool morto;
// Start is called before the first frame update
void Awake()
{
if (is_Tiger || is_Cannibal)
{
indio_Anim = GetComponent<IndioAnimações>();
indio_Controller = GetComponent<IndioController>();
navAgent = GetComponent<NavMeshAgent>();
}
if (is_Player)
{
}
}
public void DanoAplicado(float damage)
{
if (morto)
return;
vida -= damage;
if (is_Player)
{
}
if (is_Tiger || is_Cannibal)
{
if (indio_Controller.EnemyState == EnemyState.PATROL)
{
indio_Controller.chase_Distance = 50f;
}
}
if (vida <= 0)
{
JogadorMorre();
morto = true;
print(vida);
}
}
void JogadorMorre()
{
if (is_Cannibal)//
{
GetComponent<Animator>().enabled = false;
GetComponent<BoxCollider>().isTrigger = false;
GetComponent<Rigidbody>().AddTorque(-transform.forward * 50f);
indio_Controller.enabled = false;
navAgent.enabled = false;
indio_Anim.enabled = false;
}
if (is_Tiger)
{
GetComponent<Animator>().enabled = false;
GetComponent<BoxCollider>().isTrigger = false;
GetComponent<Rigidbody>().AddTorque(-transform.forward * 50f);
indio_Controller.enabled = false;
navAgent.enabled = false;
indio_Anim.enabled = false;
}
if (is_Player)
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag(Tags.ENEMY_TAG);
for (int i = 0; i < enemies.Length; i++)
{
enemies[i].GetComponent<IndioController>().enabled = false;
}
GetComponent<Movimentação>().enabled = false;
GetComponent<DisparaArma>().enabled = false;
GetComponent<GerenciaArma>().SelecionaArma().gameObject.SetActive(false);
}
if (tag == Tags.PLAYER_TAG)
{
Invoke("RestartGame", 3f);
}
else
{
Invoke("TurnOffGameObject", 3f);
}
}
void RestartGame()
{
UnityEngine.SceneManagement.SceneManager.LoadScene("Gameplay");
}
void TurnOffGameObject()
{
gameObject.SetActive(false);
}
}
I think the problem is related to the box collider.
How could I solve this guys?

Player not moving to all waypoints.

Enemy character not moving to the 3rd waypoint. After moving to waypoint 2 it just stops and the idle animation plays. The character has a NavMeshAgent on it and it looks like the destination reached event is not being triggered when he gets to the waypoint. If anyone has had a situation like this before I would appreciate any information possible. I have been trying to figure out whats wrong for a few hours now and am starting to think it might not be any of the scripts.
here is the waypoint controller
using UnityEngine;
using UnityEngine.AI;
public class WaypointController : MonoBehaviour {
Waypoints[] waypoints;
public Transform target;
//NavMeshPath path;
int currentWaypointIndex = -1;
//private NavMeshAgent agent;
//EnemyCharacter enemy;
public event System.Action<Waypoints> OnWaypointChanged;
// Use this for initialization
void Awake () {
waypoints = GetWaypoints();
}
public void SetNextWaypoint() {
if (currentWaypointIndex != waypoints.Length)
currentWaypointIndex++;
if (currentWaypointIndex == waypoints.Length)
currentWaypointIndex = 0;
if (OnWaypointChanged != null)
OnWaypointChanged(waypoints[currentWaypointIndex]);
//Debug.Log("OnWaypointChanged == null: " + (OnWaypointChanged == null));
//Debug.Log("OnWaypointChanged != null: " + (OnWaypointChanged != null));
}
Waypoints[] GetWaypoints()
{
return GetComponentsInChildren<Waypoints>();
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Vector3 previousWaypoint = Vector3.zero;
foreach (var waypoint in GetWaypoints())
{
Vector3 waypointPosition = waypoint.transform.position;
Gizmos.DrawWireSphere(waypointPosition, .2f);
if (previousWaypoint != Vector3.zero)
Gizmos.DrawLine(previousWaypoint, waypointPosition);
previousWaypoint = waypointPosition;
}
}
}
Here is the EnemyPatrolPoints script
using UnityEngine;
[RequireComponent(typeof(AI_PathFinder))]
public class EnemyPatrolPoints : MonoBehaviour {
[SerializeField]
WaypointController waypointController;
[SerializeField]
float waitTimeMin;
[SerializeField]
float waitTimeMax;
AI_PathFinder pathfinder;
private void Start()
{
waypointController.SetNextWaypoint();
}
private void Awake()
{
pathfinder = GetComponent<AI_PathFinder>();
pathfinder.OnDestinationReached += Pathfinder_OnDestinationReached;
waypointController.OnWaypointChanged += WaypointController_OnWaypointChanged;
}
private void WaypointController_OnWaypointChanged(Waypoints waypoint)
{
pathfinder.SetTarget(waypoint.transform.position);
print("waypoint changed");
}
private void Pathfinder_OnDestinationReached()
{
SealForce_GameManager.Instance.Timer.Add(waypointController.SetNextWaypoint, Random.Range(waitTimeMin, waitTimeMax));
print("destination reached");
}
}
Here is the AI Pathfinder script`
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class AI_PathFinder : MonoBehaviour
{
[HideInInspector]
public NavMeshAgent agent;
public EnemyPatrolPoints enemyPatrolPoints;
[SerializeField] float distanceRemainingThreshold;
bool m_destinationReached;
bool destinationReached
{
get
{ return m_destinationReached; }
set
{
m_destinationReached = value;
if (m_destinationReached)
{
if (OnDestinationReached != null)
OnDestinationReached();
}
}
}
public event System.Action OnDestinationReached;
void Start()
{
agent = GetComponent<NavMeshAgent>();
//enemyPatrolPoints = GetComponent<EnemyPatrolPoints>();
}
public void SetTarget(Vector3 target)
{
agent.SetDestination(target);
}
void Update()
{
if (destinationReached)
return;
if (agent.remainingDistance < distanceRemainingThreshold)
destinationReached = true;
}
}
The lines
if (agent.remainingDistance < distanceRemainingThreshold)
destinationReached = true;
are never reached as long as destinationReached is true because of
if (destinationReached)
return;
You are setting it to true after the first waypoint is reached and then never reset it to false so your Update is always skipped in the future.
You should add it e.g. to
public void SetTarget(Vector3 target)
{
agent.SetDestination(target);
destinationReached = false;
}

How to hide plane prefab used for plane detection in ARKit using Unity?

I am building an app using ARKit for vertical plane detection.Once the plane is detected I need to turn off plane detection.Even after plane is detected it is still tracking and finding more planes.How to turn off when the plane is detected.
using System;
using System.Collections.Generic;
using UnityEngine.EventSystems;
namespace UnityEngine.XR.iOS
{
public class UnityARHitTestExample : MonoBehaviour
{
public Transform m_HitTransform;
public float maxRayDistance = 30.0f;
public LayerMask collisionLayer = 1 << 10; //ARKitPlane layer
public List<GameObject> Instaobj = new List<GameObject>();
public Transform ForSelect;
int Select;
UnityARCameraManager obj=new UnityARCameraManager();
UnityARGeneratePlane obb=new UnityARGeneratePlane();
bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
{
List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
if (hitResults.Count > 0) {
foreach (var hitResult in hitResults) {
Debug.Log ("Got hit!");
obj.Hideplane();
// obb.planePrefab.SetActive(false);
m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
return true;
}
}
return false;
}
// Update is called once per frame
void Update () {
#if UNITY_EDITOR //we will only use this script on the editor side, though there is nothing that would prevent it from working on device
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
//we'll try to hit one of the plane collider gameobjects that were generated by the plugin
//effectively similar to calling HitTest with ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent
if (Physics.Raycast (ray, out hit, maxRayDistance, collisionLayer)) {
//we're going to get the position from the contact point
m_HitTransform.position = hit.point;
Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
//and the rotation from the transform of the plane collider
m_HitTransform.rotation = hit.transform.rotation;
}
}
#else
if (Input.touchCount > 0 && m_HitTransform != null )
{
var touch = Input.GetTouch(0);
if ((touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) && !EventSystem.current.IsPointerOverGameObject(touch.fingerId))
{
var screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
ARPoint point = new ARPoint {
x = screenPosition.x,
y = screenPosition.y
};
// prioritize reults types
ARHitTestResultType[] resultTypes = {
//ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingGeometry,
ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
// if you want to use infinite planes use this:
//ARHitTestResultType.ARHitTestResultTypeExistingPlane,
//ARHitTestResultType.ARHitTestResultTypeEstimatedHorizontalPlane,
//ARHitTestResultType.ARHitTestResultTypeEstimatedVerticalPlane,
//ARHitTestResultType.ARHitTestResultTypeFeaturePoint
};
foreach (ARHitTestResultType resultType in resultTypes)
{
if (HitTestWithResultType (point, resultType))
{
return;
}
}
}
}
#endif
}
}
}
Below is the UnityARCameraManager
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.iOS;
public class UnityARCameraManager : MonoBehaviour {
public Camera m_camera;
private UnityARSessionNativeInterface m_session;
private Material savedClearMaterial;
[Header("AR Config Options")]
public UnityARAlignment startAlignment = UnityARAlignment.UnityARAlignmentGravity;
public UnityARPlaneDetection planeDetection = UnityARPlaneDetection.Horizontal;
public ARReferenceImagesSet detectionImages = null;
public bool getPointCloud = true;
public bool enableLightEstimation = true;
public bool enableAutoFocus = true;
private bool sessionStarted = false;
private ARKitWorldTrackingSessionConfiguration config;
// Use this for initialization
void Start () {
m_session = UnityARSessionNativeInterface.GetARSessionNativeInterface();
Application.targetFrameRate = 60;
//ARKitWorldTrackingSessionConfiguration config = new ARKitWorldTrackingSessionConfiguration();
config = new ARKitWorldTrackingSessionConfiguration();
config.planeDetection = planeDetection;
config.alignment = startAlignment;
config.getPointCloudData = getPointCloud;
config.enableLightEstimation = enableLightEstimation;
config.enableAutoFocus = enableAutoFocus;
if (detectionImages != null) {
config.arResourceGroupName = detectionImages.resourceGroupName;
}
if (config.IsSupported) {
m_session.RunWithConfig (config);
UnityARSessionNativeInterface.ARFrameUpdatedEvent += FirstFrameUpdate;
}
if (m_camera == null) {
m_camera = Camera.main;
}
}
void FirstFrameUpdate(UnityARCamera cam)
{
sessionStarted = true;
UnityARSessionNativeInterface.ARFrameUpdatedEvent -= FirstFrameUpdate;
}
public void SetCamera(Camera newCamera)
{
if (m_camera != null) {
UnityARVideo oldARVideo = m_camera.gameObject.GetComponent<UnityARVideo> ();
if (oldARVideo != null) {
savedClearMaterial = oldARVideo.m_ClearMaterial;
Destroy (oldARVideo);
}
}
SetupNewCamera (newCamera);
}
private void SetupNewCamera(Camera newCamera)
{
m_camera = newCamera;
if (m_camera != null) {
UnityARVideo unityARVideo = m_camera.gameObject.GetComponent<UnityARVideo> ();
if (unityARVideo != null) {
savedClearMaterial = unityARVideo.m_ClearMaterial;
Destroy (unityARVideo);
}
unityARVideo = m_camera.gameObject.AddComponent<UnityARVideo> ();
unityARVideo.m_ClearMaterial = savedClearMaterial;
}
}
// Update is called once per frame
void Update () {
if (m_camera != null && sessionStarted)
{
// JUST WORKS!
Matrix4x4 matrix = m_session.GetCameraPose();
m_camera.transform.localPosition = UnityARMatrixOps.GetPosition(matrix);
m_camera.transform.localRotation = UnityARMatrixOps.GetRotation (matrix);
m_camera.projectionMatrix = m_session.GetCameraProjection ();
}
}
public void Hideplane()
{
config.planeDetection = UnityARPlaneDetection.None;
}
}
I have tried using the Hideplane() method,still the blue plane is showing
I tried this in UnityhittestAR example.I was looking for something like FocusSquare example.Once the plane is detected when we touch the screen the object get placed and no more tracking
Its A temporary solution but it works. In your UnityARKitScene attach a new script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EventHandler : MonoBehaviour {
public GameObject MainPlane;
public GameObject DestroyedPlane;
public GameObject p;
public int Got;
private void Start()
{
Instantiate(p);
}
private void Update()
{
MainPlane = GameObject.Find("Plane");
if(MainPlane!=null){
if(Got==0){
MainPlane.name = "MainPlane";
Got = 1;
}
if(Got==1){
MainPlane = null;
DestroyedPlane = GameObject.Find("Plane");
Destroy(DestroyedPlane);
}
}
}
}

How can i access another script function if the script to access is not attached to the same gameobject?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Teleport : MonoBehaviour {
public GameObject player;
public Camera mainCamera;
public Camera firstCam;
public Camera camera;
private List<GameObject> TeleportBooths;
private TeleportationsCore tc;
private void Start()
{
InstantiateObjects gos = GetComponent<InstantiateObjects>();
TeleportBooths = new List<GameObject>();
TeleportBooths = gos.PrefabsList();
firstCam.enabled = false;
mainCamera.enabled = false;
camera.enabled = true;
for (int i = 0; i < TeleportBooths.Count; i++)
{
TeleportBooths[i].AddComponent<TeleportationsCore>();
}
tc = GetComponent<TeleportationsCore>();
WorkingBooth();
}
private void WorkingBooth()
{
player.transform.position = TeleportBooths[tc.WorkingBooth()].transform.position;
camera.transform.position = new Vector3(TeleportBooths[tc.WorkingBooth()].transform.position.x - 10, TeleportBooths[tc.WorkingBooth()].transform.position.y + 10, TeleportBooths[tc.WorkingBooth()].transform.position.z);
camera.transform.LookAt(TeleportBooths[tc.WorkingBooth()].transform);
}
private void Update()
{
WorkingBooth();
}
}
I'm doing:
tc = GetComponent<TeleportationsCore>();
But tc is null.
And the script i want to access to:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TeleportationsCore : MonoBehaviour
{
public float spinSpeed = 2.0f;
private bool rotate = false;
private bool exited = false;
private int boothIndex = 0;
private void Start()
{
WorkingBooth();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
Debug.Log("Player entered the hole");
rotate = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
Debug.Log("Player exited the hole");
rotate = false;
exited = true;
}
}
void Rotate()
{
if (rotate)
{
if (spinSpeed == 350)
{
rotate = false;
exited = true;
boothIndex++;
WorkingBooth();
}
else
{
transform.Rotate(Vector3.up, spinSpeed * Time.deltaTime);
spinSpeed += 1f;
}
}
if (rotate == false && exited == true)
{
transform.Rotate(Vector3.up, spinSpeed * Time.deltaTime);
if (spinSpeed > 0.0f)
spinSpeed -= 1f;
}
}
public int WorkingBooth()
{
return boothIndex;
}
private void Update()
{
Rotate();
}
}
What i want is after i attach the script to all gameobject to get access the function WorkingBooth on TeleportationsCore.
And i don't want to attach the TeleportationsCore to the GameObject Teleport is attached on. So what other ways i have to access the WorkingBooth on TeleportationsCore ? Making the WorkingBooth public static ?
Change this:
for (int i = 0; i < TeleportBooths.Count; i++) {
TeleportBooths[i].AddComponent<TeleportationsCore>();
}
to:
TeleportationsCore[] tCores = TeleportBooths.Select(booth => booth.AddComponent<TeleportationsCore>());
Now just pick the core you want from the list.
Attach the TeleportationsCore script to empty game object. To get its reference, use this:
TeleportationsCore core = FindObjectOfType<TeleportationsCore>();
Use it for example in the Start function, as it is a bit slow.
You can find more in documentation.

Categories

Resources