I have a class called Bullet which contains a struct of bullet. How do I access variables contained in this structure, from another class using cSharp?
public class Bullet : MonoBehaviour
{
struct bullet
{
private float _shootForce;
public float shootForce // The force at which missiles travel
{
get{return _shootForce;}
set{_shootForce = value;}
}
}
}
It was a struct called Bullet before, but I wanted to put it into a class, so I named the class Bullet and the struct bullet.
I got it working now - and renamed some code. What I was missing was an instance of struct bullet(old name) in the Bullet class.
public class Bullet
{
public struct bulletData
{
private float _shootForce;
public float shootForce // The force at which missiles travel
{
get{return _shootForce};
set{_shootForce = value};
}
}
public bulletData playerBullet;
}
Then in another class I invoke the Bullet class with :
Bullet B = new Bullet();
I can then access the bulletData structure by code like :
You have a struct called bullet, but no instance of that struct. But what are you trying to achieve by having a class called “Bullet” containing a struct called “bullet”? That’s just wrong!
Like jheiling said: You don’t have an instance of your struct, only a definition. A definition is just some kind of a “blueprint”. It doesn’t contain any data. You have to create an instance of that struct. It’s the same for classes. A class definition just tells the compiler how an instance of this class looks like. In Unity by dragging a class onto a GameObject you create an instance of this class. If you want the class instance have an instance of your struct, you should create one and store it in a variable. Something like that:
public class Bullet : MonoBehaviour
{
private struct bullet
{
private float _shootForce;
public float shootForce // The force at which missiles travel
{
get { return _shootForce; }
set { _shootForce = value; }
}
}
private bullet _bulletData;
private void Awake()
{
_bulletData = new bullet();
}
private void Update()
{
// do something with _bulletData
}
}
Some further notes:
Your struct is defined as private (private is the default visibility in C#) so you can’t use the type outside of your class.
If you define your struct as public you can use the struct anywhere by the full type-path. This declares a variable with the type of your struct: private Bullet.bullet myVariable;
Type names and method names should ALWAYS start with a capital letter. Variable names should always start lower-case. Usually properties also starts with a capital letter but some people treat them like variables.
You should also think about why you want to seperate some data / functions in a seperate struct and find a proper name for it. A struct “bullet” in a class “Bullet” really makes no sense. If the struct is responsible for a specific aspect of your class, find a proper name.