How to change a parent class variable from child class in unity The 2019 Stack Overflow Developer Survey Results Are InHow to get the type of T from a member of a generic class or method?How do I update the GUI from another thread?How to get the list of properties of a class?Unable to Cast from Parent Class to Child ClassDatabinding issue with stopwatched elapsedArray of textbox and labels how to get value in submit method in c#Custom array for each object of the same classWandering AI in unity C#Unity - Networking. Host can't see client changesHow to convert keyboard controls to touch screen in Unity
If I score a critical hit on an 18 or higher, what are my chances of getting a critical hit if I roll 3d20?
writing variables above the numbers in tikz picture
Why not take a picture of a closer black hole?
Worn-tile Scrabble
Why doesn't UInt have a toDouble()?
Match Roman Numerals
How did passengers keep warm on sail ships?
Why couldn't they take pictures of a closer black hole?
How can I define good in a religion that claims no moral authority?
Why are there uneven bright areas in this photo of black hole?
What do hard-Brexiteers want with respect to the Irish border?
Does adding complexity mean a more secure cipher?
How to notate time signature switching consistently every measure
Is it ok to offer lower paid work as a trial period before negotiating for a full-time job?
How do PCB vias affect signal quality?
Is it correct to say the Neural Networks are an alternative way of performing Maximum Likelihood Estimation? if not, why?
Mathematics of imaging the black hole
What does Linus Torvalds mean when he says that Git "never ever" tracks a file?
Can withdrawing asylum be illegal?
Geography at the pixel level
What could be the right powersource for 15 seconds lifespan disposable giant chainsaw?
Correct punctuation for showing a character's confusion
Keeping a retro style to sci-fi spaceships?
How come people say “Would of”?
How to change a parent class variable from child class in unity
The 2019 Stack Overflow Developer Survey Results Are InHow to get the type of T from a member of a generic class or method?How do I update the GUI from another thread?How to get the list of properties of a class?Unable to Cast from Parent Class to Child ClassDatabinding issue with stopwatched elapsedArray of textbox and labels how to get value in submit method in c#Custom array for each object of the same classWandering AI in unity C#Unity - Networking. Host can't see client changesHow to convert keyboard controls to touch screen in Unity
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I'm just starting out with Unity, and I'm making a basic 2d game using OOP principles for the characters.
I've created a general enemy class called EnemyController and it has a child called BasicEnemy.
The idea is that when the enemy is spawned (between two points, which are a bed and a bar in this case), it either moves to the left or right and starts to patrol between the objects.
I'm using raycasting for this, and so far when the enemy hits either of those points, I've gotten the ray to flip along with the sprite.
I can't seem to get the sprite to move in the newly flipped direction.
I've tried to modify the moveSpeed variable in the parent class, and I've tried to write my own movement functions LeftMove and RightMove.
My code is below.
This is the code for the Parent class:
public class EnemyController : MonoBehaviour
//transform for each of the enemies
protected Transform enemyTransform;
protected Vector2 startPosition;
protected int damageValue, healthLevel;
public int moveSpeed;
protected int randNum;
protected Rigidbody2D rb;
private void Start()
enemyTransform = transform;
startPosition = enemyTransform.position;
rb = GetComponent<Rigidbody2D>();
randNum = Random.Range(1,3);
// Debug.Log(randNum);
if(randNum == 1)
Debug.Log("Moves Left at the start");
if(randNum == 2)
Debug.Log("Moves Right at the start");
Flip();
private void FixedUpdate()
Move();
protected virtual void Move()
if(randNum == 1)
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if(randNum == 2)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
public void Flip()
Vector3 enemyScale = transform.localScale;
enemyScale.x *= -1;
transform.localScale = enemyScale;
This is the code for the Child class:
public class BasicEnemy : EnemyController
//Origin, Direction, Range for Raycasting.
public Transform rayOriginPoint;
private Vector2 rayDir = new Vector2(-1,0);
public float range;
//GameObjects that it should hit
GameObject bar, bed;
EnemyController parentClass;
private void Start()
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
private void Update()
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true)
if(hitObject.collider.name == bed.name)
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
LeftMove();
if(hitObject.collider.name == bar.name)
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
RightMove();
void LeftMove()
rb.velocity = new Vector2(-1, rb.velocity.y);
void RightMove()
rb.velocity = new Vector2(1, rb.velocity.y);
Can someone please help me with this?
Thanks in advance!
c# unity3d
|
show 2 more comments
I'm just starting out with Unity, and I'm making a basic 2d game using OOP principles for the characters.
I've created a general enemy class called EnemyController and it has a child called BasicEnemy.
The idea is that when the enemy is spawned (between two points, which are a bed and a bar in this case), it either moves to the left or right and starts to patrol between the objects.
I'm using raycasting for this, and so far when the enemy hits either of those points, I've gotten the ray to flip along with the sprite.
I can't seem to get the sprite to move in the newly flipped direction.
I've tried to modify the moveSpeed variable in the parent class, and I've tried to write my own movement functions LeftMove and RightMove.
My code is below.
This is the code for the Parent class:
public class EnemyController : MonoBehaviour
//transform for each of the enemies
protected Transform enemyTransform;
protected Vector2 startPosition;
protected int damageValue, healthLevel;
public int moveSpeed;
protected int randNum;
protected Rigidbody2D rb;
private void Start()
enemyTransform = transform;
startPosition = enemyTransform.position;
rb = GetComponent<Rigidbody2D>();
randNum = Random.Range(1,3);
// Debug.Log(randNum);
if(randNum == 1)
Debug.Log("Moves Left at the start");
if(randNum == 2)
Debug.Log("Moves Right at the start");
Flip();
private void FixedUpdate()
Move();
protected virtual void Move()
if(randNum == 1)
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if(randNum == 2)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
public void Flip()
Vector3 enemyScale = transform.localScale;
enemyScale.x *= -1;
transform.localScale = enemyScale;
This is the code for the Child class:
public class BasicEnemy : EnemyController
//Origin, Direction, Range for Raycasting.
public Transform rayOriginPoint;
private Vector2 rayDir = new Vector2(-1,0);
public float range;
//GameObjects that it should hit
GameObject bar, bed;
EnemyController parentClass;
private void Start()
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
private void Update()
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true)
if(hitObject.collider.name == bed.name)
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
LeftMove();
if(hitObject.collider.name == bar.name)
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
RightMove();
void LeftMove()
rb.velocity = new Vector2(-1, rb.velocity.y);
void RightMove()
rb.velocity = new Vector2(1, rb.velocity.y);
Can someone please help me with this?
Thanks in advance!
c# unity3d
Why not just flip the sprite rather than change the scale? then use x/y as the natural axis they come on
– BugFinder
Mar 8 at 11:01
@BugFinder won't that be the same as the Flip function I've written? As is, the sprite flips around. Could you please give me a code sample to understand? :)
– jerome
Mar 8 at 11:03
GetComponent<SpriteRenderer>().flipX = true; transform.scale changes other things.
– BugFinder
Mar 8 at 11:06
@BugFinder there's a few colliders and stuff that will need to be flipped too. That's why I've used the transform.scale bit. Mostly cuz I'm a little new to this.
– jerome
Mar 8 at 11:10
It looks as though randNum changes if your enemy moves in + or - move direction and this never changes in your Flip function
– Prodigle
Mar 8 at 11:13
|
show 2 more comments
I'm just starting out with Unity, and I'm making a basic 2d game using OOP principles for the characters.
I've created a general enemy class called EnemyController and it has a child called BasicEnemy.
The idea is that when the enemy is spawned (between two points, which are a bed and a bar in this case), it either moves to the left or right and starts to patrol between the objects.
I'm using raycasting for this, and so far when the enemy hits either of those points, I've gotten the ray to flip along with the sprite.
I can't seem to get the sprite to move in the newly flipped direction.
I've tried to modify the moveSpeed variable in the parent class, and I've tried to write my own movement functions LeftMove and RightMove.
My code is below.
This is the code for the Parent class:
public class EnemyController : MonoBehaviour
//transform for each of the enemies
protected Transform enemyTransform;
protected Vector2 startPosition;
protected int damageValue, healthLevel;
public int moveSpeed;
protected int randNum;
protected Rigidbody2D rb;
private void Start()
enemyTransform = transform;
startPosition = enemyTransform.position;
rb = GetComponent<Rigidbody2D>();
randNum = Random.Range(1,3);
// Debug.Log(randNum);
if(randNum == 1)
Debug.Log("Moves Left at the start");
if(randNum == 2)
Debug.Log("Moves Right at the start");
Flip();
private void FixedUpdate()
Move();
protected virtual void Move()
if(randNum == 1)
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if(randNum == 2)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
public void Flip()
Vector3 enemyScale = transform.localScale;
enemyScale.x *= -1;
transform.localScale = enemyScale;
This is the code for the Child class:
public class BasicEnemy : EnemyController
//Origin, Direction, Range for Raycasting.
public Transform rayOriginPoint;
private Vector2 rayDir = new Vector2(-1,0);
public float range;
//GameObjects that it should hit
GameObject bar, bed;
EnemyController parentClass;
private void Start()
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
private void Update()
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true)
if(hitObject.collider.name == bed.name)
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
LeftMove();
if(hitObject.collider.name == bar.name)
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
RightMove();
void LeftMove()
rb.velocity = new Vector2(-1, rb.velocity.y);
void RightMove()
rb.velocity = new Vector2(1, rb.velocity.y);
Can someone please help me with this?
Thanks in advance!
c# unity3d
I'm just starting out with Unity, and I'm making a basic 2d game using OOP principles for the characters.
I've created a general enemy class called EnemyController and it has a child called BasicEnemy.
The idea is that when the enemy is spawned (between two points, which are a bed and a bar in this case), it either moves to the left or right and starts to patrol between the objects.
I'm using raycasting for this, and so far when the enemy hits either of those points, I've gotten the ray to flip along with the sprite.
I can't seem to get the sprite to move in the newly flipped direction.
I've tried to modify the moveSpeed variable in the parent class, and I've tried to write my own movement functions LeftMove and RightMove.
My code is below.
This is the code for the Parent class:
public class EnemyController : MonoBehaviour
//transform for each of the enemies
protected Transform enemyTransform;
protected Vector2 startPosition;
protected int damageValue, healthLevel;
public int moveSpeed;
protected int randNum;
protected Rigidbody2D rb;
private void Start()
enemyTransform = transform;
startPosition = enemyTransform.position;
rb = GetComponent<Rigidbody2D>();
randNum = Random.Range(1,3);
// Debug.Log(randNum);
if(randNum == 1)
Debug.Log("Moves Left at the start");
if(randNum == 2)
Debug.Log("Moves Right at the start");
Flip();
private void FixedUpdate()
Move();
protected virtual void Move()
if(randNum == 1)
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if(randNum == 2)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
public void Flip()
Vector3 enemyScale = transform.localScale;
enemyScale.x *= -1;
transform.localScale = enemyScale;
This is the code for the Child class:
public class BasicEnemy : EnemyController
//Origin, Direction, Range for Raycasting.
public Transform rayOriginPoint;
private Vector2 rayDir = new Vector2(-1,0);
public float range;
//GameObjects that it should hit
GameObject bar, bed;
EnemyController parentClass;
private void Start()
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
private void Update()
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true)
if(hitObject.collider.name == bed.name)
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
LeftMove();
if(hitObject.collider.name == bar.name)
Debug.Log(hitObject.collider.name);
Flip();
rayDir *= -1;
RightMove();
void LeftMove()
rb.velocity = new Vector2(-1, rb.velocity.y);
void RightMove()
rb.velocity = new Vector2(1, rb.velocity.y);
Can someone please help me with this?
Thanks in advance!
c# unity3d
c# unity3d
asked Mar 8 at 10:54
jeromejerome
77111
77111
Why not just flip the sprite rather than change the scale? then use x/y as the natural axis they come on
– BugFinder
Mar 8 at 11:01
@BugFinder won't that be the same as the Flip function I've written? As is, the sprite flips around. Could you please give me a code sample to understand? :)
– jerome
Mar 8 at 11:03
GetComponent<SpriteRenderer>().flipX = true; transform.scale changes other things.
– BugFinder
Mar 8 at 11:06
@BugFinder there's a few colliders and stuff that will need to be flipped too. That's why I've used the transform.scale bit. Mostly cuz I'm a little new to this.
– jerome
Mar 8 at 11:10
It looks as though randNum changes if your enemy moves in + or - move direction and this never changes in your Flip function
– Prodigle
Mar 8 at 11:13
|
show 2 more comments
Why not just flip the sprite rather than change the scale? then use x/y as the natural axis they come on
– BugFinder
Mar 8 at 11:01
@BugFinder won't that be the same as the Flip function I've written? As is, the sprite flips around. Could you please give me a code sample to understand? :)
– jerome
Mar 8 at 11:03
GetComponent<SpriteRenderer>().flipX = true; transform.scale changes other things.
– BugFinder
Mar 8 at 11:06
@BugFinder there's a few colliders and stuff that will need to be flipped too. That's why I've used the transform.scale bit. Mostly cuz I'm a little new to this.
– jerome
Mar 8 at 11:10
It looks as though randNum changes if your enemy moves in + or - move direction and this never changes in your Flip function
– Prodigle
Mar 8 at 11:13
Why not just flip the sprite rather than change the scale? then use x/y as the natural axis they come on
– BugFinder
Mar 8 at 11:01
Why not just flip the sprite rather than change the scale? then use x/y as the natural axis they come on
– BugFinder
Mar 8 at 11:01
@BugFinder won't that be the same as the Flip function I've written? As is, the sprite flips around. Could you please give me a code sample to understand? :)
– jerome
Mar 8 at 11:03
@BugFinder won't that be the same as the Flip function I've written? As is, the sprite flips around. Could you please give me a code sample to understand? :)
– jerome
Mar 8 at 11:03
GetComponent<SpriteRenderer>().flipX = true; transform.scale changes other things.
– BugFinder
Mar 8 at 11:06
GetComponent<SpriteRenderer>().flipX = true; transform.scale changes other things.
– BugFinder
Mar 8 at 11:06
@BugFinder there's a few colliders and stuff that will need to be flipped too. That's why I've used the transform.scale bit. Mostly cuz I'm a little new to this.
– jerome
Mar 8 at 11:10
@BugFinder there's a few colliders and stuff that will need to be flipped too. That's why I've used the transform.scale bit. Mostly cuz I'm a little new to this.
– jerome
Mar 8 at 11:10
It looks as though randNum changes if your enemy moves in + or - move direction and this never changes in your Flip function
– Prodigle
Mar 8 at 11:13
It looks as though randNum changes if your enemy moves in + or - move direction and this never changes in your Flip function
– Prodigle
Mar 8 at 11:13
|
show 2 more comments
2 Answers
2
active
oldest
votes
private void FixedUpdate()
Move();
protected virtual void Move()
if(randNum == 1)
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if(randNum == 2)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
The above block in your base controller tells your enemy which direction to move in based on randNum.
void LeftMove()
rb.velocity = new Vector2(-1, rb.velocity.y);
void RightMove()
rb.velocity = new Vector2(1, rb.velocity.y);
This block in your inherited controller flips the velocity.
Immediately after the velocity is flipped from Left/Right move, the FixedUpdate calls and calls Move which then changes velocity back to what it was in randNum
Proposed Solution:
Store a bool directionRight, randomize it's value at creation,
in your fixedUpdate-Move
if(directionRight)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
else
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
have your flip function call directionRight =!directionRight to flip direction.
No longer any need for your move left/right functions
I get the logic of what you're saying. I still can't figure out a way to fix it though. Could you please help me with that?
– jerome
Mar 8 at 12:01
sure, writing now
– Prodigle
Mar 8 at 12:09
I tried your solution out. So what happens is that the boolean value that is instart()is set to false when the sprite moves left, and true when it moves right, and then whenMove()is called throughFixedUpdate(), the boolean value is reset to false. That happens, and I have a "NullReferenceException: Object reference not set to an instance of an object" atrb.velocity = new Vector2(moveSpeed, rb.velocity.y);Any ideas on what I'm doing wrong there?
– jerome
Mar 8 at 14:46
add a comment |
I managed to solve this issue by overriding the parent function in the child class.
private bool facingRight;
private void Start()
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
rb = GetComponent<Rigidbody2D>();
private void Update()
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true)
if(hitObject.collider.name == bed.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = true;
Flip();
if(hitObject.collider.name == bar.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = false;
Flip();
protected override void Move()
// rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
base.Move();
if(facingRight == false)
rb.velocity = new Vector2(-1, rb.velocity.y);
else
rb.velocity = new Vector2(1,rb.velocity.y);
Like @Prodigle said, I had a boolean that I changed in order to flip the sprite.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55061695%2fhow-to-change-a-parent-class-variable-from-child-class-in-unity%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
private void FixedUpdate()
Move();
protected virtual void Move()
if(randNum == 1)
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if(randNum == 2)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
The above block in your base controller tells your enemy which direction to move in based on randNum.
void LeftMove()
rb.velocity = new Vector2(-1, rb.velocity.y);
void RightMove()
rb.velocity = new Vector2(1, rb.velocity.y);
This block in your inherited controller flips the velocity.
Immediately after the velocity is flipped from Left/Right move, the FixedUpdate calls and calls Move which then changes velocity back to what it was in randNum
Proposed Solution:
Store a bool directionRight, randomize it's value at creation,
in your fixedUpdate-Move
if(directionRight)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
else
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
have your flip function call directionRight =!directionRight to flip direction.
No longer any need for your move left/right functions
I get the logic of what you're saying. I still can't figure out a way to fix it though. Could you please help me with that?
– jerome
Mar 8 at 12:01
sure, writing now
– Prodigle
Mar 8 at 12:09
I tried your solution out. So what happens is that the boolean value that is instart()is set to false when the sprite moves left, and true when it moves right, and then whenMove()is called throughFixedUpdate(), the boolean value is reset to false. That happens, and I have a "NullReferenceException: Object reference not set to an instance of an object" atrb.velocity = new Vector2(moveSpeed, rb.velocity.y);Any ideas on what I'm doing wrong there?
– jerome
Mar 8 at 14:46
add a comment |
private void FixedUpdate()
Move();
protected virtual void Move()
if(randNum == 1)
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if(randNum == 2)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
The above block in your base controller tells your enemy which direction to move in based on randNum.
void LeftMove()
rb.velocity = new Vector2(-1, rb.velocity.y);
void RightMove()
rb.velocity = new Vector2(1, rb.velocity.y);
This block in your inherited controller flips the velocity.
Immediately after the velocity is flipped from Left/Right move, the FixedUpdate calls and calls Move which then changes velocity back to what it was in randNum
Proposed Solution:
Store a bool directionRight, randomize it's value at creation,
in your fixedUpdate-Move
if(directionRight)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
else
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
have your flip function call directionRight =!directionRight to flip direction.
No longer any need for your move left/right functions
I get the logic of what you're saying. I still can't figure out a way to fix it though. Could you please help me with that?
– jerome
Mar 8 at 12:01
sure, writing now
– Prodigle
Mar 8 at 12:09
I tried your solution out. So what happens is that the boolean value that is instart()is set to false when the sprite moves left, and true when it moves right, and then whenMove()is called throughFixedUpdate(), the boolean value is reset to false. That happens, and I have a "NullReferenceException: Object reference not set to an instance of an object" atrb.velocity = new Vector2(moveSpeed, rb.velocity.y);Any ideas on what I'm doing wrong there?
– jerome
Mar 8 at 14:46
add a comment |
private void FixedUpdate()
Move();
protected virtual void Move()
if(randNum == 1)
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if(randNum == 2)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
The above block in your base controller tells your enemy which direction to move in based on randNum.
void LeftMove()
rb.velocity = new Vector2(-1, rb.velocity.y);
void RightMove()
rb.velocity = new Vector2(1, rb.velocity.y);
This block in your inherited controller flips the velocity.
Immediately after the velocity is flipped from Left/Right move, the FixedUpdate calls and calls Move which then changes velocity back to what it was in randNum
Proposed Solution:
Store a bool directionRight, randomize it's value at creation,
in your fixedUpdate-Move
if(directionRight)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
else
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
have your flip function call directionRight =!directionRight to flip direction.
No longer any need for your move left/right functions
private void FixedUpdate()
Move();
protected virtual void Move()
if(randNum == 1)
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
if(randNum == 2)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
The above block in your base controller tells your enemy which direction to move in based on randNum.
void LeftMove()
rb.velocity = new Vector2(-1, rb.velocity.y);
void RightMove()
rb.velocity = new Vector2(1, rb.velocity.y);
This block in your inherited controller flips the velocity.
Immediately after the velocity is flipped from Left/Right move, the FixedUpdate calls and calls Move which then changes velocity back to what it was in randNum
Proposed Solution:
Store a bool directionRight, randomize it's value at creation,
in your fixedUpdate-Move
if(directionRight)
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
else
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
have your flip function call directionRight =!directionRight to flip direction.
No longer any need for your move left/right functions
edited Mar 8 at 12:26
answered Mar 8 at 11:15
ProdigleProdigle
1,048317
1,048317
I get the logic of what you're saying. I still can't figure out a way to fix it though. Could you please help me with that?
– jerome
Mar 8 at 12:01
sure, writing now
– Prodigle
Mar 8 at 12:09
I tried your solution out. So what happens is that the boolean value that is instart()is set to false when the sprite moves left, and true when it moves right, and then whenMove()is called throughFixedUpdate(), the boolean value is reset to false. That happens, and I have a "NullReferenceException: Object reference not set to an instance of an object" atrb.velocity = new Vector2(moveSpeed, rb.velocity.y);Any ideas on what I'm doing wrong there?
– jerome
Mar 8 at 14:46
add a comment |
I get the logic of what you're saying. I still can't figure out a way to fix it though. Could you please help me with that?
– jerome
Mar 8 at 12:01
sure, writing now
– Prodigle
Mar 8 at 12:09
I tried your solution out. So what happens is that the boolean value that is instart()is set to false when the sprite moves left, and true when it moves right, and then whenMove()is called throughFixedUpdate(), the boolean value is reset to false. That happens, and I have a "NullReferenceException: Object reference not set to an instance of an object" atrb.velocity = new Vector2(moveSpeed, rb.velocity.y);Any ideas on what I'm doing wrong there?
– jerome
Mar 8 at 14:46
I get the logic of what you're saying. I still can't figure out a way to fix it though. Could you please help me with that?
– jerome
Mar 8 at 12:01
I get the logic of what you're saying. I still can't figure out a way to fix it though. Could you please help me with that?
– jerome
Mar 8 at 12:01
sure, writing now
– Prodigle
Mar 8 at 12:09
sure, writing now
– Prodigle
Mar 8 at 12:09
I tried your solution out. So what happens is that the boolean value that is in
start() is set to false when the sprite moves left, and true when it moves right, and then when Move() is called through FixedUpdate(), the boolean value is reset to false. That happens, and I have a "NullReferenceException: Object reference not set to an instance of an object" at rb.velocity = new Vector2(moveSpeed, rb.velocity.y); Any ideas on what I'm doing wrong there?– jerome
Mar 8 at 14:46
I tried your solution out. So what happens is that the boolean value that is in
start() is set to false when the sprite moves left, and true when it moves right, and then when Move() is called through FixedUpdate(), the boolean value is reset to false. That happens, and I have a "NullReferenceException: Object reference not set to an instance of an object" at rb.velocity = new Vector2(moveSpeed, rb.velocity.y); Any ideas on what I'm doing wrong there?– jerome
Mar 8 at 14:46
add a comment |
I managed to solve this issue by overriding the parent function in the child class.
private bool facingRight;
private void Start()
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
rb = GetComponent<Rigidbody2D>();
private void Update()
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true)
if(hitObject.collider.name == bed.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = true;
Flip();
if(hitObject.collider.name == bar.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = false;
Flip();
protected override void Move()
// rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
base.Move();
if(facingRight == false)
rb.velocity = new Vector2(-1, rb.velocity.y);
else
rb.velocity = new Vector2(1,rb.velocity.y);
Like @Prodigle said, I had a boolean that I changed in order to flip the sprite.
add a comment |
I managed to solve this issue by overriding the parent function in the child class.
private bool facingRight;
private void Start()
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
rb = GetComponent<Rigidbody2D>();
private void Update()
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true)
if(hitObject.collider.name == bed.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = true;
Flip();
if(hitObject.collider.name == bar.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = false;
Flip();
protected override void Move()
// rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
base.Move();
if(facingRight == false)
rb.velocity = new Vector2(-1, rb.velocity.y);
else
rb.velocity = new Vector2(1,rb.velocity.y);
Like @Prodigle said, I had a boolean that I changed in order to flip the sprite.
add a comment |
I managed to solve this issue by overriding the parent function in the child class.
private bool facingRight;
private void Start()
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
rb = GetComponent<Rigidbody2D>();
private void Update()
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true)
if(hitObject.collider.name == bed.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = true;
Flip();
if(hitObject.collider.name == bar.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = false;
Flip();
protected override void Move()
// rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
base.Move();
if(facingRight == false)
rb.velocity = new Vector2(-1, rb.velocity.y);
else
rb.velocity = new Vector2(1,rb.velocity.y);
Like @Prodigle said, I had a boolean that I changed in order to flip the sprite.
I managed to solve this issue by overriding the parent function in the child class.
private bool facingRight;
private void Start()
bar = GameObject.Find("minibar");
bed = GameObject.Find("bed");
rb = GetComponent<Rigidbody2D>();
private void Update()
RaycastHit2D hitObject = Physics2D.Raycast(rayOriginPoint.position,rayDir,range);
Debug.DrawRay(rayOriginPoint.position,rayDir*range);
if(hitObject == true)
if(hitObject.collider.name == bed.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = true;
Flip();
if(hitObject.collider.name == bar.name)
Debug.Log(hitObject.collider.name);
rayDir *= -1;
facingRight = false;
Flip();
protected override void Move()
// rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
base.Move();
if(facingRight == false)
rb.velocity = new Vector2(-1, rb.velocity.y);
else
rb.velocity = new Vector2(1,rb.velocity.y);
Like @Prodigle said, I had a boolean that I changed in order to flip the sprite.
answered Mar 8 at 16:59
jeromejerome
77111
77111
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55061695%2fhow-to-change-a-parent-class-variable-from-child-class-in-unity%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Why not just flip the sprite rather than change the scale? then use x/y as the natural axis they come on
– BugFinder
Mar 8 at 11:01
@BugFinder won't that be the same as the Flip function I've written? As is, the sprite flips around. Could you please give me a code sample to understand? :)
– jerome
Mar 8 at 11:03
GetComponent<SpriteRenderer>().flipX = true; transform.scale changes other things.
– BugFinder
Mar 8 at 11:06
@BugFinder there's a few colliders and stuff that will need to be flipped too. That's why I've used the transform.scale bit. Mostly cuz I'm a little new to this.
– jerome
Mar 8 at 11:10
It looks as though randNum changes if your enemy moves in + or - move direction and this never changes in your Flip function
– Prodigle
Mar 8 at 11:13