#💻┃code-beginner
1 messages · Page 639 of 1
this is something like praetor was mentioning
excuse my crappy drawing.. but u can just use the positions and subtract to get the direction.. and then just flip it
Would it be better to turn the whole gameobject, or have the wheel be a child of a wheelAnchor game object that doesn't turn?
Also, how could I allow the player to click any point along the wheel, instead of having the "handle" or "top" teleport around to under the mouse? My initial attempt at solving the problem did that, where I used some variation of lookAt
Are there any improvement's that I could do in my script? just want some else's feedback.
https://paste.ofcode.org/365LXWDxXa8gDffPf9Pd64k
huh, interesting
but yea praetors idea is better i think as the math is simple
whats the context?
when u collider u know the obj.. soo u can just sub its pos
so i just have to get the position of the bullet or the player, minus the pos of the enemy, and then put it negative?
when the player first clicks you basically set the current rotation as the point from which you are measuring. I don't have time to put an example together right now
nooo.. u have to subtract here from there.. or there from here..
...how?
here from there will get a direction opposite
transform.position - thattransfrom.position?
ah yeah, thats what i said, i just forgot to write it
so is
get player or proyectile pos
minus enemy pos
negative
I'm making a first person game, that script is my fps controller, just want some feedback e.g. - if I'm doing things correctly, what I should change, you should do this instead of that etc.
character controllers are known the best by their owners tbh.. u have more experience in it than anyone else..
but my question now is, how i can get the player and the proyectile pos from the enemy?
why would u need the player?
I think I understand
I could set the current rotation of the game object to be under the grab point, and handle the rotation of the sprite and the actual "output" direction seperately?
my bad
the machete and the proyectile pos
like
how i can make it get the Position of the Specific proyectile (prefab) that hit it?
i know how to reference the enemy from the bullets, but not the bullets from the enemy
HOLUP
u mean, also make the position of the proyectile a value, wich i also sent to the enemy
like the damage value, but is the position of the proyectile
if u have a reference to a script u can just use it like enemy.gameObject.transform.position
sure, or have it pass in the direction already
this is wat basic subtraction looks like.. its not perfect (depending on the collider shape) but its pretty close..
huh, makes sense
well thanks :3
i will test if it works
all components have transform as a property so you dont have to go to gameObject firstly
how do I make difrent idols based on where my character is facing
blend tree
idols?
i presume they mean "idle"
different idols animations
ah, idle yeah
idles
idol is like a statue you worship
blend tree is the way to go
indeed, blend trees. #🏃┃animation question
yeah
why is it not recognizing serializedfield???
becasue that's not how it's spelled
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
still not working
show that its configured then
one question I dont think this is the reason but where are unity prefrences
if you dont see this down here, your vsc is not configured
something you could've easily googled yourself
its also part of the steps in VSC
which makes me suspicious when you claimed
"still not working" did you even click the setup steps at all..
why isnt this working
because you aren't following the steps
its not showing visual studio
then you did not configure it
for external tools do I need to browse it?
I did everything its till not working
hey can some one help me
👇
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
i am making a game for my uni project but my 3D models start to rotate on collision
while x and z rotation are blocked in rigitbody
cant find any thing
still confused
show
this is a code channel btw
well which axis are they rotating on?
I meant show the components like the rigidbody constraints / eg the problem
the model is rotating in y axis
well you haven't constrained the y axis
so of course it can rotate on the y axis
but it will not jump then
huh
rotation and position constraints are separate
why would you rotate with jump?
freeze y rotation to make it not rotate on the y axis
this won't affect position
@rich adder do you free?
hello yall, got a problem with event systems here. line 92 here is supposed to stop the method when i click on ui, but when i select an UI input field in my game with a clickable game object behind it, the logic executes and doesnt stop the method. whats the solution to this?
https://paste.mod.gg/wlautbrzgdbg/0
A tool for sharing your source code with the world!
what?
also don't randomly tag someone into your questions #📖┃code-of-conduct
in what sense, what about them?
i just had a problem about chracter moving
these my first time on unity and my teachers just joined me to the gamejam
i must do that
put a breakpoint, are you certain that if statement is hit ?
you have to ask a specific question + show the setup like code. otherwise no one can help anything
if u can come private chat i can show with share screen
no, you can use screenshots here just fine.
because private chat requires more commitment to a problem than I feel like devoting to lol
You can post here, others can chime in and help
nope thanks for help
goodluck then
Post screenshots of your editor if we need to see Inspector values and post any related !code using links from the bot . . .
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Hello i have imported a bundle of assets i have already done the “Render Pipeline converter” except that the water uses a shader and not the URP. how can i use the shader that the person has used because for now my water is pink. ? thanks
this is a code channel .
Custom shaders cannot be converted automatically
You need to find out whats the equivalent functions from BiRP shader and convert it yourself or find another one compatible with the render pipeline you are using
Sorry
how do I make the wand spright flip ?(why is my code not working)
ising UnityEngine;
public class WandController : MonoBehaviour
{
public Transform player; // Reference to player
public float distanceFromPlayer = 1.5f; // How far the wand stays from the player
private float horizontal;
void Update()
{
FollowMouse();
horizontal = Input.GetAxisRaw("Horizontal");
}
private bool isFacingRight = true;
void FollowMouse()
{
if (player == null) return; // Prevent errors if the player is missing
// Get mouse position in world space
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosition.z = 0f; // Ensure it's in 2D space
// Find position between player and mouse
Vector3 direction = (mousePosition - player.position).normalized;
Vector3 wandPosition = player.position + direction * distanceFromPlayer;
// Move wand to the calculated position
transform.position = wandPosition;
// Rotate the wand to face the mouse
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle);
}
private void Flip()
{
if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
{
isFacingRight = !isFacingRight;
Vector3 localScale = transform.localScale;
localScale.x *= -1f;
transform.localScale = localScale;
}
}
}
use links for code 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
oh ok will do next time
or how about make it properly legible so you can get help better?
and so what is the question
the wand sprite isnt flipping
where do you call Flip
(they don't)
i dont know what i did wrong...but the shards aren't shoot, they just fall off
Enemy:
if (health <= 0)
{
GameObject RifleRotoFragments = Instantiate(RifleRoto, proyectilposition.position, Quaternion.identity);
Vector3 direccionFragmentos = (transform.position - attackposition.position).normalized;
Rigidbody2D rb = RifleRotoFragments.GetComponent<Rigidbody2D>();
if (rb != null)
{
rb.linearVelocity = direccionFragments * 10;
}```
proyectile:
```cs
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.transform.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(riflebulletdamage, 1, transform);
Destroy(gameObject);
}
}```
how did you verify each function is called
player's melee:
private void MeleeAttack()
{
// Cast a ray to detect if an enemy is in range
Vector2 MacheteRange = new Vector2(attackRange, attackRange);
Collider2D hitEnemy = Physics2D.OverlapBox(machetepos.transform.position, MacheteRange, 0f, demons);
Collider2D hitProyectile = Physics2D.OverlapBox(machetepos.transform.position, MacheteRange, 0f, proyectile);
// If an enemy is detected, deal damage
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(meleeDamage, 0, machetepos.transform);
}
}```
what you mean?
Start using Debug.Log to debug your code. You come here with lots of questions that can be fixed through simple debugging
oh
Part of fixing a problem is to narrow down to where the issue is.. You can't do that if you don't verify your code is doing what you expect it to do. Logging the values, breakpoints etc. these are tools developer use to narrow down those unexpected values
this looks "AI" generated sadly
If you wrote it you would have had some idea when you would call it
but i mean, in theory it should work, cuz literally in the same part where it damages and the corpse falls, its the same that should make it yeet
the only place i have to look is if it has a rigidbody...wich i added, but i will check anyways
you're not in the theory business, you're in the exact science business. You need to test and verify those assumptions
I know when but kinda hard to make it into be well ferwell I am gona try finding a solution
holup, i think i found the issue, but not the awnser
it cheks if the object has a rigidbody, wich it doesnt, why?, cuz is a collection
finding the issue is part of fixing the problem
are all the shards of the enemy put inside a gameobject, all of the objects have a rigidbody but the collection
but my question is...How do i make the enemy interact with the children's rigidbodies instead of the gameobject rigidbody
Get / Interact with Component in Child Unity
ok
anyone wanna try out my game its only 7mb i need feedback
read the pinned post as well how to post
do u think i should use itch.io or unity play which ones better
both work fine, as long as they are those legitamate ones with some media, you should b ok
ill probably use itch.io then, and to be sure nobody can somehow like acces my files and "steal" my game and claim its theirs right
webgl sure, anything that is an exe can be decompiled and reused ( this is pretty advanced to do, not likely they are interesting in your game though not for nothin..)
guys why is my dash going down instead of left and right?
private void dash()
{
horizontal = Input.GetAxisRaw("Horizontal");
Vector2 movement = new Vector3(horizontal, 0f) * 100f;
rb.linearVelocit
}
In udpate its constantly checking for button pressed
and acording to it calling the function
nvm I am stupid
without adding layers of obfuscation to your project, anyone who is dedicated enough, will be able to decompile the project. be mindful of that for sure, but its not something id personally worry about
the odds of somebody wanting to go through that effort, unless youve got something incredibly unique and one of a kind, is quite low
besides, if you proved in court that somebody profited off stolen code, there will only be one thing on my mind
🤑
Nitpicking a bit here although my opinion is the same. Obfuscation isnt security, people can decompile it and do whatever they want if its on their system. Assets will be taken but such is life.
There are also tons of clones of games, and it's not so easy to go after them. I dont know what smaller companies do but I doubt most caught cases go to court. It's probably reported on the websites which it was uploaded and that's all
yeah, obfuscation is a speed bump, i wonder whether its the case anymore, but i know in the past its been completely possible to decompile a project in its entirety to open in engine. id like to hope 6.0 makes it far more difficult at the least
how can I determen the way my character is facing making a 2D game?
i think you'd want transform.forward
what does it return?
transform.forward would not be it
when your character walks around, and you select their gameobject, does the gizmo arrow change direction?
if the blue arrow points forwards, would that not be transform.forward?
what would be it?
it is but in 2D that would be considered "depth"
could transform.localScale.x work?
oooh youre right!
Unity 2D would be tranform.right = left/right transform.up /updown
brain fart 😆 been a long day
are you doing side to side? because "which direction is pretty vague"
ok yes but what do you want to do with the direction?
because most of the time you're the one determine which way is what
making a blink
a blink? idk what that is
like a quick dash but a teleport
where you can go through objects
its curently working but only in right
well right now transform.right is technically forward
depends how you flip the player
yeah right is forward
if you only flip the sprite, you are technically still facing "right"
but how can I use thath in a if statment
again, you should show how you currently "flip" the player or determine left and right
here is a basic one
Vector2 direction = transform.right;
if (direction.x > 0){
// Facing right
}
else if (direction.x < 0){
// Facing left
}```
used transform.localScale.x > 0
nothing hard about..
bool facingRight
facingRight = transform.localScale.x > 0
if you need to do more logic based on facing direction typing transform.localScale.x > 0 every time is creating more work
This is my blink method for some reason the trail isnt appearing
A tool for sharing your source code with the world!
this is how I defined it
[SerializeField] private TrailRenderer tr;
there is effectively 0 time between when you set the trail renderer to emitting to when you set it to not emitting. and the only line of code that runs in between those two lines is you setting the position. the trail renderer does nothing in that time
still I just need a line in betwen the starting and dthe ending positoin
also how could I fix it
How can I get an enemy’s sprite renderer to pulse red once per hit? I know how to make something pulse indefinitely using the Update() and Pingpong() methods. I’m not sure how to do it for just one pulse though. Any tips?
is your question just about how you'd run it when getting hit is a one time thing? you could still use update and some sort of timer, or just a coroutine.
Every frame, lerp the color of the sprite towards white. When the enemy is damaged, set the color to red. Is that the look you'd want?
I was planning on changing the spriterenderer’s color gradually between two color values. When the player hits, enemy goes from normal color to red back to normal, end color change there until hit again
that was understood, my question is whats stopping you from writing this? A coroutine or update is fine here. In update you just use a timer and can use that timer to check if it needs to be updating.
You could store the time of getting hit and the period of the Pingpong(). In Update(), if Time.time() is greater than the time of getting hit plus the period, set the color to white, otherwise, set it to Pingpong of Time.time() - period.
I prefer the look of instantly turning red and fading back, though.
is there a nice way to get coroutines not to lag
working on a grid streaming system and every time i need to load a new grid, it lags
if i added yield return null after every single line it actually works great but that's definitely awful practice 😭
apologies if this is vague i can give more info if needed lol
I'm having some issues with AddForce() being a bit inconsistent.
Force is added here, in a function only called in FixedUpdate():
{
if(active) rigidbody2D.AddForce(this.transform.up * attack.projectileSpeed, ForceMode2D.Impulse);
}```
when a projectile is spawned, attack.projectile speed is set to a scriptable object variable
``` public void SetProjectile(Entity origin, Vector3 target, Attack attack)
{
active = true;
this.attack = attack;
this.gameObject.tag = origin.gameObject.tag; // used for making projectile not collide with entity that fired it
spriteRenderer.sprite = attack.projectileSprite;
transform.position = origin.gameObject.transform.position;
direction = target - transform.position;
transform.rotation = Quaternion.FromToRotation(Vector3.up, direction);
transform.Translate(Vector3.up * (origin.type.size * 0.6f)); //creates projectile slightly in front of entity
}```
force is removed here once the projectile hits a wall.:
public void Halt()
{
this.rigidbody2D.linearVelocity = Vector3.zero;
this.rigidbody2D.angularVelocity = 0f;
}```
for some reason, every 20 or so times that a projectile is activated, that projectile moves extremely fast until reset.
A coroutine has nothing to do with your lag. It has everything to do what with what you're doing inside it that is causing the lag.
yeahhh that's what i was thinking it was gonna be
it's not even super intensive though like it still runs fast, but just slow enough to cause a slight hitch when going over grid boundaries
isn't the whole point of coroutines for it to be "async" in a sense though?
It's not multithreaded if that's what you mean
think i've got a misunderstanding of coroutines then
initially i thought they were like separate threads that do work without touching the main "get everything done for update in frame" task
i think my issue is stemming from the coroutine trying to load everything in one frame, so it halts to finish that process
would make sense why adding yield return null to every line made it a lot smoother LOL
its not "async" although it mimics similiar functionality
i see
the magic of it lets you spread code over frames instead of doing it at once
i think what im tryna get at is that i just need something that can lazy load the grid in however much time it takes to load, bc all this stuff happens out of the view so it doesn't need to happen totally instantly
like idc how long it takes to load, i just want it to do it, not worrying about how many frames it takes
yes you can use AsyncOperation to for example create a loading bar / screen
although if you need it to be it can be a multithread with jobs or just a plain Async/Awaitable func
Only thing Unity cares about is not calling most of its API out of the main thread
so what would be the best course of action for my case
might be a bit of an issue with the api thing bc im creating a bunch of textures and meshes
depends how you load/generate your grid
im loading everything from a rom, and reconstructing the textures and meshes the first time a grid needs to load
yeah but like for example? System.IO ? LoadResource methods etc.
some of those have async variants
can also docs async Awaitable VeryLongOperation(){ //do some work await Task.Delay(5000);//simluate a long running operation //done OnSomethingDone?.Invoke(whatever); }
even with that it still hitches though
must be the fact that even though it's async or in a coroutine, the unity api calls just take too long
depends what you're doing & what methods are you calling
if you're calling main thread stuff async will probably not change much
guess i've just gotta go in and optimize my model creation process then
appreciate the help on helping me track this down
okie. np . If you share more of the code we could take a look where it can be improved maybe
yeah sure, one sec
it's still a PoC, so apologies if it's kinda bad lol
these are the only relevant files iirc, folderPath is empty in this case bc im not static-ly saving assets to the project, was originally for editor import use
unless its the unpacking slowing down most of this shouldnt be so bad using it in a coroutine or even async with the OnInitialized static function launching all the prep
not sure where you got this from lol private async void Update()
lol i forgot i left that there
afaik the only entry async method unity has is Awake
i mean you can just make it async and it still works
but obv it doesnt fix anything
whatever you cooking here looks sick and might be something i've def thought about messing around with doing but just a heads up that showing this might not necessarily be ideal aha 😅
yeah you right
Let's say I have some UI elements on a canvas. They can process mouse events. However, I would like it so that if the elements are processing mouse events, anything "behind" the ui, like clickable objects in the gameplay world, won't also process mouse events. Any general ideas?
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html (you can use this check to block your world interactions)
I usually have a UI manager that I can query about whether the pointer is over ui or not. Inside it, it could be querying the event system.
Ah ok, I'm doing something similar (but a little bit more barbaric compared to what you're doing). I'm basically firing off an event every time the UI has the pointer over it, and non-ui scripts can process that event. Leads to a lot more work compared to what you have though, so I'm gonna go change that XD
i tried to make my own wallrunning script on top of my player movement script. i want to stop the wallrun when i press space bar. but for some reason, sometimes when i press space bar the function is not called. can anyone take a look and help me out please?
Share !code properly
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
A tool for sharing your source code with the world!
The issue is probably querying the input in fixed update. Fixed update doesn't necessarily run every frame. So you could be skipping frames where input happens.
i switched put the state() function in update now. the thing is exitingwallrun bool turns from false to true earlier than 2 seconds sometimes, even though i invoked it for 2 seconds
Well, it wouldn't be 2 sec exactly. It should be 2 or more though. Not less.
huh?
sorry i am a bit slow
It would get executed on a frame when the time is >= 2. And there's no guarantee that frame would start exactly on the 2nd second.
yeah, but my problem is that the function is executed less than two seconds
Yeah. That's technically not possible. Are you sure you're not just misinterpreting the results?
You can log during the invoke and inside the invoked method and compare the log timestamps.
i log every time the exitingwallrun bool is changed.. it sometimes turns from true to false in like half a second
Make sure you're not calling it more often than expected.
And make your logs more verbose. It's not clear what exactly is "True"/"False" and where this is printed. Add more text to make it clear.
the function is called only once
how do i make my logs more verbose? the only thing im logging is exitingwallrun bool btw
Log text.
"On Invoke called" or something
"on method invoked"
how do i use a log text? documentation is down i think sorry
Debug log takes a string:
Debug.Log("text");
And you can also use string interpolation: $"text {variable}"
oh okay lemme try that out
but before that why does this happen though
this is the exitingwallrun bool btw
It doesn't. It's likely one invoked earlier.
that doesnt explain the second false return on the end though
You're likely misinterpreting the logs. It's easy to get mistaken with so many
Especially considering they don't provide any details
It's also possible that you're calling the method somewhere else as well
i am a 100% sure i am not, you can see in the code yourself
hmm true
i brainstormed for a long time, i couldn't figure out anything. any help will be appreciated
private Image _backgroundImage = null;
private Image _controllerImage = null;
[Header("Configuration")]
[SerializeField] private bool _rightAnchorPoint = false;
[SerializeField] private bool _topAnchorPoint = false;
[Header("Generated Information")]
[SerializeField] private Vector2 _virtualInput = Vector2.zero;
[Header("Settings")]
[SerializeField, Range(2f, 4f)] private float _controllerRange = 2.7f;
public float HorizontalInput => _virtualInput.x;
public float VerticalInput => _virtualInput.y;
public Vector2 VirtualInput => _virtualInput;
public void OnDrag(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(_backgroundImage.rectTransform,
eventData.position, eventData.pressEventCamera, out Vector2 outLocalPoint))
{
CalculateVirtualInput(in outLocalPoint);
UpdateControllerPosition();
}
}
public void OnPointerDown(PointerEventData eventData)
{
OnDrag(eventData);
}
public void OnPointerUp(PointerEventData eventData)
{
_virtualInput = Vector2.zero;
_controllerImage.rectTransform.anchoredPosition = Vector2.zero;
}
private void Awake()
{
_backgroundImage = GetComponent<Image>();
_controllerImage = transform.GetChild(0).GetComponent<Image>();
}
void CalculateVirtualInput(in Vector2 localPoint)
{
Vector2 inputVector;
Vector2 inputVectorClamped;
inputVector.x = localPoint.x / _backgroundImage.rectTransform.sizeDelta.x;
inputVector.y = localPoint.y / _backgroundImage.rectTransform.sizeDelta.y;
inputVectorClamped.x = inputVector.x * 2 + 1 * (_rightAnchorPoint ? 1 : -1);
inputVectorClamped.y = inputVector.y * 2 + 1 * (_topAnchorPoint ? 1 : -1);
_virtualInput = inputVectorClamped.magnitude > 1.0f ? inputVectorClamped.normalized : inputVectorClamped;
}
void UpdateControllerPosition()
{
Vector2 controllerPosition;
controllerPosition.x = _virtualInput.x * (_backgroundImage.rectTransform.sizeDelta.x / _controllerRange);
controllerPosition.y = _virtualInput.y * (_backgroundImage.rectTransform.sizeDelta.y / _controllerRange);
_controllerImage.rectTransform.anchoredPosition = controllerPosition;
}
}
hi quick question... I want to change the camera joystick to turn the other way because when I turn left the camera turns right and I know that I just have to change some code
i need change one line of code for fix but i dont know which line of code change
when one side of the controller is "+1" and the other side is "-1" ... you probably just need to reverse them .. i think you will find your answer
i will check wait
nope :/ its not working
i found this script on github and i testing how it work
thats what i was thinking.. just copy & pasting without understanding doesnt help you in any way..
yeah
i will try my self fix it
up and down work well but left and right works the other way around
i find and learn how this script work
horizontal (x) is left and right.. vertical (y) is up and down.. maybe that helps
I don't remember if you can invoke a method with parameters, but if you can, I recommend passing something in. Like a counter or timestamp or something. And print that inside the method
you cant apparently 😔
Then perhaps avoid Invoke entirely. Use a coroutine.
okay i found the issue, when i invoke the function, the function is getting called for 2 seconds straight. eery frame for the entire two seconds, the bool is set to false.
how do i change it so that the invoke method calls the function only once
Just invoke it once. You're probably invoking it more than once every frame
This condition is being true for several frames. If you don't want it to keep invoking, make sure that the condition in the if statement is false after invoking once.
if (state != "wallrunning" && exitingWallrun)
{
Invoke(nameof(ExitWallrun), 2f);
}
oooohhhhhh. any idea how i can do that without over complicating it?
Honestly, it sounds like you're trying to implement a state machine, but doing it wrong.
I'd recommend looking at some state machine tutorials.
alright. thanks a lot!
why api scripting reference and package docks websites don't work?
Someone spilled coffee on the servers
If I have a class which is subscribed to an event, then the scene changes, then gets back to the original scene, why does the listener not work? Should I unsubscribe then resubscribe?
The instance of the component that did the subscribing was destroyed.
Loading the scene again is giving you a different instance.
if you unload a scene and load the same scene again those objects are not the same objects
they start out the same but they are not the same
Sure, so the solution is to unsubscribe on scene unloading and then resubscribe when it comes back
Right?
That would probably be ideal practice yeah, although it's worth noting that in practice in this case you shouldn't need to unsubscribe i don't think
Just mentioning in regards to logic still good to do
Yeah because the event is fired from an object which doesnt get destroyed on scene changes
Thats why I'm wondering why it doesn't work.
Currently I have a returning input which if you press a button, it holds "Back" function which disables the UI in front, and enables the previous one. If the scene changes, and we come back to the original one, this doesn't work, the returning feature doesn't do anything.
always unsubscribe
share !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Does Start resubscribe when a scene changes?
Or should I use OnEnable and OnDisable?
start only runs once per instance
Anybody knows how can I make my 3D active ragdolls arm follow my cursor like in game half sword. I dont have bones. I have 2 parted arms(upper and lower) with configurable joints.
Is the ragdoll replicating another animated character?
Yes the legs follow for walk but arms are free right now
Make the arms work and use some arm IK on the animator that it's replicating
Setting up proper active ragdolls is a massive pain though, just so you know.
Here's some helpful code for setting the target rotation https://gist.github.com/mstevenson/7b85893e8caf5ca034e6
@swift elbow > https://paste.ofcode.org/HJ68CfcdXCCqc6ZWQwHV8H
oh duh. i forgot youre using rigidbody so this approach wont work. mb
BRUH! what should I do then?
float newHeight = isCrouching ? standingHeight : crouchHeight;
capsule.height = newHeight;
float heightDifference = previousHeight - newHeight;
Vector3 positionAdjustment = new Vector3(0, heightDifference / 2f, 0);
rb.MovePosition(rb.position - positionAdjustment);
isCrouching = !isCrouching;```
no need to panic lol. i think something like this should work
dont forget to create an isCrouching bool
Thank you so much this is very good, one question though how can I make it smoother when crouching and standing back up?
you should look into lerping. its fairly simple
How too "spawn" a specific tile from a tilemap? context i have a json that specifies tiles for a world (2d) like this:
"tiles": [
{
"x": -5,
"y": 0,
"ID": "1"
},
{
"x": -4,
"y": 0,
"ID": "2"
},
...
]
}
and i want that for example ID 1 = grass ID 2 = dirt
u'd run a function that uses a switch statement or something or.. u can just have ur list or collection 1:1 so they match up
oh thanks
u know how to read from json right?
ye i already did that
ahh cool so yea a switch statement or imo it'd be cleaner just to have a colllection list or array w/ the tiles corresponding to the numbers
so ID 2 would = Collection[2] etc..
then u could just do MyTiles[IDVariable];
thank you for the information!
tilemap.SetTile(position, tilesByID[tile.ID]);```
hey could somebody help me understand how to debug the problem i'm facing? have a web development background and i started learning unity off a youtube tutorial today. it's a 2d top-down project and i have the animations working but my character's in the same spot. it's switching between the different walk sprites but it won't actually move around the screen if that makes sense
you need code to move things around
i do have vscode open but it doesn't help that this is my introduction to c#
i understand that though
animation is just animation
u need to move the object with code
or use root motion <-- look that up
i understand this but i don't know how to debug what's going on since this is my introduction to both unity and c#
Debug.Log();
i followed the tutorial but i must've missed something
("The message u want to log");
no error pops up or anything
or.. (theVariable)
then ur code isnt running
or ur debug is somewhere it isnt getting reached
did you put the script on your object in the scene?
yeah i have a player movement script
show the script and show where you put it in the scene
!code 👇 read
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
using UnityEngine;
using UnityEngine.InputSystem;
public class playerMovement : MonoBehaviour
{
[SerializeField] private float movespeed = 5f;
private Rigidbody2D rb;
private Vector2 moveInput;
private Animator animator;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
rb.linearVelocity = moveInput * movespeed;
}
public void Move(InputAction.CallbackContext context)
{
animator.SetBool("isWalking", true);
if (context.canceled) {
animator.SetBool("isWalking", false);
animator.SetFloat("LastInputX", moveInput.x);
animator.SetFloat("LastInputY", moveInput.y);
}
moveInput = context.ReadValue<Vector2>();
animator.SetFloat("InputX", moveInput.x);
animator.SetFloat("InputY", moveInput.y);
}
}
In update, log moveInput and see if it changes as you move your joystick around
Or keyboard buttons
THANK YOU SO MUCH it finnaly works :D
Me and my friend are trying to use Unity Version Control to collaborate. I invited him as a User to my project and he cannot create a new branch using the Unity DevOps Version Control app. Could someone help me how to give him proper permissions so he can create his own branch?
it's logging the movement just fine afaik
Okay, so it should be setting the rigidbody velocity. Your scene looks pretty empty, are you sure it's not actually moving? If your camera is set to follow the player directly it might not even be possible to see movement
Why is the blink not geting canceled on touching a block?
here is the code for player movment https://paste.mod.gg/daslcnojqafe/1
A tool for sharing your source code with the world!
why would it
its not even detecting collisions why?
take a wild guess lol
i haven't gotten into cameras yet as i'm very early into this tutorial series. from what i can see the example in the video shows the character moving around the scene even though it's as empty as mine
would linking the video help?
most of the 2d stuf you literally just append 2D to it
oh ok thanks
Unity is asking me to choose a template, do i have to do this, nothing that i want to follow to start making my game says anything about templates?
well you need to use at very least the blank one, which. is Core
mainly the choice to consider is URP vs HDRP
or BiRP (although this is being phased out)
any help on this
if I have a large 2d environment, no player character just the camera as an overseer, how can I get a smooth movement between rooms?
I have camera anchors for each room, and I can make it move between them, but I'd like to be able to make the camera movement smooth and crisp, where it quickly swooshes from one point to the next without stopping or starting instantly but also not just sliding_stone_block.mp3
I have a resource bar that's continiously draining, multiplied by deltaTime. I also have an event that broadcasts the resource amount in Update(). I initially thought updating the event would be slower performance wise so added a timer to update the event every second, is this right?
I tried to use the profiler but I am not sure which metrics I want to look at for this.
are you asking if broadcasting an event in update is fine ?
yes
I think it is just a pointer updated in the system but I am not sure if there are other performance handicaps
yeah you should fine
in the programming pathway course, in the plane programming part, the plane starts rotating on its own when it touches the wall, how do i fix that?
probably locking the constraints..which plane programming part?
thank you so much!! it worked :D
how do i make a variable name use another variable's value to make that name
as in I want to create a variable called "Level (variable)"
or is that not possible
it isn't possible, those happen at different types
why do you need this?
why do you want to do so?
i want to create a variable called level"variable dependent on stage"completed
why do you want that variable though?
so i can check if it's true to check if the player unlocked a stage
another question, is a global variable persistent between scenes
what would be a global variable?
static public
most likely what you want is just a collection storing the ids of the completed stages
that doesn't make sense
that would be persistent between scenes, yes
c# doesn't really have "globals"
do you mean like, multiple of these variables, or what?
yes, each with a different number depending on the current stage number
if you ever end up with numbered variables, you most likely want some kind of collection instead
are your levels sequential?
yes they are
so why not just have a single variable that tracks how many levels have been completed
trying to learn unity lingo. when people talk about a character controller, is that the interface with the joystick, the behavioral control for the rig, both, or more
It's the entirety of everything involved with making a gameplay character.
even the art and network?
If it's involved with making the character, yes
alright. thanks
there is also a specific component called CharacterController
Quick question, can I have default references of arrays? As they are of non-changeable length, I thought it would be possible, but they aren't displayed in the inspector
wdym " default references of arrays"
Just like I have a default reference to this mixer, could I have a default reference to a list/array of AudioClips?
you mean [SerializeField] private AudioClip[] clips ?
you should be able to since they are assets and not scene objects
Ah I guess I just made them public but didnt serialize the field
public is already serialized
Then it didnt work
you made them field not property right?
yea looks fine
Dont appear
Whereas mixer does appear
Quick check, I just did AudioClip instead of AudioClip[] and I did see the AudioClip there
oh thats strange.. let me try it on my end. maybe its true which would be odd..
I think maybe because Unity Initializes an array when it is attached as a component
Hmm let me try list
I wonder if it works if you added new()
Let me try
[SerializeField] private AudioClip[] clips = new()
Ah he doesnt like that
Dont see the new() List either
Lets see what happens with this
private AudioClip[] clips = new AudioClip[1];
ya sorry you need fixed size for array
thats balls
Glitch in the matrix
def something to do with the Editor drawing
Using Unity 6000.0.36f1
Ah so it should work but for some godforsaken reason it wont? :D
let me restart editor
Ah okay
i think for arrays unity does something different so it needs an instance
you can make a simple workaround though if you want to still do that
put your array inside a ScriptableObject then make a field for that, it should work
hey guys can someone help
Hmm alright. To fight the root of the problem: How would I have a collection of AudioClips, and in my script I access them
// Play sound
AudioClip newShootSound;
do
{
newShootSound = EnemySoundManag.Instance.ShootSounds[UnityEngine.Random.Range(0, EnemySoundManag.Instance.ShootSounds.Length)];
} while (newShootSound == shootSound);
shootSound = newShootSound;
AudioManag.Instance.PlayAnySoundFromList(VolumeType.SFX, clip: newShootSound, volume: 0.2f);
It's annoying to have to have a Singleton thats holding all the audio data but hey, I could (un)load the data individually per level then I guess
I have this slider in the scene but when I switch to the game it doesn't show up 😦
if its an audiomanager why not
Well basically instead of adding my sounds to each enemy I thought how about I have one class as a collection for all sounds, and I dynamically access them there
this isn't a coding question #📲┃ui-ux has pinned guide on how to properly anchor
oh ok
seems reasonable. I mix both
some objects have their own sound component on them
Oh yeah, for music I do that (with a custom looper class but still)
Hm I guess I'll just do it like this. Not as manageable as I had planned but it's still alright I guess, will keep a prefab and add it to each scene ig
the reason I like not storing on the enemy per se, is if you have an event thats all you need to "listen" to
Yeah
like if enemy Jumps, why not just access that from a dictionary.
the enemy only cares about OnJumped?.Invoke()
the rest reacts to it
Could make "blue enemy" inherit from a "enemy" class with that event action but this works for me
Alright, thanks for your help!
something magical happens if you google that same exact thought
Do I sense a sprinkle of sarcasm...
chill no need to embarrass me 🙏 
I'm not lol I've seen it all here almost, some people legitimately forget there is a search engine now days
just jk lol ❤👍
If you wanted to know what the bug was the listen button doesn't work because in one of the scripts they spelt Search wrong it says > Seach instead
that would be pretty funny if they did
They did indeed.
It happened to me I check and it was right there "Seach"
put a r in there an it was fixed
hasn't this been reported already
clearly not as its still not fixed lol
that's not what that means, no
Are you on the latest ver? xD
Unity 6 yes
even if it hasn't been fixed, if it's already been reported, you reporting it again will just be noise
go find the original report and boost it
I mean the latest 6 version
if its already in the tracker yes you should vote it up
45
although fixes like this aren't pushed right away
Coroutines waiting for next frame with yield return null is Time.timescale independant, right?
mines 42
also note that it is not the editor version that matters, but rather the input system package version
the unity version wont matter if its Input System it probably gets updated in the package
jinx
Good call
lmao
Ur both right, I feel double stupid now :')
correct, timescale does not affect frame time, it only affects the value reported by deltaTime and fixedDeltaTime
Good to know! Is there a reason to use yield return null or would yield return new WaitForEndOfFrame(); have the same effect?
WaitForEndOfFrame(); has tiny extra allocation but its the same thing no?
they don't do the same thing
they do not have the same effect, WaitForEndOfFrame is evaluated at a different part of the frame
So the default syntax for waiting a frame is to yield return null?
OH wow
If I'm trying to create a main game manager node to hold a bunch of random important information related to overall stats and supplies and such
Would it be better practice to
-shove everything into one script on one object
-multiple scripts on one object
-object has children with categories, like
main > gunnery > scriptThatHandles Gun > artilleryGunAzimuth
main > supply > scriptThatHandlesStorage > medkitsInStorage
I would personally say what serves you best as a single dev or what is the most readable as multiple devs. Always keep it in scope, scale and to your knowledge (dont implement 100 completely new features, just because it is said they are good on a project with no scope in that area whatsoever)
Basically step away from visual studio and build a readable graph just like this
draw.io is a great for that, and it's free
powerpoint is also viable
don't need anything fancy
paint.net is my personal favorite for simple stuff. It's free (on the official page, not the microsoft version) and has a lot of cool tools which paint or paint3D are missing out
I'll give that a shot, didn't think to pre-map my logic out like that
did something similar for my screen layout WIP
how can I make a slider slidable with the mouse?
I think it's as important as a gdd to map out code before diving into coding
slider is already slidable with mouse..
yeah, that makes sense
I've done some pretty complex things in a few languages for school and for my first job, but this is my first time being the one MAKING the design specs instead of just following them
when I click/drag it it doesn't move 😦
do you have event system in the scene?
also this isnt' a code question
oh mb
yes
If it doesn't move then something is either keeping it that value, or you might have an ui element blocking it
Like an invisible panel or something
inspect the Event System in playmode when you click something, see what it is
allllright let's go to #💻┃unity-talk @noble needle
@noble needle
https://learn.unity.com/pathway/unity-essentials
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
why is my game crashing from this?
https://paste.mod.gg/iictofkzqzgv/0
A tool for sharing your source code with the world!
define "crashing" here, because there's nothing in this code that would generally cause anything to "crash"
then it's some other code
when I try shoting
so then maybe show the code for that
Nothing here involves shooting
also it is against server rules to not disclose AI generated code 😉
this is the code
spawning
its not Ai I promise
I spent 30 minutes trying to get it work
it spawns the bullet and gives it velocity or am I stupid?
Where does it spawn the bullet
GameObject newObject=Instantiate(objectToSpawn, transform.position, Quaternion.identity);
think you may have pasted the wrong class mate
Yep
There is nothing of the sort in the code you've posted
oh I might have posted the wrong code my bad
A tool for sharing your source code with the world!
there it is, you have an infinite loop
Your while loop can never end
how if they are slowly coming closer
Nothing in the loop changes any of the values in the condition
i don't that should be in a while loop anyways
you're using deltaTime, so it seems like you want it to move over several frames
Putting "MoveTowards" in a while loop also doesn't make sense. If you want the object to go towards the destination in a single frame, just set the position
the while loop will make it happen in a single frame
It'll do the same thing
not a single frame
do I need a seprate function?
The definition of a frame is how long it takes for every objects update functions to finish
Everything done in update will, by definition, take 1 frame to do
the while makes it do MoveTowards multiple times
and it's within a single Update call, so it's happening in a single frame
you might want an if instead?
Do I need a IEnumerator function if I wan it to slowly be moving twoards the location
just this
you only need to change the while to if
ive got something i wanna correct with the unity input plugin when it comes to inputs that trigger every frame
because my mouse left click function only triggers once when the mouse is clicked, instead of me wanting it to trigger every frame
(me trying to make an automatic weapon but it ends up just firing once)
What does the current code look like
changed while to if
(setup for the input)
What calls HandleFire
Is it still in your input check? That's going to run exactly one time when you click.
just the input addon
I got most of the things out of the press left click it says this Assets\shoot.cs(21,54): error CS0103: The name 'newObject' does not exist in the current context
I get why but dont know what to do about it
So that's only calling it on started, which is when it goes from 0 to a non-zero value, and won't start again until it returns to 0
also occurs for the "performed" phase too
Question: why is the script that's spawning the bullet the one that's responsible for moving it? Wouldn't it make more sense for the bullet to move itself?
i set it to started to see if it would fix (my movement is called this way, manages to work fine, but the mouse click just doesnt wanna happen every frame)
gonna try to see if putting it into the update function will fix something
well I dont know I am stupid I g
yeah it's because it wasnt in the update function
now it's working fine
hey everyone, what is the best practice to make a visable "visual only" grid for players to refference. 2d games usually have a visual grid that looks like very thin string-like lines.
how should i approach this? I was thinking about using the line tool but it seems like overkill. any suggestions?
Might be good to check out https://bgolus.medium.com/the-best-darn-grid-shader-yet-727f9278b9d8
this seems like overkill as well. my game camera never moves and it's top down 2D. i just need visual lines to appear just like the unity editor lines and they need to snap to the same unity grid
I am getting a bunch of erors for unknown reasons
Can probably just make a small repeating texture then
ummm.. i want to be able to make edits to the grid on the fly for debugging... I'm thinking i want to do something similar to a debugdraw line tool... can't i just use something like that and just simply draw 1 pixel lines?
linerenderer
I have to where my bullets destroy how can I make the original one not do this I kinda need it its a refrence for everything else spawning
if u need further explanation I can send code
make the original one not do this ?
which original
how do I do thath
isnt clear what you're asking here
I will send you the code for the bullets
A tool for sharing your source code with the world!
so what do you want to do?
well how can I make the original bullet thath my weapon is refrencing not disapear
is this posible
are you cloning the original?
objectToSpawn isn't being touched though
its just cloning it
ideally
drag the bullet in the Project folder, now its a prefab. Remove it from the scene and drag n drop THE BLUE in project folder to the Gameobject field on Weapon
ok I get it
Prefabs are templates to objects
I get 500 error but here https://docs.unity3d.com/Manual/Prefabs.html
show what you did
why didnt you remove this one
whivh one
didnt know I was suposed to my bad
My tracking isnt working
I am gona cry
the bulets arent going the corect way
for
some reason
when I am on one platform its normal on the next one its glitching
idk but this doesnt seem like should be in the bullet in update
mousePosition=Camera.main.ScreenToWorldPoint(Input.mousePosition);
as it always changes..
just pass the direction directly from the shoot
how?
var spawnedBullet = Instantiate(objectToSpawn, transform.position, Quaternion.identity);
spawnedBullet .GetComponent<bulet>().Shoot(passDirectionHere)
make a new method for Shoot
the shoot script should be the one tracking the mouse
what is this I am getting mind blown
this all basic c# stuff mentioned earlier you should probably do.
also you probably don't want to directly move the transform if you plan on using collisions
so you can pass values from shoot to your bullet.. there is no reason bullet should be doing any of that
oh okay
it surely will be if you dont understand the code you're writing
Hi, I'm having an issue trying to make a following camera on my 2D game look decent. Currently, it follows the player successfully; it even has a little smoothing to it so its not locked perfectly onto the player while in motion. Unfortunately, while in motion, the player sprite looks horrendous. It appears to jitter in place.
The sprite I'm using is only 12x32 pixels, which I assume is one of (if not the) reason why this issue is happening. If it is, what should I do? Should I actually make the sprite much larger and then scale it down in the editor?
why am I having this error
Assets\Scripte\shoot.cs(16,39): error CS0246: The type or namespace name 'bullet' could not be found (are you missing a using directive or an assembly reference?)
so it's pixelart?
have you done all the pixelart asset stuff, and are you using a pixelperfect camera?
Yeah, this little guy right here. As I'm expecting discord's embed to show, it is very small.
What is bullet
you tried to use something that doesn't exist
how bullet is the object containg the bulet scipt
I am confused how can I corect this?
I did try using a pixel perfect camera but it looked even worse, maybe I had settings for it wrong, but it was too staggered. I'm wanting a normal, smooth camera for this pixel platformer demo I'm working on. Do you want me to try record a video of the issue I'm referring to?
(also I'm not sure what you mean by the pixelart asset stuff)
Is it an FAQ I overlooked
what are you trying to do? i see you have a prefab named Bullet. are you trying to assign the prefab onto a script?
Yoooo, how do I pause only some elements of the game?
public void Pausar()
{
if (GameObject.FindGameObjectsWithTag("PauseThings"))
{
Time.timeScale = 1f;
}
else
{
Time.timeScale = 0f;
}
IntroAnim();
}
filter to point, compression to none, and set pixels per unit appropriately
I wana acses the sript of the bullet I spawned
Show the code where the error is
the script is also called bulet
ok, what is it called
I though this help but it didnpt
Time.timeScale applies to everything
First two are already done - how do I determine what the appropriate pixel per unit is?
You will need to create a Boolean that these scripts can read from. If that bool is true, skip any code you don't want to run while paused
I am trying to give it the mouse position previously found
either:
- make your own system to handle pausing, where you set a variable and the stuff that should be paused checks for that to stop running
- make the stuff that shouldn't be paused, use unscaled time instead. but that'll make it not respond to anything else that affects timescale as well
this is the code
if (Input.GetMouseButtonDown(0))
{
Vector2 mousePosition=Camera.main.ScreenToWorldPoint(Input.mousePosition);
var spawnedBullet = Instantiate(objectToSpawn, transform.position, Quaternion.identity);
spawnedBullet .GetComponent<bullet>().bulet(mousePosition);
}
Do you have a class named bullet
define what a "unit" is in your game
maybe a tile width or something
your player is 16x32, so maybe ppu would be 16 or 32 depending on if your player should be 1 or 2 units tall
what component are you trying to get there
Then why are you trying to get a script named bullet if you have none
where are you updating your camera position?
ok so it's named bulet
but you're trying to get a script named bullet
see the issue here?
Okay but what does that matter? You're trying to get a component named bullet
anyways since you want to access that component, you should use that component as the type for your prefab instead of GameObject or Transform or whatever you have it as now
then you can get the component directly back from Instantiate instead of having to go through GetComponent
So I swap the first to bulet and the second I gota make a oublic vector?
<bulet>().Mouseposition(The mouse position vector I found)
Is this corecct
does your script have that function?
no it dosent I gota change it
It's in its own script attached to the camera, it was originally in the LateUpdate() method which had its own horrendous-looking jitter to it, so I changed it to FixedUpdate(). While that does look much better, its clear that there is some issue with the pixels of the sprite when the player moves.
can I just move this one wariable from here to bullets code
it should be in LateUpdate
if it's in FixedUpdate it might not be moving every frame
Yeah it was but it looked even worse than FixedUpdate()
it caused the player sprite to jitter back and forth and blur while doing so
(or multiple times each frame, if that's inconsistent then it'll step weirdly)
track the mousePosition in the Update of shooting , and only use that postion/direction when you spawn the bullet and pass it as shown
no need to track mouse in every bullet spawned, that was the point of that btw
you're just trying to Run before learning how to crawl
Update: It seems the cause of the horrific blur while using LateUpdate() is due to the smoothing effect I've put on the camera. Is it not possible to have parity between LateUpdate() and a slight, smooth "lag" to the camera while maintaining visual quality?
nvm I am just confused asf
Without the smoothing effect it looks completely fine but it would be a big shame to have to drop it
confused about what?
we're talking riddles here, you have to be specific
we don't have eyes on your pc
because you have a compile error
also why is your IDE not configured
I thought you did that
because you made a mistake
it's definitely not configured
because you copied my example verbatim including a variable that doesn't exist?
there'd be a lot more green if it were configured
and underlined red that Shoot() function
not even using the same capitlization...lord
and why does the one in bulet return an int
this just goes from worse to horrible the more i look
I know
a while loop 😬
yeah this isn't a guessing thing
you have to be exact with this..this like exact math/science you're dealing with
throwing random stuff at the wall won't work
thats like 2% of the bigger problem
if is wrong, why put an if there?
if all you're doing is tracking how far it went from your shoot pos then track that in update
mousePosition/targetPos should be a field that gets its value from Shoot Method
oh so method is just to get position
the method is just to get value from another script
so you dont have 200 bullets track the mouse
oh okay so I figured it out thanks
Vector2.MoveTowards ignores whats between just fyi
your bullet would phase through obstacles/walls
I will do on colison later
OnCollision doesn't help
just one question its saying something something protection level
transform literally teleports, its not good collision
on collision2D destroy
screenshot the error otherwise we can't help
you made shoot() private
of course it cant be accessed from other scripts
this is partially why a configured IDE is important so you can catch these before hitting save and going into unity..
and the rules #📖┃code-of-conduct or #854851968446365696 forgot which
we shouldnt have to tell you multiple times
wait we literally had it working..
https://discord.com/channels/489222168727519232/1358142843629207622
or did you lie?
🤔
Tried to make a jumping and walking animation, Walking works but I cant jump anymore: (
A tool for sharing your source code with the world!
this is the code
did you verify the isGrounded condition is met ?
also Animator might be taking control of the transform? idk
if(Input.GetButtonDown("Jump") && !isGrounded)```
Looks like you have it set to only be able to jump if you're already NOT grounded
which doesn't seem right to me
I see what should I change
especially since then you're doing isGrounded = false inside that
what do you think? When should you be able to jump?
When you're grounded?
Or when you're not grounded?
when im grounded
so make the code reflect that
! means NOT remember
oh righttt
you probably just wanted to keep it for animator.SetBool("isJumping", !isGrounded);
but not when on ground to jump
Secondarily:
private void OnTriggerEnter2D(Collider2D collision)
{
isGrounded = true;```
This isn't the most robust grounded check, you may run into problems in the future with this
look into Raycast and alike
maybe boxcast so its wider.. ? depends on you want the shape to be ideally to match bottom half of your collider
I see thank you very much! this is my first platformer trying top learn as much as possible
"MonoBehaviour" is what you want to make
👍
does this make sense? im coming from python so im not sure if this is how it works, it says == isnt valid
if (GameObject.GetComponent.Collider.OnCollisionEnter(Collision)) == True;
{
playerBody_Ragdoll.AddForce(Vector3.up * playerJumpForce, ForceMode.Impulse);
}```
this is hella wrong
also you should configure your IDE
saw your ide was def not configured
ide?
i mean i kinda just installed it and got it working lol
i think theres a unity debugger extension
nope not configured
it would not show the entire path
colors are off
and at the bottom it would say Project: Assembly-CSharp
can someone help me this something i never thought would be so difficult lol
I'm trying to draw a rectangle on a grid with mouse dragging.
It's working.. but it's inverted when im dragging in a negative direction.
so i want to flip the start and end positions of the mouse drag if it's moving in a negitive direction.. how to do this seems really difficulkt.
which i bet doesnt
after you get your IDE configured go look at code examples for collision detection, this is way off
alright
here is what to look for
how do i do so?
!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
if you verified all the steps above in the link
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
ah ok
im on linux so i need to find a different one
I use Mint, the instructions are exactly the same
as long as you didnt install them using some type of self-contained install such as Flatpak
ah thats why it didnt work? i had to install snap
its possible. From my experience those usually create self-contained installs and have a hard time connecting to other applications
its always best to use apt get when possible or .deb (if you're ubuntu,debain mint etc.)
.rpm for fedora and such
https://code.visualstudio.com/download
also one of the important steps is having the .NET SDK and the Unity Package Visual Studio Editor package
Get the minimum and maximum X and Y coordinates of the start and end vectors
For example cs Vector2 min = new Vector2(Mathf.Min(start.x, end.x), Mathf.Min(start.y, end.y)); Vector2 max = new Vector2(Mathf.Max(start.x, end.x), Mathf.Max(start.y, end.y);
Oh I just learned that Vector2.Min/Max exists too, so you can also do: cs Vector2 min = Vector2.Min(start, end); Vector2 max = Vector2.Max(start, end);
how do i get it to find my vs code? i cant select it using the browse option as it isnt an executable from what i know
something like this?
You have an error - probably because you put a semicolon at the end of that first line improperly
nah its this
Just remove that semicolon
You put it inside another method, don't do that
void Method()
{
void LocalMethod()
{
}
}```
that's not an error it's a warning, but it's an important one
why not?
Unity won't find it that way
OnCollisionEnter is a totally separate thing it's not part of your movement function
it needs to be its own function
is this not right? i feel real dumb rn
now you put it outside the class
it needs to go inside the class, not in any other functions
// You put it here. Bad.
void FunctionWrong() {
}
class MyClass {
void Function1() {
}
void Function2() {
}
}```
it was this extra bracket at the top
yes you have to be careful with your brackets, they are what define the boundaries of the various code elements (classes, methods/functions, if statements, etc)
ya
im guessing it cant find my playerRagdoll_body? (using screenshots cause i feel like knowing the code lines are important)
playerBody_Ragdoll is null, yes. You need to make sure you've assigned it a value before you use it.
It's not about "it can't find it". It doesn't try to find anything automatically. You have to give your reference variables a value either by assigning them in code or in the inspector.
a value? but its an object, do i give it a str or set it to true lol
No.
Like I said
assign it in the inspector
or in your code to whatever type of value it is
"an object" is kinda meaningless. Everything in C# is an object
do you mean GameObject?
I think it's a Rigidbody most likely based on the context here, not a GameObject
The most straightforward way to assign values to your references in Unity is through the inspector. I would stick with that for now.
ohhh, yea its a rigidbody
well, its a rig i wanna put on a rigidbody
rigid body is more of the collision
i forget i cant "attach" scripts like in godot they need to reference the object specifically i think
oh i set it to private? maybe if i make it public
if you make it public or if you mark it with [SerializeField] then you can assign it in the inspector
ohhh i get it now
neat,
perfect
can i export a procedural texture from blender to unity?
If you bake it, sure.
aww,,, i was hoping i could just export in its base format
There is nothing to export. "A procedural texture" would just be some shader code running and generating at runtime.
And you can't export shaders between blender and unity(or any other programs really).
then ig id have to remake it
I downloaded an asset pack that has both tiles and objects. The tiles were fine and I managed to put them into a TileMap, but the objects are all different sizes
Is there an easy way to get these into unique sprites?
And then once I have them in unique sprites, what's the way to use them as such? Do I just layer them on top?
not a code question
set the image to Multiple and slice it
ah fair point
yeah that was my first attempt but since they're different sizes it slices them up poorly
use autoslice and it tries its best then you need readjusting, the link I sent addresses that
I'm not sure if this is the right place to ask, but I'm feeling real stupid. I'm using unity 6 with Visual Studio 2022 on Windows, and it seems like when I edit a script, it updates in the display window in unity, but I have to close the editor then launch it again to get it to update the behavior when I press play. is this intended? Or is there something im likely doing wrong?
Perhaps you have "auto refresh" disabled in the preferences?
You need to turn it on or manually refresh withi Ctrl + R
Ah seems like auto refresh was off. Thanks!
So I made a pretty basic chunk loading system that feels unnecessary to run on the main thread…I check if the player moves to a different chunk in update, and if they did, calls a method to delete far away chunks and make new ones. Should I make chunk drawing method async/await? run on a different thread? What’s the best move here
It depends what it involves. If you can afford to move it to a background thread it would be a good idea to do
Alternatively make it async on the main thread.
So I’m not entirely sure how to do that in unity I’ve read some stuff about unity not being thread safe