Hey Friends I am working on a angry bird like game. In which i have used a spring joint and many game objects(balls) initilises one by one.
i am not happy with it i want to initialize a ball by loop every time through the ball.
please guide me thanx
You can create a prefab by dragging and dropping the ball on the project folder and use the Instantiate method inside a loop to “initialize” it on your game .
public GameObject ball // Set this value in the inspector by dragging and dropping the prefab
void Start(){
GameObject ballObject; // a temporary holder for the instantiated object
for(i=0;i<length;i++){ // loop for instantiating balls
ballObject = Instantiate(ball); // instantiates a new prefab ball
ballObject.Transform.position = new Vector2(x,y) /*change x and y with the position where you want the balls to be located (you can use i to have consistent variation of location or a random range for random location)*/
//add other components here using the ballObject if you wish
}
}
Nothing Happend. Ball just Falling to Bottom
i want it to through with spring joint
Here is my code the ball.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Ball : MonoBehaviour {
public AudioClip Hit,leave;
private bool isPressed = false;
public Rigidbody2D rb;
public Rigidbody2D Holder;
public float releaseTime = .15f, loadtime;
public float maxDragDistance= 2.5f;
public GameObject nextBall;
public Text text;
public static int remaininghits=10;
public LevelManager levelmanager;
public TextControll textcontroll;
GameObject prefab;
// Use this for initialization
void Start(){
prefab = Resources.Load ("Projectile") as GameObject;
levelmanager = GameObject.FindObjectOfType<LevelManager> ();
levelmanager = GameObject.FindObjectOfType<LevelManager> ();
}
void Update(){
if (isPressed) {
//capture mouse pos;
Vector2 mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
if (Vector3.Distance (mousePos, Holder.position) > maxDragDistance)
rb.position = Holder.position + (mousePos - Holder.position).normalized * maxDragDistance;
else
rb.position = mousePos;
}
}
void OnCollisionEnter2D(Collision2D Collision){
AudioSource.PlayClipAtPoint (Hit, transform.position);
Debug.Log ("Collision Detected");
}
void OnMouseDown () {
isPressed = true;
rb.isKinematic = true;
}
void OnMouseUp () {
//on leaving the mouse
isPressed = false;
rb.isKinematic = false;
remaininghits--;
StartCoroutine(Release ());
}
IEnumerator Release(){
AudioSource.PlayClipAtPoint (leave, transform.position);
yield return new WaitForSeconds (releaseTime);
GetComponent<SpringJoint2D> ().enabled = false;
this.enabled = false;
//New ball
yield return new WaitForSeconds (2f);
if (nextBall != null) {
nextBall.SetActive (true);
Destroy (gameObject, 3f);
}
else {
yield return new WaitForSeconds (loadtime);
remaininghits=10;
Application.LoadLevel ("start");
}
}
}