Creating a parameter from a player object - c#

This might seem like a stupid question but I am having trouble passing a parameter into a constructor in one of my classes. The object I have created is a player object and I am trying to get its position in my enemy class. The reason why I am trying to do this is because I want my enemies to follow the player around the screen. I am using c# in psm to create this program. Any assistance is greatly needed.
This is my enemy class.
public class SmartEnemy:Enemy
{
private Player player;
private Vector3 vel, pos;
private static Random gen= new Random();
public SmartEnemy (GraphicsContext g, Texture2D t, Vector3 p, float pwr, Player pop) : base(g,t,p,pwr)
{
pos = p;
player = pop;
vel = new Vector3 (0, 0, 0);
sprite.Rotation = 0;
sprite.Center.X = 0.5f;
sprite.Center.Y = 0.5f;
}
public override void Update()
{
Vector3 playerPos= player.Pos;
double angle=Math.Atan2(playerPos.Y-sprite.Position.Y,playerPos.X- sprite.Position.X);
Vector3 vel=new Vector3((float)Math.Cos(angle),(float)Math.Sin(angle),0);
sprite.Position+=vel;
}
public override void Render()
{
sprite.Render();
}
}
//
}
This is my code in my Appmain that creates an enemy.
pieces.Add (new SmartEnemy(graphics, eTex, new Vector3(gen.Next (200,900), gen.Next (200,900),0),.5f));

Your SmartEnemy constructor expects a Player object, yet you're not supplying one in your code:
SmartEnemy(graphics, eTex, new Vector3(gen.Next (200,900), gen.Next (200,900),0),.5f));
Create a player object and send in:
Player p1 = new Player();
pieces.Add( new SmartEnemy(graphics, eTex, new Vector3(gen.Next (200,900), gen.Next (200,900),0),.5f, p1) );

Related

How to make Objects fall out of the sky randomly and then delete themselves when they go off-screen?

