I have 2 scripts one on player :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerPositionCorrection : MonoBehaviour
{
Transform _playerTransform;
public float _xAxys;
public float _newXAxys;
public GameObject _changerPlayerPosition;
private void Start()
{
_playerTransform = GetComponent<Transform>();
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "ChangePlayerPosition")
{
float _newXAxys = this.GetComponent<ChangePositionOn>()._newPostion;
}
}
private void LateUpdate()
{
if (transform.position.z != 0)
{
transform.position = new Vector3(_xAxys, _playerTransform.position.y, _playerTransform.position.z);
}
}
and second on object :
public class ChangePositionOn : MonoBehaviour
{
public float _newPostion = 5;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
I using Unity 2022.1.19f1 and C#.
Thank you for your healp, Michal
I would like to have several object in my game and when player will collide with them change location on x axis.
Unfortunately every time i have this error message:
NullReferenceException: Object reference not set to an instance of an object
PlayerPositionCorrection.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/PlayerPositionCorrection.cs:23)
CodePudding user response:
- Check if the ChangePositionOn script is attached to the player gameObject.
- remove the float decalaration in the function because it makes it a local variable
- replace your function with this instead
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("ChangePlayerPosition"))
{
Debug.Log("Check if Collided With : " other.gameObject.name);
_newXAxys = this.GetComponent<ChangePositionOn>()._newPostion;
Debug.Log("New XAxys value : " _newXAxys );
}
}
CodePudding user response:
Make a new script PositionCorrector and Attach it to the Collider GameObject :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PositionCorrector : MonoBehaviour
{
//this should be attached to Collider GameObject
//this is the X value you want to change to, each collider can have a different number.
public float _newXAxys=4;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("PlayerTag"))
{
//changing the x axys of the player position
other.transform.position = new Vector3(_newXAxys, other.transform.position.y, other.transform.position.z);
}
}
}