クラス BlueShip のクラス BasicLaser からイベントをインストールしようとしているので、基本的にこのイベントは n 時間単位ごとに発生します。
以下は、統一されたスプライトに「接続」されたクラス BlueShip です。
using UnityEngine;
using System.Collections.Generic;
using System.Timers;
using System;
public class BlueShip : MonoBehaviour
{
enum LaserTypes { BASIC_LASER };
private float speed_ = 100f;
private List<GameObject> laser_ = new List<GameObject>();
private GameObject currentLaser_;
private Transform transform_;
private Vector3 currentPosition_;
private bool isElapsed_ = true;
// Use this for initialization
void Start()
{
transform_ = transform;
/*Basic laser is the default and it's guaranteed to be installed at the beginning of the game*/
laser_.Add((GameObject)Resources.Load("BasicLaser"));
currentLaser_ = laser_[(int)LaserTypes.BASIC_LASER];
laser_[0].GetComponent<BasicLaser>().timerElapsed += new TimerElapsed (BasicLaser_timerElapsed);
//HERE I'M adding observer to this event but look for line named *2 in class BasicLaser
}
public void BasicLaser_timerElapsed(object sender, EventArgs e)
{/*this is supposed to react to event timerElapsed in BasicLaser*/
isElapsed_ = true;
}
// Update is called once per frame
void Update()
{
var amtToMove = Input.GetAxis("Horizontal") * speed_ * Time.deltaTime;
transform_.Translate(Vector3.right * amtToMove);
/*Those below set the position for laser to be instantiated at*/
currentPosition_.x = transform_.position.x;
currentPosition_.y = transform_.position.y + (this.transform.localScale.y / 2) + currentLaser_.transform.localScale.y;
currentPosition_.z = transform_.position.z;
if (Input.GetKeyDown(KeyCode.UpArrow))
{
if (isElapsed_)
{
var t = Instantiate(laser_[(int)LaserTypes.BASIC_LASER], currentPosition_, Quaternion.identity);
isElapsed_ = false;
}
}
}
}
//BasicLaser class which is "connected" to a BasicLaser prefab in unity
using UnityEngine;
using System.Collections;
using System.Diagnostics;
using System;
public delegate void TimerElapsed(object sender,EventArgs e);
public class BasicLaser : MonoBehaviour
{
private float speed_ = 500f;
private static uint frequency_ = 2;//the frequency with which this laser can be fired
private static Stopwatch stopWatch_ = new Stopwatch();
public event TimerElapsed timerElapsed;//HERE IS THE EVENT
public uint Frequency
{
get { return frequency_; }
set { frequency_ = value; }
}
private Transform transform_;
// Use this for initialization
void Start()
{
transform_ = transform;
stopWatch_.Start();
}
// Update is called once per frame
void Update()
{
var amtToMove = speed_ * Time.deltaTime;
transform_.Translate(Vector3.up * amtToMove);
var t = stopWatch_.Elapsed.Milliseconds;
if (t > frequency_)
{
stopWatch_ = new Stopwatch();
stopWatch_.Start();
if (timerElapsed != null)//*2 THIS IS ALWAYS NULL!!!
even though I've hooked it in BlueShip class, what's going on?
{
timerElapsed(this, EventArgs.Empty);//raises the event
}
}
if (transform.position.y >= Screen.height)
{
Destroy(gameObject);
}
}
}