- Home /
Problem is not reproducible or outdated
Can't figure class property
Hello!
I pass Vector3 parameter from external class in the method. Then assign it to class field. Then when I want to check class field value it says it is null. What am I doing wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CustProjectile : MonoBehaviour
{
Vector3 direction;
private void Start()
{
}
private void OnTriggerEnter(Collider other)
{
Destroy(gameObject);
}
public void InitiateProjectile(float speed, Vector3 direction)
{
Debug.Log(direction + "= PARAMETER FROM METHOD");
this.speed = speed;
this.direction = direction;
Debug.Log(this.direction + "= VALUE IN THE CLASS");
}
private void Update()
{
Debug.Log(this.direction + "= VALUE IN THE CLASS FROM UPDATE METHOD");
var dir2 = transform.position + direction;
transform.position += dir2 * speed * Time.deltaTime;
}
}
When i try this script and call InitiateProjectile from another script, it gives the right value in the update function. The speed variable is not defined though.
@metalted, https://youtu.be/DQeni3IfQvw, any ideas why this might not work for me? I deleted speed for question.
Well as mentioned, when i make two scripts with one containing this code, and the other containing a call to InitiateProjectile, it works fine. So there must be something outside these 2 scripts that's setting the direction variable. I believe that if there is no access modifier it will automatically be private. But you can try to add private in front of the direction variable, so that no outside script can access the variable directly. Another thing you could try is to not use similar variable names. There is nothing wrong with the this-keyword, but it might have strange behaviour in some cases. Change the parameter names of your function (or script, doesnt matter) so that you don't have to use the this-keyword and see if it helps anything.
Follow this Question
Related Questions
Vector3.MoveTowards doesnt work 1 Answer
Vector3.distance is always returning 0 4 Answers
How to Clamp LookAt on the Y Axis 1 Answer
Rotating game object to movement direction 1 Answer
Smooth movement for Gameobjects switching position 2 Answers