- Home /
trying to move an object with no script by accessing its rigidbody2d component.
I have a slime sprite that will instantiate and fire a slime ball. As stated above, I am trying to move the slime ball by using velocity on its rigidbody component. The problem is that it will only instantiate without moving at all. I am getting zero errors and am very puzzled as to why my code is not working.
private bool SpawnBall;
public GameObject SlimeBallAttack;
public float slimeballX;
public float slimeballY;
public float slimeballSpeed;
public float ballVerticality;
public SlimeBallMove ballVelocity;
void Start()
{
SlimeE = GetComponent<Rigidbody2D>();
SlimeAnim = GetComponent<Animator>();
currentEnemyState = EnemyState.Idle;
mySpriteRenderer = GetComponent<SpriteRenderer>();
risk = 0;
random = true;
}
void Attack()
{
InvokeRepeating("RandomValue", 1f, 1f);
}
private void RandomValue ()
{
risk = Random.Range(0, 11);
attackMeter += risk;
if (attackMeter >= 20 && SlimeAnim.GetInteger("SlimeAttack") == 1)
{
attackMeter = 0;
SpawnBall = true;
}
if (SpawnBall == true)
{
if(mySpriteRenderer.flipX == false)
{
Instantiate(SlimeBallAttack, new Vector2(gameObject.transform.position.x + slimeballX, gameObject.transform.position.y + slimeballY), gameObject.transform.rotation);
SlimeBallAttack.GetComponent<Rigidbody2D>().velocity = new Vector2(slimeballSpeed * Time.deltaTime, ballVerticality);
}
if (mySpriteRenderer.flipX == true)
{
Instantiate(SlimeBallAttack, new Vector2(gameObject.transform.position.x - slimeballX, gameObject.transform.position.y + slimeballY), gameObject.transform.rotation);
SlimeBallAttack.GetComponent<Rigidbody2D>().velocity = new Vector2(-slimeballSpeed * Time.deltaTime, ballVerticality);
}
SpawnBall = false;
}
NOTE: the Attack() function is in update and is only called if a certain condition passes. Also, I have tried putting the code to instantiate and move the object in update but it is only instantiating with no movement.
Answer by Lysander · Jan 03, 2018 at 05:56 AM
You're trying to use functions on the components attached to the Prefab, not the object you just instantiated. These are two different objects. Instantiate returns a GameObject, so just assign that to a temporary variable, then use your GetComponent and such on that.
GameObject newSlime = Instantiate<GameObject>(SlimeBallAttack, new Vector2(gameObject.transform.position.x + slimeballX, gameObject.transform.position.y + slimeballY), gameObject.transform.rotation);
newSlime.GetComponent<Rigidbody2D>().velocity = new Vector2(slimeballSpeed * Time.deltaTime, ballVerticality);
Thanks so much, that was exactly what was wrong. Now I understand prefabs better :D
Your answer
Follow this Question
Related Questions
Object not moving according to the meshes..? 0 Answers
How to make a gameobject with rigidbody2D fly through the air? 2 Answers
Adding force to object hit by sword 0 Answers
How do add force to the left (x-axis) 2 Answers
Adding a child problem 0 Answers