For Unity (Lastest Version & C#)
How do I make an object fall from the sky at random places (random x but fixed y) in a 2D game
How do I delete them when they get off-screen and create a timing between objects falling
Whenever I run the program it randomly creates object but keeps naming them this: myObj, myObj(Clone), myObj(Clone)(Clone), myObj(Clone)(Clone)(Clone) every time a new object is instantiated. More importantly the instantiate part keeps running, spawning a bunch of objects and not deleting them.
Also, I just don't get how to delete the objects as soon as they get out of from the camera. Do I have to create a different script for it or smthn?
public class RandomObjectsFalling : MonoBehaviour
{
public GameObject obj;
public float timebeforedie = 1f;
void Start()
{
StartCoroutine(SpawnBlocks());
}
IEnumerator SpawnBlocks()
{
while(x <= 1)
{
float randomPosition = Random.Range(-10f, 10f);
GameObject clone = (GameObject)Instantiate(prefab, new Vector3(randomPosition, 8, 0), Quaternion.identity); //problem is this keeps getting called creating a whole bunch of objects but they don't get destroyed
yield return new WaitForSeconds(timebeforedie);
Destroy(clone);
}
}
}
Use this code to Spawn Your Obj
public GameObject prefab;
public bool startSpawning;
public float spawnDelay;
private float _currentSpawnDelay;
private void Start()
{
_currentSpawnDelay = spawnDelay;
}
private void Update()
{
if (startSpawning)
{
_currentSpawnDelay -= Time.deltaTime;
if (_currentSpawnDelay < 0)
{
_currentSpawnDelay = spawnDelay;
var randomPosition = Random.Range(-10f, 10f);
Instantiate(prefab, new Vector3(randomPosition, 8, 0), Quaternion.identity);
}
}
}
And This To Destroy Them But This Code Need To be Attach On Obj You That you want to Spawn
private void Update()
{
if (gameObject.transform.position.x < -20)
{
Destroy(gameObject);
}
}
Attach The Destroy Code to your Obj Prefab

The Object you want to instantiate is null. Unity 3D

i have a problem with my unity code and i can't get it why it doesn't work. I am kinda new to unity, just starting to learn it. I have 4 prefabs with different name in the project tree, and i want a prefab to spawn every second, but i want it to be randomized without using "if"'s, so i tried to save the prefabs names in an array and then Instantiate the GameObject that has the same name with the value of the array. When i run my script in Unity it says that the object i want to instantiate is null, i tried to find an answer on the web, but i found nothing. Can you help me?
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawnnoif : MonoBehaviour
{
public GameObject cub;
public GameObject capsula;
public GameObject cilindru;
public GameObject sfera;
public int x;
public GameObject paleta;
public float delta;
public string[] a = { "cub", "capsula", "cilindru", "sfera" };
void Start()
{
Vector3 position = new Vector3(UnityEngine.Random.Range(-1.88f, 2.1f), 1, UnityEngine.Random.Range(-7.81f, -3.1f));
x = UnityEngine.Random.Range(0, 3);
Instantiate(GameObject.Find(a[x]), position, Quaternion.identity);
}
IEnumerator Spawn()
{
while (true)
{
Vector3 position = new Vector3(UnityEngine.Random.Range(-1.88f, 2.1f), 1, UnityEngine.Random.Range(-7.81f, -3.1f));
x = UnityEngine.Random.Range(0, 3);
Instantiate(GameObject.Find(a[x]), position, Quaternion.identity);
yield return new WaitForSeconds(1.0f);
}
}
}
Please don't use Find for this! It is extremely expensive! And unreliable!
This function only returns active GameObjects. If no GameObject with name can be found, null is returned.
Especially since it looks like you want to use this for prefabs that only exist in the Assets and not in the Scene this will always return null as it only finds objects from the Scene.
Rather use an array like
public GameObject[] Prefabs;
reference your objects here and simply do
Vector3 position = new Vector3(Random.Range(-1.88f, 2.1f), Random.Range(-7.81f, -3.1f));
Instantiate(Prefabs[Random.Range(0, Prefabs.Length)], position, Quaternion.identity);
To your IEnuemrator ... well, you never start this as a Coroutine so it is simply never running.
You can do it directly in Start using StartCoroutine
private void Start()
{
StartCoroutine(Spawn());
}
private IEnumerator Spawn()
{
while (true)
{
Vector3 position = new Vector3(Random.Range(-1.88f, 2.1f), Random.Range(-7.81f, -3.1f));
Instantiate(Prefabs[Random.Range(0, Prefabs.Length)], position, Quaternion.identity);
yield return new WaitForSeconds(1.0f);
}
}
actually you could even directly use
private IEnumerator Start()
{
while (true)
{
Vector3 position = new Vector3(Random.Range(-1.88f, 2.1f), Random.Range(-7.81f, -3.1f));
Instantiate(Prefabs[Random.Range(0, Prefabs.Length)], position, Quaternion.identity);
yield return new WaitForSeconds(1.0f);
}
}
If Start is declared as IEnumerator Unity automatically runs it as a Coroutine.
Or in such a simple case you could even use InvokeRepeating like
private void Start()
{
// second parameter is the initial delay
// last parameter the repeat interval
InvokeRepeating(nameof(Spawn), 0, 1.0f);
}
private void Spawn()
{
Vector3 position = new Vector3(Random.Range(-1.88f, 2.1f), Random.Range(-7.81f, -3.1f));
Instantiate(Prefabs[Random.Range(0, Prefabs.Length)], position, Quaternion.identity);
}
You could use an array of GameObjects (the prefabs) and assign them in the editor. Then you can assign as many prefabs as you want in the Inspector and spawn them randomly:
public class Spawnnoif : MonoBehaviour
{
public GameObject[] prefabs;
public int x;
public GameObject paleta;
public float delta;
void Start()
{
Vector3 position = new Vector3(UnityEngine.Random.Range(-1.88f, 2.1f), 1, UnityEngine.Random.Range(-7.81f, -3.1f));
x = UnityEngine.Random.Range(0, prefabs.Length);
Instantiate(prefabs[x], position, Quaternion.identity);
}
...
}

Unity 3D scripts move multiple objects

I have a problem. I'm doing a project in Unity 3D (c#), a 3D worlds editor. My problem is that I want to move multiple objects by selecting them. I managed to move one with my mouse cursor, but for multiple I failed :D
This is my code to move one :
public class ClickAndDrag : MonoBehaviour {
private RaycastHit raycastHit;
private GameObject Gobj;
private float distance;
private Vector3 ObjPosition;
private bool Bobj;
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
if (Input.GetMouseButton (0)) {
var ray = GetComponent<Camera> ().ScreenPointToRay (Input.mousePosition);
var hit = Physics.Raycast (ray.origin, ray.direction, out raycastHit);
if (hit && !Bobj) {
Gobj = raycastHit.collider.gameObject;
distance = raycastHit.distance;
Debug.Log (Gobj.name);
}
Bobj = true;
ObjPosition = ray.origin + distance * ray.direction;
Gobj.transform.position = new Vector3 (ObjPosition.x, ObjPosition.y, ObjPosition.z);
} else {
Bobj = false;
Gobj = null;
}
}
}
Thanks for your help!
private GameObject Gobj; is a variable for a single GameObject. Reformat it to private List<GameObject> objects; and instead of Gobj.transform.position = new Vector3 (ObjPosition.x, ObjPosition.y, ObjPosition.z) do this:
foreach (GameObject item in objects)
{
item.transform.position = new Vector3 (ObjPosition.x, ObjPosition.y, ObjPosition.z)
}
EDIT: In case you aren't sure about how to manipulate a List, List<T> has a set of built in functions to make it really easy. You can now just call objects.Add(newObject); to add an object, and objects.Remove(oldObject); to remove an object.

How to instantiate object class that contains GameObject? [duplicate]

