#💻┃code-beginner
1 messages · Page 511 of 1
No, but you can expose the backing field using SerializeField and mutate that from the inspector
The only issue is that it will not trigger the getter/setter of the property that uses it
ok, so you are a fan of
Vector3 pos = transform.position;
pos.y = 1f;
transform.position = pos;
because I am not
I'm a fan of
ref Vector3 pos = ref transform.position;
pos.y = 1f;
I think the average programmer is going to get confused by a value type that's suddenly working as a reference type
This kind of falls under being chaotic with your code simplification
is there any way an object can just will itself into existence without any code telling it to run? even in an empty scene my gamemanager object will show up and its kind of scary
I'm betting your singleton implementation will lazy load itself
using UnityEngine;
public abstract class SingletonPrefab<T> : MonoBehaviour where T : SingletonPrefab<T>
{
private static T _instance;
public static void CreateInstance()
{
if (_instance == null)
{
_instance = Instantiate(Resources.Load<T>(typeof(T).Name));
DontDestroyOnLoad(_instance);
}
}
public static T Instance
{
get
{
if (_instance == null)
{
_instance = Instantiate(Resources.Load<T>(typeof(T).Name));
DontDestroyOnLoad(_instance);
}
return _instance;
}
}
}
this is the code for the singleton im using
its not an issue or anything, if anything its helpful cus i can just slap the event system on there and other ddol scripts i need
Now look at the getter for your Instance property
yeah, but doesnt something have to get it for it to be created?
in an empty scene surely nothing is getting it right?
Something somewhere is accessing your GameManager.Instance
Could you quickly describe this please?
im trying to create a viking suffix name generator but it works different depending on the ending of a name. i wanted to ask, how would you go about checking the last few letters of a string in an efficient way?
i was originally thinking of just splitting it into characters and adding the last few together and comparing it, but that would be difficult since the endings of names are different lengths
or can you just use .Contains?
no need to split strings
https://learn.microsoft.com/en-us/dotnet/api/system.string.endswith?view=net-8.0
ive never seen this before, thank you
that also solves the issue .Contains would have caused (names including the letter combinations at the start or in the middle)
im a bit confused by the syntax here - does nameEndings[ending] return the key or the value in a dictionary<string, string>
Value
You could prefer iterating over the dictionary as a whole
That way you don't need to index into it again
Ideally one wouldn't iterate over a dictionary at all.
In this case the dictionary keys should probably be the suffixes if possible
Or if the suffixes aren't known ahead of time, a trie/prefix tree would be best here
the way i did it is the name endings are the keys, and the suffixes are the values
so the way it works is essentially for each name ending, there is an appropriate suffix
why do these menus on the left and bottem open after I start visual studio code? how can I turn it off?
public void PlaySFX(AudioClip clip, bool randPitch=false)
{
// Preprocess
float deltaPitch = UnityEngine.Random.Range(-0.6f, 0.6f) * (randPitch? 1 : 0);
SFXSource.pitch += deltaPitch;
// Play sound
SFXSource.PlayOneShot(clip);
// Return to Baseline
SFXSource.pitch -= deltaPitch;
}
why am i not hearing the pitch variation?
You set it immediately back to normal. It doesn't wait for the sound to finish playing
A coroutine that checks if the sound is still playing every frame, for example. Or design the function so that you don't need to set it back, just always set it to the correct pitch before playing sounds
public void PlaySFX(AudioClip clip, bool randPitch = false)
{
// Preprocess
if (randPitch)
{
SFXSource.pitch = SFXSourceDefaultPitch;
float deltaPitch = UnityEngine.Random.Range(-0.2f, 0.2f);
SFXSource.pitch += deltaPitch;
}
// Play sound
SFXSource.PlayOneShot(clip);
}
Worksss thanks 👑
👍 but that will keep the random pitch even if you later call it with randPitch false
For some reason my animation is stuck in the jump state but the code looks fine...
I'm using floats for both Blendspaces and assigned them each to their respective blendspaces...
But it doesn't auto-update the number whenever I do the movement
Anyone know why the animation is always stuck on Jump...?
The "else if" applies to the wrong if statement. Have the IDE format the code properly so that you see it better
Nice, that fixed the fall animation part in the jumping
But for some reason my Horizontal Movement animations aren't playing at all, (Idle, Walk, and Run)
Looks like your character is never set to the Grounded state
Ok nice, that fixed it, thank you
So basically I can control parameters straight from Unity...
I just have to worry aobut the logic in the code
Yeah, you'll just have to add some checks (using raycasting) to see if the character is on the ground or not and set it in code. Then it should work nicely.
Ok nice, nice, thank you, I appreciate you
I have both the Ground and Wall checkers based on some tutorials I watched, hopefully they work, I have to test them out
So been working on a game for a gamejam and tried using an fov effect
but it seems like the rotation is limited to the initial camera co-ordinates even when the camera moves away from 0,0,0
i have what i think is the likely offending line and a demonstration of the problem.
ive tried using different mousepos to co ordinate methods on the main cm but it doesnt help
im kinda at a loss witht this id really appreciate some help
Hey, im struggling with 2 Problems.
First One: Does anyone know, why the playersprite is micro-stutter while moving and has any fix idea for it?
The Second: Can i disable or whatever that the player can merge the Input Like W and A Key to go to Left and Top. I only want the movement to Top, Left, Right, Down.
I thanks in advance.
Code: ```public class PlayerController : MonoBehaviour
{
[SerializeField] private float walkSpeed = 5f;
[SerializeField] private float runSpeed = 5f;
[SerializeField] private SpriteRenderer spriteRenderer;
public Rigidbody2D rb;
private bool isRunning;
private Vector2 movementInput;
public void OnMove(InputValue value)
{
movementInput = value.Get<Vector2>();
}
private void FixedUpdate()
{
MovePlayer();
FlipSprite();
}
private void MovePlayer()
{
if (!Input.GetKey(KeyCode.LeftShift))
{
Vector3 move = new Vector3(movementInput.x, movementInput.y, 0) * walkSpeed * Time.deltaTime;
rb.MovePosition(transform.position + move);
}
else if (Input.GetKey(KeyCode.LeftShift))
{
Vector3 move = new Vector3(movementInput.x, movementInput.y, 0) * runSpeed * Time.deltaTime;
rb.MovePosition(transform.position + move);
}
}
private void FlipSprite()
{
// Flip the sprite based on the movement direction
if (movementInput.x > 0)
{
spriteRenderer.flipX = false;
}
else if (movementInput.x < 0)
{
spriteRenderer.flipX = true;
}
}
private void OnCollisionEnter2D(Collision2D other)
{
Debug.Log(other.gameObject.name);
}
}```
Well, yes, it will be relative to (0, 0, 0) because you're reading the mouse position and translating it to world position so you're getting a position relative to the center of the world, which is (0, 0, 0), and then not doing anything else with it.
Make it relative to the playerTransform instead, i.e. Vector3 lookingDirection = (mousePos - playerTransform.position).normalized;
Then use that with rotZ and most likely fieldOfView.SetAimDirection(lookingDirection) too
just put it in now and yes it works omg thx
didnt even think about it like that
1st: It's either because of the camera following the player in Update() instead of LateUpdate() or Rigidbody2D interpolation being turned off
2nd: Of course, either change your code so that it doesn't use both the X and Y input within MovePlayer() or change the value of movementInput within OnMove() so that only one axis has a value. If you mean how to do it using the input system itself, then I don't know.
@modest dust Yea, thats works fine. Thanks.
Do you happen to know how I manage to ensure that the vertical input is not preferred over the horizontal one? Everything is fine so far, but the thing is that if I hold down W and then press A or D, it continues to accelerate vertically, i.e. it goes up. However, if I hold down A or D and then press W or S, then it goes directly to the new input vertically.
If the input value you're reading is incorrect then I don't know, I've never used the new input system, try googling or ask in #🖱️┃input-system.
There's also a thing called keyboard ghosting which may sometimes be an issue, so also check that out, just in case.
@modest dust Okay, thanks. 🙂
i dont really know if this goes here but i need to copy code into a google doc, how do you do it? just copy pasting from vs looks bad
should probably check google's documentation to see if there is any code formatting available for it. but that's certainly not a unity question so it doesn't belong here.
also why would anyone want to share code in a google doc 😬
i would choose anything over a google doc but i have to do it that way
mayb i can just link pastebins or sth
which menus specifically? the file explorer and the panel? (output, problems, etc)
how do you expect to code without those?
you can always remove the file explorer entirely by right clicking its icon in the side bar
but then you... don't have a file explorer, so...
This is so pedantic, it's up to them
why do these menus on the left and
wait, we're supposed to use those? 
well, i just use vscode as my main ide for all languages. was just very taken aback cause i can't imagine how you even code without looking at your files
it's pretty quick to reenable the explorer when you need it
not false
i like looking at them inside unity
I think it's really nice when I can see more of my file, and there's less clutter on screen:
uh I still haven't been able to fix this
and how can I prevent the bottom menu from opening when the program is launched?
my inventory class has to communicate with my UI class to add items but i also need to do the opposite when UI buttons are pressed,
wouldnt this create circular dependency error or something. is that a thing in unity
how do ppl handle this type of stuff
Circular dependencies aren't a problem generally
But also
As far as inventory communicating with the UI
It's best to reverse that dependency using the observer pattern
So only the UI will depend on the inventory, not the other way around
i see, im assuming i add UI using player script then?
Not sure what you mean by that
When I say observer pattern I mean basically the UI scripts have a reference to the inventory and subscribe to events on it.
Rather than the inventory having a reference to the UI
oh i see, so inventory -> UI happens trough UnityEvents instead of using a reference?
UnityEvent or C# events
quick question, if i have a UI Manager object, that defines the UI logic (such as starting to play the game). and a Game Manager which defines the game logic (such as the actual sequence of starting up the game board, getting the players set up etc..), what is the best way to when clicking a button that the UI Manager is related to, to then execute the Game Manager Logic that is responsible for starting the game?
like i have this:
// UIManager
public void startPlaying()
{
// ??
// ??
// ...
}
attached to the play button
and i have this:
// GameManager
// Setup Game
void setupGame()
{
// Some Logic
// Some Logic
// ...
}
i can make the setup game public and then get a reference to GameManager with a tag for instance, then execute it from within the startPlaying function, but is that a good solution?
create in game manager public function for this button will execute say "OnButton1"
and when your button in UI manager acutaly clicked then wia external link init that functions like this ...SceneManager.OnButton1();
dont i want to encapsulate the button logic to operate from UI manager though?
sounds like you're suggesting making a public function anyway in Game Manager
that will depends on what are going to do in your function
if you want to just translate an object sometimes it is easier to have external link on that object and when button is clicker do something like this SceneManager.Object1.transform.translate....
but if there is many things to do it's beter to hafe function in scenemanager
yeah i think i have the latter
its like 40-60 lines of code in the setup funciton
i just want to call it when the paly button is called
but is it valid to make setup function public?
shouldnt i use events?
for now just do it i straightforward way and afterwards you anytime f will necessary can convert it in events
are events more proper way?
sometimes
but they re complicated and if you haven't necessary in them right now you can do it in simple way
any good tutorials for a level menu system with stars?
any good tutorials for a level menu
can i still use normal input like Input.GetAxis("Horizontal") instead of the input actions provided automatically with unity 6 urp scene?
sure, as long as you have active input system set to old or both
Hey I know this is a huge favor to ask, but would any one be okay to share a screen with me and help me with some code? I’m new and just can’t understand it at all. I’m following along closely with a video for homework but mine isn’t running like it is in the video. I’m in a class and have been trying to get help from my instructor for over a week, but have not been able to get in contact
not likely screenshare.. you are better off posting the video your'e following and your current code.
Show !code and say what the actual error is
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
👻
I am trying to make a 2d strategy game based on cold war but sadly idk unity well, where do I start? anyone help?
Why doesnt ground detect my legs collision and is there a way I can make arms kinematic but character still has gravity
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks
Question: how can I get the name of an object I just instantiated? Or at least have a reference to it? Am I able to just use this?
Debug.Log("Made object");
objectColor = this.GetComponent<SpriteRenderer>();```
Gameobject gm = Instantiate(…)
var myInstance = Instantiate(etc.. string theName = myInstance.name
but yeah I just shown example name you don't need that since you only need reference it seems lol
you almost never use gameobject names
it was working fine until I decided to have random colors applied and then the spawn count didn't go up and I suddenly had hundreds of objects
depends where you're calling this instantiate function
Your are changing the color of your spawn manager
also this ^
You are calling “this”, so you are getting everytime the sprite of the object that has attached your manager script
I have it being called in update, it's just a stupid asteroids clone and it's spawning a new one when the count is less than 4
Well
are you resetting the count back up ?
I didn't have it as this originally, but the way I was doing it also wasn't working 
doesn't seem you have any type of delay so its gonna spawn them all at once, not ideal
a loop is better if you want multiple ones spawned at once
A courutine should fix this problem
yeah I have the count going up when one is spawned but when I tried to add color to it, it was breaking because there wasn't a reference to the spawned asteroid so it never got to the part where it added 1 to the count
Ops I responded to the wrong message
⬆️
You should reference the object that you are spawning not your manager
yes but that alone would only change it on the wrong sprite renderer but not cause freezeup, what you see is probably them spawning at once and count being out of sync
Since your manager is probably an empty object, it cannot find any sprite renderer attached to it, and it is giving you an error
I wasn't trying this, I was trying
objectColor = objects[randomObject].GetComponent<SpriteRenderer>();
instead of this
Also this
but I'm realizing it was just getting the color of the prefab, not the one that was spawned
this would change the original prefab or whatever original clone it was
Is all of this in a for loop then?
I just wasn't sure if this.GetComponent was going to do it or if I was going to go down the wrong rabbithole
this is always referencing the script you're in
{
if (asteroidCount < 4)
{
SpawnAsteroid();
}
}```
you 99% of the time don't need to use this
oh so this only spawns if its like 3 or something
and it wasn't getting the referrence to the spawned one so the script broke and never added to the counter and as soon as I hit play I got hundreds of them lmao
Yeah, its because you are not counting when one of them is no longer there
how are you counting them up?
So it will remain 4 all the time
No, I have it decrease when one is destroyed
I highly suggest you to do a Debug.Log(asteroidcount);
the issue would be if its not being added to list so anything less than 4 and keep spawning
Anche check if at any point it goes under 4
I just wanted to add colors
jesus..
I did the debug, it was telling me I didn't have a reference and that's why i just needed to learn how to get that
lmao it's so stupid isn't it
so, do this:
Var myinstance = Instantiate(…);
SpriteRenderer spr = myinstance.GetComponent<SpriteRenderer>();
perfect, let me give that a go
ig don't forget the random Poo obstacles
And then check if it still gives you an error, and keep a debug.log of that int
i was thinking of doing that instead of smaller butts
or just make some of them as shooters of projectiles and its just firepoint from butthole lol
that is absolutely terrifying
even better than this would be making the prefab variable a SpriteRenderer type, then Instantiate will return the instantiated SpriteRenderer removing the need for the GetComponent call (unless they are already using another component type that they care about rather than just GameObject)
it would automatically get the instanced objects sprite renderer?
what have I been doing
yes cause its cloning prefab as sprite renderer
neat, good to know
I'm not sure I follow, like instead of having an array of GameObjects make it an array of SpriteRenderer?
thought I prefer using another script that runs its own Custom / Setup methods targetting specific components
(ofc use cases for this is more complex than 1 component)
eg
MyScript theScript = Instantiate(etc..
theScript .SetText("Somethinng")
theScript .DoMoreStuff();
instead of
MyScript theScript = Instantiate(etc..
theScript.GetComponent<TMP_Text>().text = "Something";```
It depends on what you want to do there
if you need to access something else within the gameobject, best stick with the array of gameobjects
yeah I do need to access some other parts, but it's good to know I can do that if i need to access ONLY that
If you only need the sprite render then make a SpriteRenderer array, if you need something else from the spawning objects you better save that as a GameObject array
you're welcome
make the array of a type you care most about. you can always call GetComponent on any component to get lesser needed components. there is almost never a reason to have a GameObject variable because of that
So quick question, is unity learn a good place to learn coding patterns?
yup they have a few there
but if you want specific things check out this PDF
https://unity.com/resources/level-up-your-code-with-game-programming-patterns
Thanks!
np . also check out this site, for other more useful types of design patters that come in handy
(observer pattern is def a top one to learn for sure)
https://refactoring.guru/design-patterns/csharp
Thanks again, will do
it's still giving me troubles, I've got this just to see if I could get it to work:
Debug.Log("New ass made");
buttColor = newAss.GetComponent<SpriteRenderer>();
Debug.Log("got new ass component");
randomColor = Random.Range(0, 2);
Debug.Log("got random color");
buttColor.color = assteroidsColors[randomColor];
Debug.Log("Applied color");
assteroidCount += 1;```
what are the "troubles"
and it's causing a reference error on the "buttColor.color = assteroidsColors[randomColor];" line
btw whenevr you random range an array is always best to use not magic numbers
use the length of array
so newAss doesnt have a buttColor component
or assteroidsColors is null
raher than doing such useless Debugs, use them to debug the components etc
I had them in there just to see at what point it was breaking
Debug.Log($"did we get buttColor ? {buttColor != null}");
yes but we print specific things to make them more useful
I think you could use a breakpoint
did we get buttColor ? True
Not sure if you can use that with visual studio on Unity
so it's likely something with the assteroidsColors array
did you initialize it
I did, then I appended the 3 colors in the start function
Could this be caused by using color32 instead of just color?
no they have implicit conversion
show full script !code use links
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok it's definitely something with the array, I tried to just do buttColor.color = color.green; and it was perfect
This would be handy, ‘cause you can see the variables changing during the execution of the script
show code lol
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I will definitely have to look more into this
yeah its not initialized
never used .append but ig it doesn't throw on a null array?
also why .append lol
well color me stupid, I thought private Color32[] assteroidsColors; was doing that lmao
nah only if you put [SerializeField] then unity Would do that for you since it shows in the inspector
unity has to initialize it in order for array / list to show in inspector
Because I'm still a baby with this stuff 😂
public or [serializefield]
much easier you do this in the inspector anyway
assign them with the color wheel and done.
I didn't even consider doing it in the inspector honestly, thanks!
np. lol never seen that append method before, just for future if you want to modify array you would use indexes / specific element . if you need to add more items to array use a list instead
I would also suggest you to change a lot of hard coded things, so when you need to change a value you can do it in the inspector
Without having to reload the script and find the right line to change
I definitely have much to learn, I appreciate the help, all of you
Okay thank you will do when I’m off
Off work that is
having issues im not sure if its because i wiped my pc and reinstalled everything i had my game backed up i get this warning
External Code Editor application path does not exist (C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\devenv.exe)! Please select a different application
UnityEditor.DefaultExternalCodeEditor:OpenProject (string,int,int)
Unity.CodeEditor.CodeEditor:OnOpenAsset (int,int,int)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
not only that the [SerializeField] use to be green idk if theres away to fix the color and stuff
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
thx
Such a good bot. Love all the prepared help messages it has.
SO i am REALLY new to unity so im follwing some videos. But all of them have
using System.Collections;
using system.Collections.Generic;
using UnityEngine;
already there when making a new script I only have unity engine. What are they and how do i get them?
Why do you want them
This is the default architecture of a monobehaviour when you create it from unity
do i need them? the vids i watch already have them so i assume i need them too
AHHH ok. ok... so i dont need them so thats why its not there?
yep
AHHH ok ok thank you
if (Input.GetMouseButton(1) && !Input.GetKeyDown(KeyCode.S))```
Why does this if statement still occur when I'm holding both S and right mouse at the same time?
if (Input.GetMouseButton(1) && !Input.GetKey(KeyCode.S))```
this works. Thanks
GetMouseButtonDown is only true on the exact frame when you first start pressing the button
Mornin all, Having a strange issue and was wondering if anyone could see the mistake?
I'm adjusting my 'fuelConsumptionPerSecond' based on key input. Now, the weird thing is that the left and right strafe works as expected, but the forward and back doesn't, and I'm at a bit of a loss as to why.
void ControlInput()
{
// Forward and Back movement Input
if (Input.GetKey(GameManager.Instance.controlsManager.forwardKey))
{
moveZ = Mathf.MoveTowards(moveZ, 1, lerpSpeed * Time.deltaTime);
playerStatsController.SetFuelConsumption(1f);
}
else if (Input.GetKey(GameManager.Instance.controlsManager.backwardKey))
{
moveZ = Mathf.MoveTowards(moveZ, -1, lerpSpeed * Time.deltaTime);
playerStatsController.SetFuelConsumption(1f);
}
else
{
moveZ = Mathf.MoveTowards(moveZ, 0, lerpSpeed * Time.deltaTime);
playerStatsController.SetFuelConsumption(0f);
}
// Strafe Left and Right movement Input
if (Input.GetKey(GameManager.Instance.controlsManager.leftKey))
{
moveX = Mathf.MoveTowards(moveX, -1, lerpSpeed * Time.deltaTime);
playerStatsController.SetFuelConsumption(1f);
}
else if (Input.GetKey(GameManager.Instance.controlsManager.rightKey))
{
moveX = Mathf.MoveTowards(moveX, 1, lerpSpeed * Time.deltaTime);
playerStatsController.SetFuelConsumption(1f);
}
else
{
moveX = Mathf.MoveTowards(moveX, 0, lerpSpeed * Time.deltaTime);
playerStatsController.SetFuelConsumption(0f);
}
}
The forward and back always returns 0.
as in fuelConsumptionPerSecond is 0?
you';re independently doing this for both sets of if/else statements:
playerStatsController.SetFuelConsumption(0f);```
Yes, but only on the forward/back, on the left/right it returns 1 as expected.
true, your left and right "else" statement runs after you set fuel consumption to 1 in the forward and backward if statement
Ah okay. Thank you.
Quick dirty example fix: https://pastebin.com/0wrhk9cf
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Just do a seperate check after setting moveX and moveZ to check if any of them are !=0 and set fuel consumption accordingly
this could all ultimately be simplified using a vector2 though
I think I could do a simple Rigidbody velocity check too?
you could but that doesn't seem like it makes sense for this code
the code is checking if you are applying thrust
not if your velocity is a certain thing
as in "are my engines on?"
Depends on what you want fuel consumption tied to
After you turn your engines off, typically you are still moving.
but not consuming fuel
Oh yeah, I was just thinking out loud regarding the different ways of performing that check if that makes sense?
What happens if an external source bumps your rigidbody ? Would that be considered fuel usage ?
Ah yeah, that's a fair point.
But yeah, the consumption is tied to when the keys are pressed (when the thrusters are active), so I think just checking if moveZ and moveX = 0 should do it?
yes
Cool. Thank you guys 🙂
how do i get a reference to an object that i dont know if its active or not at the time of trying to get its reference?
Why are you deactivating the object?
I usually don't do that if I have other ways
isnt that how i switch between UIs showing?
I'm not a professional but what UIs
More context please
Actually it sounds right to deactivate them to switch
Let me experiment a little. I'll see if I find anything or not
Okay I found that if you hold the reference before deactivating it works
Just hold a reference to all of your UI elements in Start and then disable and enable them all you want @snow apex
how
However you want
Make them public or write [SerializeField] if you want them private
Or you can get them by their tag or layer or name whatever
It's up to you
Example:
public GameObject yourObject; // set from inspector
void Start() {
yourObject.SetActive(false);
}
void Update() {
if (/*Under your desired condition*/) {
yourObject.SetActive(true);
}
}
youre doing what i suggested lol
ure activating and deactivating
Yeah but it works
You said it doesn't right?
You said you can't hold the reference
my only issue is then how do i get a reference to an inactive object
The reference is that yourObject
singleton always works for me... 🤷♂️
i havent found a cleaner way
yet
Ah hell naw I don't like singletons
youre defining it through the unity interface?
But yeah I guess you can do that
singletons are lovely
If you don't want to you don't have to
You can also find them by tag or whatever
Your choice my friend
no you cant lol
i might be mistaken but i dont remember you being able to use that on inactive objects
oh well then yeah
well how do i find them if they are disabled lol
whats wrong with using a singleton reference?
how do i fix my UI transform changing values when i parent it via code
GameObject _ItemUI = Instantiate(ItemUI);
_ItemUI.transform.parent = SelectedSlot.transform;
these are the normal values
Is it an issue?
The values are relative to its parent
You can modify recttransform.anchoredposition etc if you need to
not sure what u mean but this is what im trying to replicate
https://gyazo.com/5e62b1c3aaa4f5bf252d66d305707d13
i set up the prefab so it stretches to match the parent, but they just change values for some reason when i do it trough code
i have a button that references a function for its click functionality from an object called UIManager (First image). that object becomes scene persistant:
void Awake()
{
// Implement Singleton pattern
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this.gameObject); // Make Persistent <-----------------------------
}
else
{
Destroy(gameObject); // Destroy duplicate
}
}
the issue is that it leads to the Function to go missing for the button! (Second Image)
how do i solve this issue?
looks like you will need a script to set the OnClick event rather than using the inspector
how could i fix that when i shoot my projectile it automatically explodes in the air ?
see why it's exploding and stop doing it
@languid spire
it's case sensitive
so i need tp put all the horizontals with a capital?
If you look at where it tells you (Edit > Settings > Input), you'll see the list of axes set up for your project. When you refer to them from the code, they must be spelled exactly the same
Apply the same directions as for the previous issue.
is it a problem with capitals again?
Look.
Go look at the input settings and see for yourself
why would different rules apply for one and not the other?
im slow
how to look at input settings
thank you sorr im 13 and just started unity
being 13 does not excuse you from reading and thinking
I just don't understand half the stuff your saying 😭
then you ask for clarification, don't hide behind your age or lack of knowledge/experience
Mb bro
Trying to get object to another scene but i get this error?
MoveGameObject, not MoveGameObjects
so i have gameObjects that are supposed to be cities and those cities are in a list and that list is in a script for a gameObject which is basically the country and i want to know if theres a way to get the parent of the list or something so that on the city its written the country that owns it
idk how to say parent of list or somehting
Have the gameobject country call a script that gets the list and then set the country based on the gameobject that contains it, I guess
it works thanks i also did this for the flag
i declare a public int with -1 default value but on Awake check its value becomes 0.
after checking, i didnt find anything that changes its value. i tried adding another public int field that has -2 value and it fix the problem
so im supposed to just leave this useless 2nd field ?
did you look in the inspector, that value takes precedence
Yes, pretty much
If you want to optimize this, I suggest you get the component once and use the reference. Right now you call it twice
Maybe Cities can be a list of CityManager, even
uh, so even with 2nd field , in inspector first int value stays 0 so i did have something apparently, but check on awake and start differs. (0 without 2nd field)
show the inspector and your code
i dont know what to show. its 2 public int field declaration with debug on start and awake
ill restart
screenshot the inspector where the script is used
yes it shows the name of the field, with value beside it as i mentioned. sec let me restart
look, if you do not want to learn what is wrong by doing what you are asked, don't bother asking for help
this is without additional dummy field
//public int testIndex = -2;
public Vector3Int CurrentGridLocation { get { return GameManager.Instance.floorTilemap.WorldToCell(transform.position); } }
public Vector3Int GridPosition { get; protected set; }
protected virtual void Awake()
{
Debug.Log(dataListIndex);
FloorSaveAndLoad.Instance.OnListChanged += Instance_OnListChanged;
GridPosition = GameManager.Instance.floorTilemap.WorldToCell(transform.position);
}
protected virtual void Start()
{
Debug.Log(dataListIndex);
if (dataListIndex == -1)
{
FloorSaveAndLoad.Instance.SaveFloorItemData(this);
}
}``` the code
are you looking at its value outside of play mode? because the value you see in the inspector there will be the one assigned before Awake is run
so you see dataListIndex is 0 in the inspector. As I said, this value take precedence
this is with 2nd value uncommented, and the check goes thorugh
to SaveFloorItemData(this)
so what i have to solve is, what changes its value. you already helped me as i thought it would be -1 in inspectors 2nd case
do you not understand what the word precedence means?
take priority ?
yes, so what do you not understand here?
but my check on start goes through so that is what i need, even though it shows 0 on inspector
well show the console then to prove that, we cannot see your screen
i put the console in hierarchy in the photo, this is actually me trying to do saving with data binding, so its very possible i f.up some order cause so many things happen in multiple objects awake and start. its fine your very first reply already helped
you're right it does show -1 and -2 outside play mode.
screw this, i cant. a comment dont remove should suffice..
guys what is this?
Click in the error
Well, I clicked on the error but it doesn't show anything
Is it still there if you reboot the Unity Editor? Looks like the usual false positives
yes, it still shows me
https://discussions.unity.com/t/default-values-for-public-int-float-variables/904965 i finally understand what you two @languid spire @slender nymph means. outside of play mode, the value on inspector on prefab asset is the default value.
and adding default, pre-awake value through code do not change default value on already created prefab.
dammit, hours wasted for this knowledge
Im trying to make the player rotate towards the mouse but this keeps coming, how do I fix this?
Are you sure cam is a camera?
show the declaration for cam
do you have your own class called Camera ?
so yes you do
yes
there is the problem, do not re use Unity class names
huh oh, no, I didnt create my own class called "Camera"
according to that you did
What Unity Editor version are you using? Try the latest LTS or the one prior to the latest.
unity 6
im using that class to put in the Main camera from the project hierarchy
isnt it like public GameObject smtg
You gotta give it a different name, it’s taking a script called camera but it’s not the Unity camera
ohh, i get it now.
thanks ya
Or if you're wanting your class to be called Camera, you'll need to be explicit with the type (having the namespace and whatnot in addition)
i fixed the problem. I had script named "Camera"
so it was interfering with it
UnityEngine.Camera as the type would be the alternative
alright.
How to move the following gameObject in the direction of something? Like I have a vector2 direction, I want this object to move, but depending upon where the direction says it to move. Like left, right or up and down.
{
// Time taken to move one piece to the next position
float moveDuration = 1f;
float elapsedTime = 0f;
GameObject last = assemblyLine[assemblyLine.Count - 1];
Vector3 startPosition = last.transform.position;
Quaternion startRotation = last.transform.rotation;
Vector3 targetPosition = assemblyLine[0].transform.position;
Quaternion targetRotation = assemblyLine[0].transform.rotation;
assemblyLine.RemoveAt(assemblyLine.Count - 1);
assemblyLine.Insert(0, last);
while (elapsedTime < moveDuration)
{
elapsedTime += Time.deltaTime;
last.transform.position = Vector2.Lerp(startPosition, targetPosition, elapsedTime / moveDuration);
last.transform.rotation = Quaternion.Lerp(startRotation, targetRotation, elapsedTime / moveDuration);
yield return null;
}
}```
last.transform.rotation = Quaternion.Lerp(startRotation, targetRotation, elapsedTime / moveDuration);```
This is the line where im moving it, I want it to follow a direction as well
It's very unclear what you mean here. Change the target position to what you want. An object can only move in one direction at a time.
Example: If The target position lies on the left side of current position, I want it to move right till the end of the screen, and then come from Left Start of the screen to the target position
Make the target position on the right untill it reaches that point, then change it to be on the left
Got it
Yeah Agreed, I was experiencing bit of a brain fog that I made a simpler thing look complex. sorry
Why isnt my "Ball" turning green?
I have a problem, because I don't have a problem.
I made this script 3 years ago and I don't remember how it actually work.
I mean I understand the code inside but I don't know how it is even able to communicate with Unity if I press the "ESC" Button on my keyboard, how it this script even able to register it, if it doesn't even have a Update Function?
It does only have those public void xxx() stuff but the Keyboard ESC is a keyboard button that can not be called like if you press an UI Button or something, so how is this script even able to work because I tried to understand it now for 2 hours but I don't know how it is even able?
Because if I out comment everything in this script, opening the ESC Menu will stop working, so it must be this script.
https://paste.ofcode.org/GR3k837BeSBzrsqH7PixFS
I also have a script inside that does get called by an UI button but this is another story that I am able to understand, only the part, how it is able to get called of a ESC Keyboard Input does confuses me.
do you have a Component named Ball
cause according to your compiler you do not
probably better off asking in #🖱️┃input-system
I see i wrote ball insted of balls
balls
I dont know if its that Input System specific?
Its more like a beginner code confusion, or am I wrong?
I have to rework this entire script and I dont can rework it, if I dont know how it does comunicate to avoid missing some parts that I should delete, if I rework it.
whats wrong with it exactly ?
This code was one of my first scripts I wrote, 3 years ago.
Back then it seems I used a different method to get new input system inputs without the need of a Update event.
Today I use update because its easy to read and the performance factor doesn't seems to be influenced by it.
I want to rework it, but how can "public void Meine_ESC_Funktion()" even work, if its a Keyboard button that does access this event? I mean if it would be a UI button, you have Button "On Click ()" in the Inspector but this does not exist if you want to access something by a Keyboard key like [ESC].
But if I press ESC, this function does get called and I don't can remember how I have done it 3 years ago, how is this even possible?
how should we know by this image alone
honestly I only use the Send Messages feature for now on the new input system
so I can only comment on that
it requires no polling, all you do is call the event that matches the action name with the On prefix.
such as
OnMove(InputValue value)
//gets called when Move keys are pressed in Action Map
if this aint code related, you would post in #💻┃unity-talk
Thank u
How would you exactly code the Manhattan distance in unity? is it a formula I must know? right now I have a 2D grid and you can't use Euclidean distance but you would need to use Manhattan distance, using it for A*.
Manhattan distance is just abs(x1 - x2) + abs(y1 - y2)
thats it?
yup
what would you put x1, x2 as? is it a place on the grid
such as left, right, up, down?
Where can I find it?
is there a gameobject where you do this?
oh, well I do appreciate it man
On the player Input component
Vector2 moveInput;
private void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
}
I use it this way for now without the Events / generating c# class. Works fine for me
just one of many ways they allow you to use it. I Found it the most straightforward easy way with least friction
It was Invoke Unity Events
Yeah I haven't used that yet so I cannot comment on any of it lol
Heya. Trying to Write something on my UI. Is there a way to access the text fields without declaring each one of it as public variable in my script?
I just wonder why I made it like that instead of using
bool _RightButtonPressed = _controls.Player.Inventory_Hotbar_RightButtons.WasPressedThisFrame();
Inside of an Update?
Does it make a performance different?
If not, I would go with the Update event, if yes, I would go with the Unity Invokes.
because now you have to poll in Update , it builds up
if the system is there to use events/ messages its much better to do so
Update is not exactly a free operation
only caring/reacting when something happens is way more performant in the long run
Yes there are many ways, but the best way will always just be declare either a public field or a field with [SerializeField] attribute and drag in the reference you want.
I know there was a reason why I made it like that back then and now I know it again, thanks.
Yeah i know, but I fear that it adds up with all the fields i may use
Hello i have seen a tuto for an easy AI so it do Vector3 = target position - gameobject position but in the tuto the vector is normalized. What is the utility of normalized i dont understand ?
normalizing a vector will make the vector 1, and will still have the same direction
JESUS CHRIST WHAT DID UNITY DO THE MANUAL
most of the links are broken.....
!docs
But What is make the vector 1 ???
Ohhh its like make the speed constant ??
yes
Okkk ty
basically
Ty
And every other way would be worse. At least by drag and dropping you have a direct link to what you want. If you're creating stuff at runtime, which cant be dragged and dropped then it's a different story
public GameObject[] Waypoints;
public int index = 0;
private Vector3 Dir;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Dir = Waypoints[index].transform.position - gameObject.transform.position;
transform.Translate(Dir.normalized * speed * Time.deltaTime);
if(gameObject.transform.position == Waypoints[index].transform.position)
{
index++;
}
}```
why my gameObject dont change his target ?
my gameObject shake when he is at the waypoint
because you should not test for equality, check for a distance from
yeah comparing two floats is bad because they are never equal
Hey, so I changed some controls on my webGL build, it runs great in the player/build & run, but when I replace the files on the web app I have it on and build it to run in local for testing, nothing has changed. Any insight would help
ohhh ok
tried a clean before rebuild and it didn't seem to work
probably need to clear your browser cache
haha let's try it
yah that didn't do it
I'm presuming you did restart your web server to reload that cache
yes haha
when I build/run in unity, it works great in the local host that pops up, so it must be in my local repo for it
yep, your webserver is serving up old files
but I've entirely replaced the build/ template data folders and index.html file with the new ones as well as removed the .br so a new one is created on building it
in my unity folder that is
ran a clean before rebuilding the whole web app too tho
hello there is something like tag.length ??
What are you trying to do here
i am trying to get the number of gameObject with the tag "Ennemy"
but if there is nothing like that i will make a variable in my program for this
If you're not keeping track of the enemies yourself, then what you can use is FindGameObjectsWithTag("Enemy"), which returns an array of all objects with that tag. Then check the array's Length
Ask in #💻┃unity-talk
dont crosspost and this isnt code related
so i can do int EnnemyCount = FindGameObjectsWithTag("Enemy");
no
oh
That won't compile, you're missing the "get the length" part
definitely no
GameObject[] enemies = FindGameObjectsWithTag("Enemy");
int enemiesAmount = enemies.Length;
why my prefab dont save the gameObjects ?
most likely , because they are part of the scene
prefab cannot bring scene objects with it
oh
hold those waypoints in the enemy spawner of the scene, then when you spawn enemy you pass those to the enemy
how can i give waypoints reference in the correct order ?
wdym
how can i give to my array the reference of my waypoints ?
Instantiate returns you that object, from there you can modify any component including the Enemy script
eg
var enemyInstance = Instantiate(etc.. enemyInstance.GetComponent<Enemy>().Waypoints = Waypoints
even better spawn it as Enemy skip the get component, same idea though
idk your exact behavior use case, like you want specific paths / orders make each one a different order of the same points so you have an array of array of points
eg
[Serializeable]
public class WaypointsPaths{
public Transform[] Waypoints;
}```
```cs
[SerializeField] private WaypointsPaths[] waypointPaths;
enemy.waypoints = waypointPaths[index].Waypoints;
index++;``` @round mirage
more efficient way of doing this?
does unity have something to do a simmilar thing by default?
if you know lmk cause I do the same shit lol
alr lmao
you would think the LayerMask would have some method in it but no..we don't
"you guys dont have extension methods? ".
I think the main concern is that since Layermask can hold multiple layers and gameobject layer is only 1 int, it would be some weird issue if you select multiple layermasks
trying to load sprites via code. Resouces/Sprites/Plants my question is will it work like this
switch (Type)
{
case PlantType.Chamomile:
Debug.Log("Chamomile");
return "Sprites/Plants/Chamomile";
case PlantType.Echinacea:
return "Sprites/Plants/Echinacea";
case PlantType.Lavender:
return "Sprites/Plants/Lavender";
case PlantType.sage:
return "Sprites/Plants/sage";
case PlantType.thyme:
return "Sprites/Plants/thyme";
case PlantType.Yarrow:
return "Sprites/Plants/Yarrow";
default:
return "Sprites/Plants/Chamomile";
}
HarvestableSprite = Resources.Load<Sprite>(HarvestableSpritePath());
Do sprites have a Exenstion on their name? or is my format in my folder wrong?
thats what i was thinking
but even then it could display a warning or something
i have the wrong picture of the sprites but same thing, there next to the displayed pciture
have you read the Resources.Load docs?
public static class Extensions
{
public static int ToGameObjectLayer(this LayerMask layerMask)
{
return 1 << layerMask.value;
}
}```
```cs
LayerMask layermask;
void Test()
{
gameObject.layer = layermask.ToGameObjectLayer();
}```
btw slightly more efficient to do bitshift than Pow (no floating point operations / casting)
alr thanks
Does unity feature inbuilt CSG operations, or do I need to write them myself/use an external library?
can someone help me quickly? I want to be able to shoot an object in the direction of the player and i want it to continue forever at a constant speed. how do i do that?
(player.position - shootPoint.position).normalized would be the direction vector towards the player. Setting multiple of that as the velocity of the bullet should be enough. If you want the bullet to go forever, you should make sure there's no drag on the bullet Rigidbody and no gravity
someone know why my ennemies do this ??? (i got this after i have used transform.Lookat)
public GameObject[] Waypoints;
public int index = 0;
public float dist;
private Vector3 Dir;
private WaypointSaver waypointSaver;
// Start is called before the first frame update
void Start()
{
waypointSaver = GameObject.Find("WaypointSaver").GetComponent<WaypointSaver>();
Waypoints = waypointSaver.Waypoints;
gameObject.transform.position = Waypoints[0].transform.position;
}
// Update is called once per frame
void Update()
{
Dir = Waypoints[index].transform.position - gameObject.transform.position;
transform.Translate(Dir.normalized * speed * Time.deltaTime);
dist = Vector3.Distance(gameObject.transform.position, Waypoints[index].transform.position);
if(dist < 0.05f)
{
index++;
}
if(index == Waypoints.Length)
{
Destroy(gameObject);
}
transform.LookAt(Waypoints[index].transform);
}
}```
Hey guys, I have a problem in my flappy bird game (left). Right now I am trying to implement the player sprite rotating downward when falling and upwards when I jump as seen in the right gif. As you can see in my game, when jumping repeatedly the bird doesn't stay facing upwards, it does a piddle-paddle motion instead. Here is my code: https://hatebin.com/hegfjecnyl
In the other gif the bird rotates downwards when it's falling faster than a certain speed, not when it's not jumping. Also the code does slerps incorrectly
hmm, thats a good observation. how does the code do slerps incorreclty though
Slerp is (original rotation, target rotation, time elapsed / total rotation time). Yours is (current rotation, target rotation, speed * deltatime)
Quaternion.RotateTowards would be more appropriate
I am pretty sure this has been answered a thousand times, but the test ads work in the editor but when i build on my android device i don't see any ads. How can I fix this? I am using just simple UnityAds and no mediation. I have Android Ad ID and verified it is in test mode.
hey, i'm doing the beginner course with unity, and after closing and reopening the project i was hit with this error
`using System.Numerics;
using System.ComponentModel.Design.Serialization;
using System.ComponentModel.DataAnnotations.Schema;
using UnityEngine;
// Controls player movement and rotation.
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f; // Set player's movement speed.
public float rotationSpeed = 120.0f; // Set player's rotation speed.
public float jumpForce = 5.0f;
private Rigidbody rb; // Reference to player's Rigidbody.
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody>(); // Access player's Rigidbody.
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Jump")){
rb.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
}
}
// Handle physics-based movement and rotation.
private void FixedUpdate()
{
// Move player based on vertical input.
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = transform.forward * moveVertical * speed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + movement);
// Rotate player based on horizontal input.
float turn = Input.GetAxis("Horizontal") * rotationSpeed * Time.fixedDeltaTime;
Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
rb.MoveRotation(rb.rotation * turnRotation);
}
}
`
you need "using System" on top
you need to get your !IDE configured 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Systemac1 is missing a semicolon
fixed that, still doesnt work
same error?
same error
I think I did everything in the guide
that using System.ComponentModel.DataAnnotations.Schema; is your problem
do i just delete it?
if you do not see red underlines in your code then you probably missed a step
so now that using SystemAc1 is your problem. comment that out then see what issues you ahve
this was sample code provided by the tutorial, didnt write this
the tutorial 100% would not have included those using directives
yeah ive never seen SystemAc1 namespace before
wasnt there the first time, just when i repoened project
but you need to focus on getting your IDE configured before fixing your errors
`using System;
//using SystemAcl;
using System.Numerics;
using System.ComponentModel.Design.Serialization;
using System.ComponentModel;
using UnityEngine;
// Controls player movement and rotation.
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f; // Set player's movement speed.
public float rotationSpeed = 120.0f; // Set player's rotation speed.
public float jumpForce = 5.0f;
private Rigidbody rb; // Reference to player's Rigidbody.
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody>(); // Access player's Rigidbody.
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Jump")){
rb.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
}
}
// Handle physics-based movement and rotation.
private void FixedUpdate()
{
// Move player based on vertical input.
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = transform.forward * moveVertical * speed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + movement);
// Rotate player based on horizontal input.
float turn = Input.GetAxis("Horizontal") * rotationSpeed * Time.fixedDeltaTime;
Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
rb.MoveRotation(rb.rotation * turnRotation);
}
}
`
wrong reply but also !code 👇
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I've been staring at it for a bit but i dont think I missed anything, is it maxbe that i have 2 of these?
no. did you complete all of the steps though
i think only the dev kit one came with unity
that isn't helpful
i think i found one step i didnt do
where do i find packages?
exactly where the instructions tell you
tutoril says window, but cant wifind it there
nvm
im dumb
wasnt the problem, its updated
if you cannot get vs code configured following the easy instructions provided, then consider switching to visual studio
it also generally helps to read messages that your tools give you. like the one that you probably ignored in vs code that said to install the .net sdk
Is the ide configured? A configured ide would tell you all of the issues with some underlining and complaints.
Is unity discarding vscode as a viable coding editor in version 6?
Idk man, I did everything in the tutorial, looked all the messages, I'll reinstall vscode and try again i guess
why would you even assume that?
I just checked, they deprecated the package for vscode integration
yes, that package has been deprecated for 2 and a half years now. but if you'd look at the current configuration steps, you'd see that a different package is used now
Ok I have never noticed it until today, thanks
the package wasn't actually marked as deprecated in the unity editor until the earlier 2023 versions (which unity 6 is an update from). but it hasn't been maintained in more than 2 years and for a while support was being completely dropped for it, but microsoft is now supporting the unity extension
go in external tools in unity preferences , close vscode and try Regenerate project files button. Open script through unity again, look at output tab for any errors / messages
Ok, that's why I've never seen this message. And yeah it's still working amazingly so that's fine
they've already got this installed as it was installed automatically by the unity extension
Thanks for the suggestions, I ended up getting it working thanks to you by using rotatetowards() and a check for if the bird is dropping at a certain speed. https://hatebin.com/cstfceqhdq
what would have to happen for this to throw an index error?
you dont have enough elements
oh empty list?
yea
How does O in SOLID work with mod support in games? I'm not sure I'm understanding it right because the two ideas seem to clash
I know it's not directly scripting related but wasn't sure where else to ask
Mod support isn't really related to solid principles.
So what does "closed for modification" mean in "O"
It means that you design your code in such a way that you can build on it by extending existing classes, rather than modifying them.
I say classes, but it's not limited to them. It might mean using/implementing interfaces as well.
I don't understand - is extending classes not modifying them? Maybe if you have an example that could help me understand.
If you design a skills/abilities system, you implement it in such a way that you don't need to modify the existing code later on, when you want to implement new skills/abilities/features
Oh right I see what you mean
What about if you're reading the skill names from a text file for instance? You're technically not changing the code by changing the string in the file.
I'm asking since SOLID was mentioned to me in regards to reading from a text file that users can modify.
Trying to make a bounce like in mario, right now the player destroys the enemy but no bounce is added to the player, any ideas why?
are you overriding y velocity in your movement script ?
Oh! Yes I believe I am, I am using terodev's ultimate movement script
How can I make is still work?
you could probably add onto it, or just not override y in movement. I usually use AddForce for these
btw, if you're using unity 6 you can assign to just a single axis of the rigidbody2d's velocity now using the linearVelocityX and linearVelocityY properties
Okay, thank you guys I will try that then
is rigidbody2d.velocity deprecated and instead using linearvelocity?
indeed
is there any difference
no
interesting, why not just add on to velocity though 🤔
ah yeah, i guess that would be a good indicator that they aren't using unity 6 lol. and it's just a rename
Something like this?
what do you mean?
reset Y velocity first, then apply Impulse forcemode
Okay, how can I reset it?
instead of renaming it, why not just make it VelocityX and VelocityY instead of linearvelocity/X/Y
assign 0 to it lol
rb.velocity = new (rb.velocity.x, 0) // reset Y vel rb.AddForce(vector3.up * force, forcemode2d.impulse)
you still need to make sure the movement script isn't overriding the y by having only x being overridden
rb.velocity = new (xmovement, rb.velocity.y)
well that's what those properties were called before the velocity property was deprecated for the rename
I don't think that's related. That's handling data, not behavior/implementation.
I see, thank you for your explanation it was really helpful.
Howdy! I'm trying to make a game object toggle whether it exists in the game or not, I would like to use two public variables that can be assigned in unity: the game object being toggled, and a bool to determine if its toggled on or toggled off, i am seeing the target object variable in the inspector but its not showing the bool variable, would any of yall be willing to help?
it's not showing because you have compile errors so it hasn't been able to recompile to show the newer variable
writing python syntax lol wth is that?
i modified it and it seems to match, but it is still giving a compiler error, i am very new to c#, could you explain what my mistake is?
which error is it, did you save?
im sorry, it seems im a little too used to pycharm
didnt save
thank you
are you following some type of course ? check pins in this channel for some to help you get started
ill check for the pins thanks, no im not following a course, trying to develop some 3d buttons for a simulator research project
also is your !ide configured? I'm getting mixed signals.
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
ide def needs configuring
its got some issue with .NET Core SDK not being found, which im assuming is the issue with the IDE, i dont have perms to do things so im waiting until the week to ask IT to install it
oh yeah .net sdk 8 is dependency needed for plugin to work correct
why not install it?
^ what those guys said, also .activeSelf I believe returns whether the object is active or not, meaning in your case you're setting it to visible if its visible, and invisible if its invisible
what you want is just basic true or false
ah ok, i got that line from a stack exchange i found online
yeah the proper syntax here would be targetObject.SetActive(true) or false depending on which one youre doing
I would definitely look into the !docs
but definitely should look at docs, tutorials and 100% set up IDE
its like working with notepad without a configured IDE, actually I think its the equivalent to notepad
doing that tomorrow, again, need to wait for IT
exactly, its already hard enough to tell where you screw up even with IDE configured, i cant imagine doing it with it not
btw you can just do
targetObject.SetActive(Visible)
thank you all
Inside the OnCollisionExit2d method, how can I write a if statement that uses information from the incoming collider (Like the incoming game object its apart of or the incoming rigid body involved)?
this is my code:
the if statement under OnCollisionExit2D isnt read so the Debug message does not go through.There are no red errors in my code.
why wont the if message be read?
pretty much how you did it, this message is sent when collider leaves the collisionsdo you have at least 1 rigidbodyFirst Check is not printing ?
oh nvm i see the code above is using it so I assume you are
It might just be a error to do with my game
Wanna double check, if I have quaternions rotations on the x y and z axis i.e angleaxis(30, Vector.right) and I want to apply them in the order XYZ am I doing q=xyz or q =zyx
might be a dumb question, how can i make the script output a variable (specifically an integer) to be referenced by other scripts in the unity project
Choose the best way to refer to other variables.
thank you
hey sorry for rookie question, but why do my character controller references keep getting this error? i've looked at tutorials and documentation but i still can't figure it out
CharacterController is a class, you need a reference. Please consider starting with tutorials on Unity !learn.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks man 🙏
again sorry for the stupid question lol
There's no stupid question
Hi, I'm currently working on a game for my graduation project and I bought some some assets from itch.io and the character has ToWalk, Walking, OutWalk animation
how can I make the ToWalk and OutWalk happens only once (when the character accelerate and decelerate) and Walking animation in a loop?
I'm working on unity
If you haven't already you need to make an Animator controller, also #🏃┃animation
I did
and about the collider, i'm facing a problem where my character when sliding on a wall, her body enters the wall, should I make a different collider for each animation?
this is a code channel, please move to #🏃┃animation as I indicated above
Ok, thank you <3
if ((Input.GetMouseButtonDown(1)) && cooldownAttack <= 0.0f && _grounded && (_characterController.enabled == true))
{
new Vector3 movement = Player.GetComponent<PlayerCode>().movementDirection;
var slash = Instantiate(slashPrefab, bulletSpawnPoint.position + new Vector3(movement.x, 0f, movement.z),Quaternion.Euler(-90f, 0f, bulletSpawnPoint.transform.eulerAngles.y));
cooldownAttack = cooldownNormal;
Destroy(slash,0.5f);
}else if ((Input.GetMouseButtonDown(0)) && cooldownAttack <= 0.0f && _grounded && (_characterController.enabled == true))
{
new Vector3 movement = Player.GetComponent<PlayerCode>().movementDirection;
var stab = Instantiate(stabPrefab,(bulletSpawnPoint.position + transform.forward * 2) + new Vector3(movement.x, 0f, movement.z), bulletSpawnPoint.rotation);
cooldownAttack = cooldownNormal;
Destroy(stab,0.5f);
}```
I'm trying to make an attack spawn in front of the player even when the player moves
why does multiplying velocity by Time.DeltaTime make the object move slower?
Only thing I can think of is if physics functions and stuff is already at a fixed rate
It is
Parent it to the player.
is the key difference between inheritance and polymorphism that poly is method overriding rather than inheriting?
im still struggling to remember the distinction
Inheritance has shared declaration with separated implementations for a method, in polymorphism both declarations and implementations are separated
using Unity's input system (Unity 6) I have this snippet that controls the camera:
private void Update()
{
UpdateFollowPos();
Vector2 currentInput = sensitivity * look.action.ReadValue<Vector2>();
AdjustRotation(currentInput);
OrbitAdjustPosition(allowOcclusion);
}
The sensitivity is just a float, and no framerate-dependent thing is being done to values.
Now the strange thing is that the sensitivity does seem to ignore framerate for mouse-delta values, but not for my controller. If my framerate is too low, my controller becomes very sluggish. Any ideas for how to fix this so that controller becomes framerate-independent, without changing any mouse-movement?
simply multiplying by Time.deltaTime would not be a solution, as it's (to my knowledge) already being done behind the scenes with the new input system.
you need to multiply by deltaTime when using a controller but not when using a mouse. so you need to check the current input device
If you are using joystick position for controller it will not be able to account for the frame time. Mouse delta changes every frame and depends on frame time by definition (it's delta between positions in 2 frames) but joystick position depends only on joystick itself
aha, I see. So values from the mouse are accounted for, while the controller just outputs analog 1 to 0. That makes a lot of sense for the behaviour I'm seeing. Thanks y'all.
!logs
WallJump is not working on x-axis for some reason
private void WallJump()
{
Debug.Log("WallJumpForce.x: " + wallJumpForce.x);
Debug.Log("FacingDirection: " + facingDirection);
canDoubleJump = true;
rb.velocity = new Vector2(wallJumpForce.x * -facingDirection, wallJumpForce.y);
Flip();
StopAllCoroutines();
StartCoroutine(WallJumpCoroutine());
}
it's working alright on y-axis
do me a favr add two new print statements displaying the value of facing direction and wall jump force after the line where you pared in the new vector2 values into the rigidbody velocity
basically
print($"WallJumpForce.x is now {wallJumpForce.x} and facingDirection is now {facingDirection}");
then send a picture of your console log
usually when people have actually debug logged the values like you have and it seems to be correct, they are accidentally overriding the velocity in their normal movement code immediately afterwards
I figured it out
apperantly
I should add return when the player is walljumping
private void HandleMovement()
{
if (isWallJumping)
return; // Exit early if wall jumping
if(moveSpeed < maxSpeed)
{
moveSpeed += accelerationSpeed * Time.deltaTime;
}
if(xInput == 0)
{
moveSpeed = 0;
}
if(dashTime > 0)
{
rb.velocity = new Vector2(xInput * dashSpeed, 0);
}else
{
rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);
}
if(isWallDetected)
return;
if(isWallJumping)
return;
}
yes, because if you dont you override the velocity.
Also, next time when you add debug.logs show the console
Ok, Thank you <3
btw, read your own code. It's pointless to have the wall jumping return twice in the same method
yeah move both return statements to the top and remove one of the wallJumping conditions
77 if ((Input.GetKeyDown(KeyCode.Q)) && energy => 60 && _grounded && (_characterController.enabled == true))
{
StartCoroutine(Summon());
}```
For some reason it's asking for a } at line 77
Your if statement has unmatched parentheses
Look closely and count the open and close parentheses
what is the point of telling us this if we do not know what line 77 is?
tbh, looking at your usage of brackets I wonder if you know what the reason for them is
you need to configure your !IDE 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Alr
is there a way to do a better walljump that can let the player keep the momentum, mine stops and resetes the character's velocity to 0
private void WallJump()
{
canDoubleJump = true;
rb.velocity = new Vector2(wallJumpForce.x * -facingDirection, wallJumpForce.y);
Flip();
StopAllCoroutines();
StartCoroutine(WallJumpCoroutine());
}
private IEnumerator WallJumpCoroutine()
{
isWallJumping = true;
yield return new WaitForSeconds(wallJumpDuration);
isWallJumping = false;
}
Looks fine, you've inverse the x directional velocity. Were you referring to the final stall in the video?
Velocity shouldn't go to zero unless you've got friction or some force being applied to your character.
If anything, I'm assuming you're setting the x directional velocity relative input somewhere and it's interrupting your x directional physics in the air.
private void HandleMovement()
{
if (isWallJumping)
return; // Exit early if wall jumping
if(moveSpeed < maxSpeed)
{
moveSpeed += accelerationSpeed * Time.deltaTime;
}
if(xInput == 0)
{
moveSpeed = 0;
}
if(dashTime > 0)
{
rb.velocity = new Vector2(xInput * dashSpeed, 0);
}else
{
rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);
}
if(isWallDetected)
return;
if(isWallJumping)
return;
}
maybe it's from the handle movement function
but when I remove the return code he doesn't apply the force on x-axis
A solution would be to change how input affects your character while jumping/in-the-air. Where you'd add to velocity rather than set velocity while in the air.
like this
if (in the air)
velocity += direction * scalar * speed
else
velocity = direction * speed```
You may want to clamp the value after adding to velocity if it isn't meant to be too large. The above snippet is simply pseudo code and instead your code should be addressing the x component of velocity.
Hi peps, using the Sync namespaces refactor in Visual Studio. Doesn't seem to be working, it just says there's nothing to sync.
Honestly, moved a bit of files, and it not working properly made things annoying.
Hello guys I need help
So I am learing to make a 2D platformer and I have successfully created a character move and jump
and I also have a moving platform. So I want the player to jump on platform and move along with the platform.
I tried watching youtube videos but when I tested it the player get stuck on the platform and run slow on the moving platform.
The player uses linearVelocity to move whereas the platform uses Tranform component for moving (maybe that's the problem)
If anyone can help me then do help plz
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
there's lot of solutions here. the most obvious one would be parenting the player to the platform in OnCollisionEnter and then deparent them in OnCollisionExit
Yeah I tried that but as I said the character moves slower than before on the moving platform
that's strange, I wonder why that would be. i did something with moving platforms a few years ago and i used that solution and it worked fine
for the platform movement i used transform.position and for the character movement i used rigidbodies
What if I use transform component for player movement?
and if I use that, then how can I simulate gravity?
did you try moving the platform using velocity?
this was with moving the platform with transform.position and the player with transform.velocity
mb for the audio in the bg, i'm in class atm 😭
oh wow my full ass name is on the screen
lemme crop that out
nah, don't do that. manipulating the transform does not use the physics engine. everything else will have to move using the same method. you'd have to simulate gravity for every moving object in the game . . .
no
but if I use too much physics then it might affect the performance, right?
yes, but using too much of your own system would affect your performance more. the systems that unity uses for physics have been developed over decades, they're pretty good at what they do
if you don't NEED to create a new system, don't
using too much of anything can affect your performance
moving platforms will do no harm. only worry about performance when it actually affects the quality of your game . . .
one of my recent projects was running like ass because of too many print statements 😭
ok I will try that
yes, displaying logs will slow down (affect) the game because you're creating garbage to print those messages . . .
this was using transform.position for platforms, and rb.velocity for the player movement
just parenting the player to the platforms
does unity do that? like if an object is on top of a moving platform, changing the moving platform's velocity will accelerate the object on top of it due to friction?
not if you are moving the platform with the transform. perhaps that is your problem, use physics for everything or for nothing
it's not my problem, but yeah that's what i meant by changing the platform's velocity
using rb.velocity
as I understand it he's moving the player with rb and the platform with transform, that is not going to fly
yeah, but the player is parented to the platforms
to the platform that the player is standing on*
that's what i did here
and it worked
exactly, 2 incompatible moving systems
There is a way to draw the line in the Game view instead of the Scene view only ?
Debug.DrawRay(ray.origin, ray.direction * 5f, Color.red, 5f);
how so? the player's velocity allows them to move relative to the platform, and the platform's movement (which the player's movement follows since it's parented) allows the whole system to move relative to the world position
turn on gizmos
in game view
it's disabled by default
it's a button in the top right of the game window
because when you move the platform which moves the player child you are effectively trying to override the rb on the player, that won't work
Ohh thanks ! I didn't know i will need to enable this to view the line
Note that it won't actually be in the game, it's still editor-only
how so? let's say the platform moves one unit to the right per second, and the player's velocity is (3, 0, 0)
player velocity moves the player by 3 * fixedDeltaTime, the platform moves the whole system (including the player) right by 1 * deltaTime
in total, the player moves 3 * fdt + 1 * dt
which is the expected outcome
which is why this is working
even though one is using transform.position and the other is using rb.velocity
The physics system has very strong opinions about where the Rigidbody should be and if it's not actually there all of its math gets wonky. You could call Physics.SyncTransforms() at the end of every frame in which a platform moves the player, but that's a moderately expensive operation and might affect performance. Still, if you want to do it, you should profile it and see how much it affects things before deciding on it
the platform moving is just like applying an additional velocity, they're not overwriting each other, they're adding to each other
maybe i just haven't experienced this yet, but for all of my applications, parenting a rigidbody to a moving body that uses transform.translate to move has worked fine
no, because the unity physics system ONLY knows about physics movement
sure, the physics system doesn't understand that it's moving the extra amount, but it's still moving, no?
the physics system will move the player by however much their velocity is
then the transform.translate will move it however much it needs to move to keep up with the platform
not the way it works, the rb will get upset if it's not where it thinks it should be
It is, admittedly an edge case, but it depends on a lot of factors like the actual velocities, the framerate, what you're trying to do with the physics system, but it can lead to things like eaten inputs or incorrect jump angles and other quirks like that. In casual play, it might not be noticed, but if it does cause problems it'll be very annoying to diagnose (and speedrunners of the future will curse you forever)
if what you said was true, there would not be a problem mixing transform and rigidbody movement on one gameobject, I'm sure you've tried it and found out it does not work
Theres are lots of easy ways to produce weird results with this setup. In your video it looks like almost only moving platforms so yea its not like much could even go wrong.
Since you're directly moving the transform, your object does not respect physics during this move. If you ever have a section where an object is in the way of the player, the platform will move them into it or through it if its small.
Does anyone know why I can't seem to set my tiles on my tilemap to different colors?
tilemap.SetColor(position, new Color(0f, 0f, 0f, 1f));
is not working for me
I am using the default sprite shader, the material is the Sprite lit default
iirc usually because tiles are locked
What does that mean specifically?
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.SetTileFlags.html
https://docs.unity3d.com/ScriptReference/Tilemaps.TileFlags.html
You need to unlock the tile before you can modify it
I don't see anything on those pages on what lock actually means or how to unlock...
I mean you could easily google what you don't know.. its pretty logicial.. if its locked its not modify-able.. if its unlocked it can be freely modified..
literally the second link explains what each Flags is
its not logical, for example when I click on the scriptable tiles link on that page it goes to "That page is missing" https://docs.unity3d.com/Manual/Tilemap-ScriptableTiles-TileBase.html
Hi, I have the problem that, while importing a .png as a sprite (2d and UI) my icon gets scaled in a way it looks really bad while even windows explorer (Icon above) displays the image correct. How can i fix that?
well idk they been having issues with links the past few days I think they are doing a merge.
this is a code channel
#📲┃ui-ux / #💻┃unity-talk
also the Windows photo viewer adds lot of extra filtering so its probably that making it look "smooth"
Ok from looking at the 2023 documention it looks like I need to create a scriptable tile not just a regular tile, would you say this is correct?
thats if you want tiles with custom properties / extra functionalities. If you are just changing color you have to do as I mentioned, set the lockmode to none and change the color.
I sent the function
scroll up
just to be clear..
tilemap.SetTileFlags(cellPos, TileFlags.None);
tilemap.SetColor(cellPos, myCol);
Yea I deleted that last message cause I realized how stupid it was, thanks for giving the code
i get your point, but for my intents and purposes it worked fine, i guess it depends on what you're going for
i'm sure rb.move could be used with to produce a similar result that actually obeys physics
Still can't believe the tiles start off as locked and it doesn't really tell you in any of the documentation and my googling wasn't helping either. Now everything is working such a big difference wow. Thanks again @rich adder
np.
yeah the documentation doesn't talk about much about this system as it should, think of the tilemap as being one big gameobject and the tiles are like part of the same bigger objects so they are default locked
how do u get the size of a probuilder object. i cant reference "probuilderMeshFilter" or anything
does it have a Regular renderer/
"mesh renderer"
can get bounds.size from taht
Hi all, I'm looking for a bit of advice please. (Sorry if this ends up being long)
The game is based in an asteroid belt around a planet. I have the spawning system all working the way I need it to (spawn in 'chunk' objects, create lists of Asteroid positions/rotations/scales, the chunks then grab asteroids from an object pool and apply the data from these lists when they're activated (Distance to player). It all works fantastically, I have an absolutely massive Asteroid Belt and performance is excellent.
Here is the script that creates the lists and deals with the grabbing asteroids from the pool etc. when the chunk is activated (This script lives on the Chunks).
https://hastebin.com/share/ahodunaxoc.csharp
My question is, I need to add more data into the Asteroids (They each have an Asteroid Controller script on them along with a scriptable object (Randomly selected at runtime to deal with what type of 'ore' the asteroid holds), for things like Amount of ore, Asteroid health etc. for the mining system.
Would the best way to deal with adding this extra data be creating an Asteroid Class and instead of creating the 3 seperate lists mentioned above, have all of that in the class, and then in the 'Generate Chunks' method create a list of Asteroid Classes?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
why not have a list of scriptable objects.. then just assign one to each asteroid as u create them.
asteroid.data.oreType
asteroid.data.health
asteroid.data.resourceAmount
same variable to call on all asteroids, each having different scriptable objects/ therefor different data
Mainly Because the asteroids are dynamically created, they'll never be same on each run. And if I understand correctly, I would need to create a scriptable object for every single possible permutation of said variables?
Can anyone explain to me why i cant create a script in the hierarchy anymore? did they remove that in unity 6 or am i going mental? Ive made sure visual studio 22 is set to my external scripting program
u can have an Enum for each type of ore..
u would just pick a random one
min and max values for the rest?
I think it's been renamed to MonoBehaviour instead of C# Script
Since you haven't been able to create a behaviour with any other language for like a decade now
it is Mono now 👍
you cant create scripts in the hierarchy anyway, only in the project window
woha
but when i did that it included all sorts of shit i dont need, like using system.host something
"googling ide"
the thing you code in
ur coding program
u can also set up templates to use.. so when u create a script its only what uw ant
aha, gah i shouldent have updated to VS22 :p
VS2019 superior
ok so nowdays u screate a script in ur asset, and then drag it to your hierarchy?
That's how it's always been done
It's just called something different in the menu now
aight thanks, why this thing even became a problem for me is because the code Application.Quit() isent reicognized, thought it had something to do with the other thing
I already have Scriptable objects controlling the types of ore (name/ore colour etc. etc.) It's more the 'dynamicness' of the asteroids (because they get put back into a Pool any data grabbed from a Scriptable object (ie, amount of Ore based on the size of the asteroid which is dynamically set wouldn't be stored. Not sure if I'm making any sense tbh. lol.)
you never drag a script into the hierarchy, you can drag it onto an existing gameobject though.
Application.Quit is ignored in the editor (per the documentation)
Application.Quit doesn't do anything in the editor. It closes a standalone built process
ye im trying to code a game menu :p
and Application.Quit() remained black and isent popping up in the popup thingie where it suggests stuff
you were not able to create a script in the hierarchy anyway like ever iirc, only in the project window/asset window, you could create on in the inspector if that's what you mean
Yeah, Scripts are Components, and components have to live on something (GameObject)
ah ye ofc, i dident mean i was trying to create one in the hierarchy, i meant rightclckjing a gameobject in the hierarchy
I don't think you can do that, unless that's possible. you would make it via inspector and project window/asset window
components are scripts but not all scripts are components 😛
like for my game menu i created an empty parent and placed my buttons and stuff in there, and now i wanted to rightclick the empty parent and create a script, coulda sworn ive done that before :p
LOL. Actually, yeah fair point, honestly didn't think about that.
||And also not all components are scripts either but that's a smidge too pedantic for beginner code||
You could get even more pedantic and say in a technical sense, all components are scripts. 😛 (Yes being obtuse and just trying to be funny lol.)
anyway, really appreciate ur help, any idea on why Application.Quit() isent "found" in visual studio? neither is
SceneManager.Loadscene
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
also not found and remain black
Maybe a silly question, but have you set up the event handler on your button correctly and got it pointing to your public void that contains the Application.Quit() ?
IT WORKS
soooo many templates
im not sure what i did but now it works :p
oh is that a list of different templates on what you need to script? sounds nifty
i always assumed unity realized that depending on what gameobject u rightclicked and added script too
when u create a new one.. could make it this for example
I've a problem, When the player jumps and move he gets way too fast is there a way to fix ?
show code
(i tried adding a physics material and settings the friction to 0 but thats way too slippery)
Alright
Hey does someone know why Visual Studio is not autocompleting the codes Im wrting in C#?
u need to cap the velocity somehow..
{
leftLegRB.AddForce(Vector2.right * (speed * 1000) * Time.deltaTime);
yield return new WaitForSeconds(seconds);
rightLegRB.AddForce(Vector2.right * (speed * 1000) * Time.deltaTime);
}
IEnumerator MoveLeft(float seconds)
{
rightLegRB.AddForce(Vector2.left * (speed * 1000) * Time.deltaTime);
yield return new WaitForSeconds(seconds);
leftLegRB.AddForce(Vector2.left * (speed * 1000) * Time.deltaTime);
}```
!ide 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
thx
if (isOnGround && Input.GetKeyDown(KeyCode.Space))
{
pr.Play();
rb.AddForce(Vector2.up * jumpForce);
}```
incredible. every single AddForce call you have is wrong
lol
ouch addforce!
Well, to be honest I saw it on a youtube video
But how can I fix ?
hahaha, my life :p
must have been someone who didn't know wtf they were talking about because you don't multiply your forces by deltaTime. and for one-off forces like jumps/impulses you use ForceMode2D.Impulse
you need to either control the velocity directly.. or cap ur velocity.. (maybe check if it hasnt reached a threshold before u apply more forces)
but yes, clamp the magnitude of your velocity after adding force to ensure it does not go above your desired speed
Alright so I just have to remove the deltaTime?
well that's not all. you need to remove the * 1000 as well since that was literally just compensation for the deltaTime multiplication
then you'll of course need to adjust the values of the variables you use so that they work correctly
Alright thx
is this looking good @rocky canyon
not sure what ur asking.. but in the newer versions of unity yes, Visual Studio Editor is the correct plugin
Library\PackageCache\com.unity.ide.visualstudio@2.0.18\Editor\VisualStudioIntegration.cs(28,18): error CS0246: The type or namespace name ‘Messager’ could not be found (are you missing a using directive or an assembly reference?)
I have tried everything, from reinstalling visual studio, unity, even looked on page 2 of google yet nothing worked. I have tried importing an older version of the package from a different project, yet it still cannot find the required file. This bug leads to visual studio 2022 being unusable because it is like notepad
Code Editor is not being supported anymore
i don't know why you're pinging spawn, when i was the one who called the bot for you. but that is just one step of several, complete all of them
update your packages
i have, it still didnt fix it
the newest 2.0.22 version
ive tried like 10 different versions
from different projects
I just saw it wrong, I was about to tag u
then close unity, delete the PackageCache folder from inside the Library folder in your project and launch it again because it clearly shows the error is coming from 2.0.18 not 2.0.22 which is the actual latest
i have tried that with the latest 2.0.22 version as well
but ive tried it iwth this 2.0.18
same error
you need to be actually on the latest version
i guess one more try wont hurt
it's not the raycast that is short, but your drawray. you only draw one unit of the ray rather than the whole thing. look at the docs for the method again
Why does Unity hub say "Install editor" what
Im in the editor
obviously you can skip the "install the editor" and "install visual studio" parts since they are already installed.
yes, you will see the "Install Editor" button on the Installs section of the unity hub because that is where you manage your editor installations
can you create directories in StreamingAssets at runtime?
so what do I need to do now I did all the steps
Well the problem isn't solved yet.. isn't there a way to clamp the values ?
that wouldn't break anything would it
regenerate project files and restart your code editor
on a standalone build, yes
what do you mean by that?
an exe application
but I didnt change anything though I already did these steps before asking you
not a mobile/webgl build