How do i get object position and transform position to it - c#

How do i localize other GameObject position
and Move to it (like teleport to that object) how can i do it?
BotController.Player
it's object what i want to get position of it and move to it (teleport)
i work on game hack

In case you already have reference to the target object you can just use this.position = BotController.Player.position anywhere in the object you wanna teleport.
public class EasyTeleporter : MonoBehavior
{
...
public void SomeFunction()
{
position = BotController.Player.position
}
}
If you are creating first person game and want to achieve something like teleporter to any object you should use raycasting for that.
For example you can take Unity default asset FirstPersonCharacter (available on asset store or you can add it when starting a new project) and add the following script to the FirstPersonCharacter gameobject (wich is child of FPSController prefab):
using UnityEngine;
using System.Collections;
public class PlayerTeleporter : MonoBehaviour
{
bool shooting = false;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
shooting = true;
}
}
void FixedUpdate()
{
if (shooting)
{
shooting = false;
RaycastHit hit;
// you are casting a ray in front of your camera wich hits the first collider in its path
if (Physics.Raycast(transform.position, transform.forward, out hit, 100f))
{
// normally you shouldn't teleport directly into the trget object
transform.position = hit.transform.position;
}
}
}
}
Generally you should clarify you question. What game you are creating, what are the target and object of teleportation and how do you wanna trigger that.

Related

Instantiate not showing object

I am trying to get a object to spawn at mouse position in unity 2d
whenever I click, but none of the objects are showing. It adds new clones in the hierarchy, but just not showing.
Here Is the script for the game controller object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gamecon : MonoBehaviour
{
public GameObject square;
public void Start()
{
}
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 spawnpos = Camera.main.WorldToScreenPoint(Input.mousePosition);
GameObject g =Instantiate(square, (Vector2)spawnpos, Quaternion.identity);
}
}
}
I cant find any answers on the web that apply to my situation.
Thanks for help.
The solution is to use the ScreenToWorldPoint method and not the WorldToScreenPoint because what you need is the world position to spawn your object.
Use the following code:
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 spawnpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
GameObject g =Instantiate(square, (Vector2)spawnpos, Quaternion.identity);
}
}

reference from various scripts causing problems [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
For some reason when I'm in the normal view in-game I am able to link the scripts that I need to call in order to make an animation like so
however, whenever I start the game it automatically removes them from the slots, and it doesn't work
I am completely clueless as to why this may be happening and unity keep giving me errors that say that I'm not setting an instance to my script I really have no clue why this may be happening.
I have 3 scripts that I'm working with that is giving me the problem
one is the main script for the enemy vision (I am referencing the other scripts in this one)
the second is the enemy animation script which makes him go from idle to attack and the third is an animation for the gun model since I had to make it follow the hands of the enemy
scripts attached bellow
1st script(enemyAI):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAi : MonoBehaviour
{
public bool detected;
GameObject target;
public Transform enemy;
public GameObject Bullet;
public Transform shootPoint;
public float shootSpeed = 10f;
public float timeToShoot = 1f;
public EnemyAni Animation;
public GunAni GunAnimation;
void Start()
{
Animation = GetComponent<EnemyAni>();
GunAnimation = GetComponent<GunAni>();
}
public void Update()
{
//makes the enemy rotate on one axis
Vector3 lookDir = target.transform.position - transform.position;
lookDir.y = 0f;
//makes enemy look at the players position
if (detected)
{
enemy.LookAt(target.transform.position, Vector3.up);
enemy.rotation = Quaternion.LookRotation(lookDir, Vector3.up);
}
if (detected == true)
{
Animation.LookPlayer = true;
GunAnimation.ShootPlayer = true;
}
if (detected == false)
{
Animation.LookPlayer = false;
GunAnimation.ShootPlayer = false;
}
}
//detects the player
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
detected = true;
target = other.gameObject;
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
detected = false;
}
}
}
2nd Script (EnemyAnimation):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAni : MonoBehaviour
{
public Animator animator;
public bool LookPlayer;
public void Start()
{
animator = GetComponent<Animator>();
}
public void Update()
{
if (LookPlayer == true)
{
animator.SetBool("IsShootingStill", true);
}
else
{
animator.SetBool("IsShootingStill", false);
}
}
}
3rd script (GunAnimation):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunAni : MonoBehaviour
{
public Animator animator;
public bool ShootPlayer;
public void Start()
{
animator = GetComponent<Animator>();
}
public void Update()
{
if (ShootPlayer == true)
{
animator.SetBool("IsShooting", true);
}
else
{
animator.SetBool("IsShooting", false);
}
}
}
Your code:
void Start()
{
Animation = GetComponent<EnemyAni>();
GunAnimation = GetComponent<GunAni>();
}
Searches the GameObject that holds the EnemyAI script for EnemyAni and GunAni. If the GameObject doesn't have those it will return null.
Sounds like you want to remove that code.
Note that if the scripts exist on a child of that GameObject you will need to use GetComponentInChildren
There are some things to review, good practices:
GameObject target is private for C#, but it is better to put private before.
variable names like Bullet Animation GunAnimation should always begin with lowercase, because they might be confused with a Class Name (search in internet for CamelCase and PascalCase).
Name should be clear. EnemyAni Animation is not clear enough, because Animation maybe any animation (player, enemy, cube, car, etc.).
It is better enemyAnimation to be clear, as you did with GunAnimation (only just with lower case at beginning)
As slaw said, the Animation must be in the GO attached.
about last item
Let's say you have an empty GO (GameObject) called GameObject1 and you attach EnemyAi script to it.
In Runtime (when game mode begins), it will try to find Animation = GetComponent<EnemyAni>();, but it won't find it
Why?
Because GetComponent<> searches for the Component(Class) that is in the <> (in this case EnemyAni) in its GO (in this case, GameObject1), but the unique script attached to GameObject1 is EnemyAI.
So, you have 3 options:
Attach EnemyAni to GameObject1
Create another GO (for example, GameObjectEnemyAni), attach the script EnemyAni and drag and drop GameObjectEnemyAni to GameObject1 and delete Animation = GetComponent<EnemyAni>(); in Start
Keep in mind: if you leave that line of code, instead of getting the script EnemyAni from GameObjectEnemyAni, it will run the code Animation = GetComponent<EnemyAni>(); in Start, and obviously, it won't find it
Create events. It's a really good practice for avoiding code tight coupling, but that is more advanced stuff.

