I am making my object follow the rotation of another object. I want my object to rotate with very little difference, that is, from its current rotation it should not rotate completely with the other object.
There should be a difference u pto its rotation such that it should rotate 10% of what the main object rotates. How do I do this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowRotationWithLimit : MonoBehaviour {
public GameObject objectToFollow;
// Start is called before the first frame update
void Start () {
}
// Update is called once per frame
void Update () {
this.transform.eulerAngles = new Vector3 (this.transform.eulerAngles.x, objectToFollow.transform.eulerAngles.y, this.transform.eulerAngles.z);
}
}
I am not able to get that logic of creating that difference.
I would rather call it FollowRotationWithFactor then and simply use a multiplier
public class FollowRotationWithFactor : MonoBehaviour
{
public GameObject objectToFollow;
public float factor = 0.1f;
// Update is called once per frame
void Update ()
{
var eulerAngles = transform.eulerAngels;
eulerAngles.y = objectToFollow.transform.eulerAngles.y * factor;
transform.eulerAngles = eulerAngles;
}
}
Related
I am making a turret that shoots a bullet at a set rate, but when the timer is done it doesn't spawn a new bullet even though it doesn't say i have any errors. the bullet has a simple script where it moves at a set speed either left or right, and gets destroyed on impact with an object. the turret does not have a collider right now so I know that's not the problem.
Here is the code for shooting:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurretShoot : MonoBehaviour
{
public GameObject bullet;
public int bullet_rate = 10;
public int timer;
public Transform SpawnPoint;
void Start()
{
timer = bullet_rate * 10;
}
// Update is called once per frame
void Update()
{
if (timer == 0)
{
Instantiate(bullet, SpawnPoint.transform);
timer = bullet_rate * 10;
}
else
{
timer -= 1;
}
}
}
Here is the bullet code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletMove : MonoBehaviour
{
public int moveDirection;
public int moveSpeed;
void Start()
{
}
// Update is called once per frame
void Update()
{
this.transform.position += new Vector3(moveDirection * moveSpeed, 0, 0);
}
void onCollisionEnter2D(Collider2D col)
{
if (col.GetComponent<Collider>().name != "turret_top")
{
Destroy(this);
}
}
}
Here is the inspector for the turret:
Probably what is happening is it get's destroyed when it spawns.
I don't have a collider on the turret
You aren't instantiating it at the turrent. You are simply setting the parent when you are instantiating it:
public static Object Instantiate(Object original, Transform parent);
Meaning it is probally spawning at Vector3.Zero and instantly gets de-spawn.
Rather use the overload method of:
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
That way you are spawning it the location you want. This is how you would go about it:
var bulletObj = Instantiate(bullet, SpawnPoint.transform.position, Quaternion.Identity);
bulletObj.transform.parent = SpawnPoint.transform;
timer = bullet_rate * 10;
I'm trying to use a UI Slider to change the movement speed for my player character using the GetComponent feature. I have everything working except apply the number(float) that I create from the movement of the slider to the variable that controls how fast the player can move.
I've used Debug.Log(); to determine that the variable I'm trying to grab from one script does not equal the other. It almost seems that they're being stored as two separate variables.
The varspeed variable keeps track of the number when I move the slider.
In script BallScript:
GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed = speedvar1;
Debug.Log(speedvar1);
In script PointBuyScript:
public void Start()
{
mySpeed.onValueChanged.AddListener(delegate { ValueChangeCheck(); });
}
public void LateUpdate()
{
varspeed = mySpeed.value;
Debug.Log(varspeed);
}
When I move the slider the number in the console from PointBuyScript scales with the Slider. However, the one from BallScript forever remains the same.
BallScript Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BallScript : MonoBehaviour
{
// Start is called before the first frame update
public float speed;
private Rigidbody rb;
public float speedvar1;
public float SpeedMain;
void Start()
{
rb = GetComponent<Rigidbody>();
speedvar1 = GameObject.Find("Canvas").GetComponent<PointBuyScript>().mySpeed.value;
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.00f, moveVertical);
speed = speedvar1; // this is where I try and update the speed variable to the slider number
rb.AddForce(movement * speed);
}
void LateUpdate()
{
Debug.Log(speedvar1);
Debug.Log(speed);
// Debug.Log(SpeedMain);
}
}
PointBuyScript Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PointBuyScript : MonoBehaviour
{
public Slider mySpeed;
public float varspeed;
public float mainSpeed;
public void Start()
{
// GameObject speed1 = GameObject.Find("Ball");
// BallScript hellome = speed1.GetComponent<BallScript>();
// varspeed = GameObject.Find("Ball").GetComponent<BallScript>().speed;
//Adds a listener to the main slider and invokes a method when the value changes.
mySpeed.onValueChanged.AddListener(delegate { ValueChangeCheck(); });
}
public void Update()
{
// Debug.Log(mySpeed.value);
//mainSpeed = mySpeed.value;
}
public void LateUpdate()
{
varspeed = mySpeed.value;
Debug.Log(varspeed);
}
// Invoked when the value of the slider changes.
public void ValueChangeCheck()
{
}
}
This code:
GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed = speedvar1;
Says "take the value in speedvar1 and assign it to PointBuyScript#varspeed." That is, the value of PointBuyScript#varspeed is changed (and speedvar1 remains unchanged).
You probably want:
speedvar1 = GameObject.Find("Canvas").GetComponent<PointBuyScript>().varspeed;
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
Hello I am new to coding in unity and i was trying to make the health bar go down when the player hits an object. When i use a debug.log it prints what i want it to print when it collides with the object however when i try to make the health go down when it hits the object it gives me this error
NullReferenceException:
Object reference not set to an instance of an object
DamagePlayer.OnCollisionEnter2D (UnityEngine.Collision2D collision)
(at Assets/Scripts/DamagePlayer.cs:30)
here is my code.
My Damage class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamagePlayer : MonoBehaviour
{
public BarScript bar;
public int playerHealth = 100;
int damage = 10;
// Start is called before the first frame update
void Start()
{
print(playerHealth);
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.collider.tag =="enemy")
{
Debug.Log("enemy");
bar.math(damage);
}
}
}
Health Bar class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BarScript : MonoBehaviour
{
private float fillAmount;
[SerializeField]
private Image content;
// Start is called before the first frame update
void Start()
{
fillAmount = 1f;
}
// Update is called once per frame
void Update()
{
content.fillAmount = fillAmount;
}
public float math(float value)
{
return fillAmount =(value / 100);
}
}
My Player class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Rigidbody2D rb;
[SerializeField]
private float speed = 300f;
private float jump = 400f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Movement();
}
void Movement()
{
if (Input.GetKeyDown("d")){
rb.velocity = new Vector2(speed * Time.fixedDeltaTime, rb.velocity.y);
}else if (Input.GetKeyDown("a"))
{
rb.velocity = new Vector2(-speed * Time.fixedDeltaTime, rb.velocity.y);
}else if (Input.GetKeyDown("space"))
{
rb.velocity = new Vector2(rb.velocity.x, jump * Time.fixedDeltaTime);
}
}
}
You haven't create an instance of BarScript in DamagePlayer, that's why this is creating problem.
Without instance you can't access member method of a class, you can use static to make that accessible by anyone. If it is just for Player then you can do that (Single-player), But it won't be so nice.
If you it's multi-player or you want do the same for enemy, then create prefab with both script, then instantiate or use pooling. Finally use findGameobjectsWithTag (not findGameobjectWithTag) and access those scripts, members and use their member methods.
I am a bit confused as to why this is, so basically Im trying to get it to where the camera follows the player without moving left and right with him.
using System.Collections;
using UnityEngine;
public class CameraMotor : MonoBehaviour {
private Transform lookAt;
private Vector3 startOffset;
private Vector3 moveVector;
void Start () {
GameObject.FindGameObjectWithTag ("Player").transform;
}
// Update is called once per frame
void Update () {
moveVector = lookAt.position + startOffset;
//X
moveVector.x = 0; //center of track
//Y[image][1]
moveVector.y = Mathf.Clamp(moveVector.y,3,5);// for ramps/stairs
transform.position = moveVector;
}
}
I think you want GameObject.FindWithTag
https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html
Even so,
GameObject.FindWithTag ("Player").transform;
does nothing. (Nothing usefull atleast)
lookAt is never assigned, so im guessing what you want to do is
lookAt = GameObject.FindWithTag ("Player").transform;
If you are looking for an object in your scene, then use this simple script;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnswerScript : MonoBehaviour {
private Transform lookAt;
// Use this for initialization
void Start () {
lookAt.Find("The Object That You are Looking For");
}
// Update is called once per frame
void Update () {
}
}
I just want to move a bullet (but it doesn't work) and test on cube (but the code too did not move the cube).
The commented codes also did not move the game object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movetest : MonoBehaviour
{
//public GameObject cube;
// Use this for initialization
public GameObject testmovecube;
public Rigidbody rb;
void Start () {
//testmovecube = this.GetComponent<GameObject>();
//rb = testmovecube.GetComponent<Rigidbody>();
move();
//
}
// Update is called once per frame
void Update () {
}
private void move()
{
testmovecube.transform.position =
Vector3.MoveTowards(transform.position, new Vector3(226, 1, 226) , 2);
//transform.Translate(Vector3.forward);
//rb.AddForce(Vector3.forward);
}
}
Please any help is appreciated.