This question already has answers here:
Declaring a new instance of a class in C#
(2 answers)
Closed 2 years ago.
I am attempting to instantiate a large number of "particles" using a C# script in Unity. I have created a particle class that contains the creation of a corresponding GameObject. The GameObject within each particle instance is a sphere. When attempting to instantiate a new particle (Particle p = new Particle(...)) I get a Unity warning that the 'new' keyword should not be used.
"You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor()"
What is the proper way to instantiate a number of instances of my particle class (each containing a singular sphere GameObject)?
Particle Class:
public class Particle : MonoBehaviour {
Vector3 position = new Vector3();
Vector3 velocity = new Vector3();
Vector3 force = new Vector3();
Vector3 gravity = new Vector3(0,-9.81f,0);
int age;
int maxAge;
int mass;
GameObject gameObj = new GameObject();
public Particle(Vector3 position, Vector3 velocity)
{
this.position = position;
this.velocity = velocity;
this.force = Vector3.zero;
age = 0;
maxAge = 250;
}
// Use this for initialization
void Start () {
gameObj = GameObject.CreatePrimitive (PrimitiveType.Sphere);
//gameObj.transform.localScale (1, 1, 1);
gameObj.transform.position = position;
}
// FixedUopdate is called at a fixed rate - 50fps
void FixedUpdate () {
}
// Update is called once per frame
public void Update () {
velocity += gravity * Time.deltaTime;
//transform.position += velocity * Time.deltaTime;
gameObj.transform.position = velocity * Time.deltaTime;
Debug.Log ("Velocity: " + velocity);
//this.position = this.position + (this.velocity * Time.deltaTime);
//gameObj.transform.position
}
}
CustomParticleSystem Class:
public class CustomParticleSystem : MonoBehaviour {
Vector3 initPos = new Vector3(0, 15, 0);
Vector3 initVel = Vector3.zero;
private Particle p;
ArrayList Particles = new ArrayList();
// Use this for initialization
void Start () {
Particle p = new Particle (initPos, initVel);
Particles.Add (p);
}
// Update is called once per frame
void Update () {
}
}
Any help is greatly appreciated!
Your code looks fine other than you may have accidentally typed the declaration wrong for gameObj
Change GameObject gameObj = new GameObject(); to just GameObject gameObj = null; in your Particle class.
The error specifically mentions that you cannot do what you did and in your Start() you are setting it like it mentioned.
EDIT: Looking at Particle, it inherits MonoBehaviour. You need to have gameObject create the instance for you using gameObject.AddComponent<Particle>();
http://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html
gameObject is defined on MonoBehaviour so you should have access to it already.

Wont allow me to create more than 1 LineRenderer

I am attempting to create LineRenderers at runtime(when the user presses a button).
My Problem: I can never create more than one LineRenderer. When I go to created the 2nd one, the LineRenderer object is always NULL.
What am I doing wrong? Can you provide advice on what I need to do to create more than one LineRenderer?
public class AppInit : MonoBehaviour {
public Vector3[] TEST_VERTICES;
public const int SPEED = 5;
public List<LineRenderer> lines;
// Use this for initialization
void Start () {
TEST_VERTICES = new Vector3[10] {new Vector3(0,0,0), new Vector3(10,10,10), new Vector3(30,10,50), new Vector3(30,40,50),
new Vector3(10,30,90), new Vector3(10,20,40), new Vector3(50,20,40), new Vector3(70,80,90),
new Vector3(10,70,20), new Vector3(60,10,0)};
lines = new List<LineRenderer>();
}
// Update is called once per frame
void Update () {
float x = Input.GetAxis ("Horizontal") * Time.deltaTime * SPEED;
float z = 0;
float y = Input.GetAxis ("Vertical") * Time.deltaTime * SPEED;
gameObject.transform.Translate (new Vector3(x,y,z));
}
void OnGUI() {
if (GUI.Button (new Rect(10,10,100,20), "Create"))
createString(TEST_VERTICES);
}
public bool createString( Vector3[] vertices ) {
LineRenderer lRend = gameObject.AddComponent ("LineRenderer") as LineRenderer;
//LineRenderer lRend = new LineRenderer();
lines.Add(lRend);
Debug.Log ("IS NULL"+(lRend == null).ToString ());
lRend.SetColors (new Color(100,0,0,100), new Color(0,0,100,100));
lRend.SetWidth(10, 1);
lRend.SetVertexCount(vertices.Length);
for (int i=0; i<vertices.Length; i++)
lRend.SetPosition(i, vertices[i]);
return true;
}
}
As Iridium points out, you can only add one component of each type to a gameobject. So you want to create a new game object for each new linerenderer. The simple way to do this here is to change:
LineRenderer lRend = gameObject.AddComponent("LineRenderer") as LineRenderer;
to:
LineRenderer lRend = new GameObject().AddComponent("LineRenderer") as LineRenderer;
Then if you need to access the linerenderer's gameobject later you can do so by lRend.gameObject. Or lines[index].gameObject.
A quick Google brings up this page: http://answers.unity3d.com/questions/47575/create-a-linerender-in-c.html which suggests that you cannot add multiple instances of the same type to a single GameObject, and suggests that multiple GameObject instances should be used instead.

Categories

Resources