ThirdPersonController collision not calling OnTriggerEnter event

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
public Transform target;
// Update is called once per frame
void Update ()
{
}
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Test")
{
this.transform.position = target.position;
}
}
}
I have a ThirdPersonController and i want it to collide with a cube or cylinder.
The script is attached to the ThirdPersonController.
I tried to add either to the cylinder or the cube Rigidbody turned on/off the Use Gravity and the Is Kinematic but nothing. It's not getting to the event.
ThirdPersonController uses CharacterController and OnControllerColliderHit is used for that not OnTriggerEnter.
Note that you must move it with the Move function not directly by its transform in order for OnControllerColliderHit to be called.
void OnControllerColliderHit(ControllerColliderHit hit)
{
}
Every thing is correct but the thing wrong here is you are changing the position of the object which is colliding with a second object , but the thing id the thing is the collider is already there.....
As it's alternative try to print any statement when collision happens like this
private void OnTriggerEnter(Collider other)
{
if (other.tag==your_tag)
{
print("message");
}
}

Unity reticle as a pointer

I have a 3d Unity game with few 3d objects in worldspace. I have a reticle in cameraspace. When reticle crosses each 3d object, I have a pointer -enter and pointer-exit event written. when mobile phone is moved the reticle moves, but the 3d object stays in worldspace. The reticle is not functioning as pointer. Although the touch event is working, I could not make reticle as a pointer. I have added physics raycast with the camera.
What mistake I am doing?
Okay, so you are trying to use a UI.Selectable event (Selectable.OnPointerEnter) on a non-UI object.
Assuming you have the reticle position in screen space, I highly recommend using Physics.Raycast from the a script attached to the Camera object, though it could simply reference the camera instance instead. We can use this combined with a "hitObject" to trigger custom reticle enter/exit/hover events as seen below:
CameraPointer.cs:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Camera))]
public class CameraPointer : MonoBehaviour {
private GameObject hitObject = null;
private Vector3 reticlePosition = Vector3.zero;
private Camera camera;
void Awake() {
camera = GetComponent<Camera>();
}
// Update is called once per frame
void Update () {
// TODO: Replace with reticle screen position
reticlePosition = Input.mousePosition;
// Raycast variables
Ray ray = camera.ScreenPointToRay(reticlePosition);
RaycastHit hit;
// Raycast
if (Physics.Raycast(ray, out hit)) {
if (hitObject != hit.transform.gameObject) {
if (hitObject != null) {
hitObject.SendMessage("OnReticleExit"); // Trigger "OnReticleExit"
}
hitObject = hit.transform.gameObject;
hitObject.SendMessage("OnReticleEnter"); // Trigger "OnReticleEnter"
} else {
hitObject.SendMessage("OnReticleHover"); // Trigger "OnReticleHover"
}
} else {
if (hitObject != null) {
hitObject.SendMessage("OnReticleExit"); // Trigger "OnReticleExit"
}
hitObject = null;
}
}
}
MyObject.cs:
using UnityEngine;
using System.Collections;
public class MyObject : MonoBehaviour
{
// Custom reticle events
void OnReticleEnter()
{
Debug.Log("Entering over " + this.name);
}
void OnReticleExit()
{
Debug.Log("Exiting over "+this.name);
}
void OnReticleHover()
{
Debug.Log("Hovering over "+this.name);
}
}

Making Destroyer (UnityC#)

I making simple runner game.
I want do have some block over which player which jump.
I make a prefab and quad.
Attached Spawn script:
using UnityEngine;
using System.Collections;
public class SpawnScript : MonoBehaviour {
public GameObject[] obj;
public float spawnMin = 1f;
public float spawnMax = 1f;
// Use this for initialization
void Start ()
{
Spawn();
}
void Spawn()
{
Instantiate(obj[Random.Range(0, obj.GetLength(0))], transform.position, Quaternion.identity);
Invoke("Spawn", Random.Range(spawnMin, spawnMax));
}
}
Also I attached Destroyer script:
using UnityEngine;
using System.Collections;
public class DestroyerScript : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Application.LoadLevel(1);
return;
}
if (other.gameObject.transform.parent)
{
Destroy(other.gameObject.transform.parent.gameObject);
}
else
{
Destroy(other.gameObject);
}
}
}
But when player enter this object nothing happens.
Screen of my Quad:
Where is my mistake?
You use OnTriggerEnter2D. If your collider not ticked isTrigger field, you can use OnCollisionEnter2D.
And also if your object has Normal (3D) collider you need to use 3D versions of them.
OnTriggerEnter or OnCollisionEnter.
And also you should read this.
UPDATE
After discussion and looking your project problem is your character doesnt hit the destroyer object's collider. It moves with your main camera. (Destroyer object is child object of camera). Because of that when you take your destroyer from camera's child object it works.
Any child object in the heirarchy inherits it's parents movement. So if the collider is on a child object of the camera, it will move when the camera moves.

Categories

Resources