I have a game object Ship with a script Ship.cs this game object then has a gameobject Child FillerShipRender which has 24 children named MountPointCannon.
Ship.cs
using UnityEngine;
using System.Collections;
public class Ship : MonoBehaviour {
public int cannonballs;
public GameObject CannonType;
// Use this for initialization
void Start () {
populateMountPoints ();
}
// Update is called once per frame
void Update () {
}
public int getCannonballs()
{
return cannonballs;
}
void populateMountPoints()
{
GameObject clone = new GameObject("myClone");
foreach (Transform t in GetComponentsInChildren<Transform>())
{
if (t.name == "MountPointCannon")
clone = Instantiate (CannonType, t.position, t.rotation) as GameObject;
clone.transform.parent = transform;
}
}
}
When run this instantiates 24 cannons using the MountPointCannons for the locations. Each cannon has a ShootCannon.cs script. I would like to have the ShootCannon script access the Ship.cs to determine how many cannonballs are available and take one to shoot. When I use the commented out line it does not work.
using UnityEngine;
using System.Collections;
public class ShootCannon : MonoBehaviour
{
public Rigidbody projectile;
public Transform barrelEnd;
public int force;
public Quaternion rotation;
void Start()
{
}
void Update ()
{
if(Input.GetButtonDown("Fire1"))
{
Rigidbody ball;
ball = Instantiate(projectile, barrelEnd.position, rotation) as Rigidbody;
ball.AddForce(barrelEnd.right * force);
//Debug.Log (transform.parent.GetComponent(Ship).Cannonballs);
}
}
}
I get the following errors in unity when I uncomment this line
Also in MonoDevelop “Cannonballs” within the commented area is displayed in red…
I have no idea how to reference another script looked online and this seemed the right way to do so in this situation but I guess I am wrong. Any help would be appreciated.