- Home /
How can I spawn a bullet using PhotonNetwork.Instantiate()?
I am trying to spawn a bullet/projectile by using PhotonNetwork.Instantiate(). I have attached this code to the Main Camera:
using UnityEngine;
using System.Collections;
public class Ability1 : MonoBehaviour {
public GameObject projectile;
public float projectilespeed = 20;
void Update(){
if (Input.GetButtonDown ("Fire1")) {
Rigidbody clone =(Rigidbody)PhotonNetwork.Instantiate(projectile, transform.position, transform.rotation, 0);
clone.velocity = transform.TransformDirection(Vector3.forward * projectilespeed);
Destroy(clone.gameObject, 3);
}
}
}
I have referenced the "Bullet" prefab by dragging it into the projectile box. My project is structured like this: Assets>Player>Character 1>Resources>Bullet. It is also worth noting that I have another prefab in the same folder as "Bullet" called "Character 1". I get 3 errors when I run this code:
NullReferenceException: Object reference not set to an instance of an object
The best overloaded method match for
PhotonNetwork.Instantiate(string, UnityEngine.Vector3, UnityEngine.Quaternion, int)' has some invalid arguments 3. Argument
#1' cannot convertUnityEngine.GameObject' expression to type
string'
I have experimented and tinkered with the code and cant find a solution. Does anyone know what the problem is and how to fix it? Thank you in advanced.
Answer by kevinspawner · Dec 31, 2014 at 04:26 AM
Rigidbody clone =(Rigidbody)PhotonNetwork.Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
Not tested try this.
It didnt work, but I found a workaround by typing
Gameobject clone = (Gameobject)PhotonNetwork.Instantiate("projectile", transform.position, transform.rotation);
clone.rigidbody.velocity = Vector3.forward * projectilespeed;
Turns out you cant pass a variable into the first parameter of PhotonNetwork.Instatiate(). I have another issue though. Now, when I spawn a projectile, it does not face my current rotation.For example, I will turn my character to the left or right, but the bullets always travel along the z- axis. They should follow my rotation, like bullets co$$anonymous$$g out of the barrel of the gun that I am holding. Do you know how to fix this?
Your answer
Follow this Question
Related Questions
What does "Couldn't find matching instance in prefab" mean? 2 Answers
Instantiating prefabs: "The object of type GameObject has been destroyed". 1 Answer
"Prefab GameObject's can not be made active!" - Need a fix 1 Answer
InvalidCastException when Instantiating with photon (PUN) 2 Answers
Convert code to get prefab then sprite ? 0 Answers