#💻┃code-beginner
1 messages · Page 682 of 1
make sure you also change the parameter to Collision2D
using UnityEngine;
public class Enemy_Test : MonoBehaviour
{
public int health = 100;
void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("We collided with something.");
if (collision.gameObject.CompareTag("Player"))
{
Debug.Log("We tested and collided with the player!");
TakeDamage(10);
}
}
public void TakeDamage(int damage)
{
health -= damage;
Debug.Log("Damage taken: " + damage);
if (health <= 0)
{
Destroy(gameObject);
}
}
}
wait
i made one static class and unity is freaking out, ai says its a 'Unity parser bug'
is that a script for a enemy to take damage or for it to deal damage
since its on the enemy.. it detects contact with player..
and damages itself
simple mode: (1) script
but you can use that to deal damage to the player, right
Where would i add a webhook here?
yes, it would just be opposite in my setup
the player would detect if it touched an enemy.. and damage itself..
or u can flop it out and have the enemy damage the player
my code was just buns 😭
ya, kept adding to it and adding to it..
u should try to keep it simple.. if u change out the way somethings happening.. remove the uncessary parts
it 'll get too cluttered to read/fix if u dont
what exactly is your question?
setting the webhook url? or actually creating a webhook?
occam's razor 🗣️
Yeah! where would i set/place the webhook?
that's not what occam's razor means
i thought it was simplest answer simplest solution
you didn't actually answer my question
"setting"
yeah, in the face of a problem
you would just assign the webhook url in the inspector, presumably, since you've made it public
so here?
...is that the inspector?
but yes u could do it it there.. but then that defeats the purpose of it being public
arlight, unless there is a way to make it a other setting not costing me a error.
have you never set fields from the inspector before
public field would keep it easy to change w/o loading up the solution but if u wanna keep it internal nothing wrng with assigning it in the class itself
ty
@rocky canyon are you still awake
i get a compile error here
field is not classified or something
do i mind this?
I don't think the field keyword is used that way, unless it's a custom type you've defined
What's the type of discordWebhookURL supposed to be?
Not sure what field is doing in there . . .
a discord webhook which acts like a bot.
which sends like
thus'
a message
for a anticheat
field is here because
Is field a type?
Yeah but I mean that field in specific is going to have a type - whether it's a number or some text or a true/false
Well, the name of the variable has "URL" in it, so I'd guess it's supposed to be a string . . .
This begs the question as to why you put the type as field?
string creates this
@cosmic dagger
What is line 9
Yeah that's not how lines work
You've got the line public string discordWebhookURL; and then a random unattached string that cannot be
Yeah the semicolon means the line ends there - so basically the compiler is reading that you're saying
public string discordWebhookURL;
And then on a new line just you have that string "https...." sitting there, which is not valid
Compare that line to the one below it
You type the line correctly
see im not the greatest at problem solving.
listen, im very dumb at this crap, but its right here probably, or im going to cry in a corner.
😭
I'm confused what relation the screenshot you just sent has to the issue you were having before
Why would you look at that line when I just said to look at the line right below it
What does this line have to do with anything
mhm.
Cool you get it
It might be good to start from first principles - do you know what the equals sign is doing?
Approach 1 is what I would start with. To handle objects being destroyed - that can be done in two ways:
- Enemies fire an event when they die. When you add an enemy to your aggro range, you subscribe to the death event to remove the enemy from your list in case of death
- Each frame, or periodically, you check your list with
== nullwhich will return true for destroyed objects, or you have anisDeadflag on the script which you check.
Approach 2 can also work. Just make sure you use one of the versions of OverlapCircleAll that takes a List so it doesn't allocate a new array each time
Also I would use a HashSet instead of a List for option 1
Ahh that's smart. Yeah I've already got a death event for entities so that would work perfectly
just don't forget to also unsubscribe from the death event in the event handler 😛
So true!
alternatively you dont need to unsubscribe if you just set the delegate to null after invoking it
Does that have a big difference compared to unsubbing? Or is it just cause its shorter code lol
you just dont have to remember to unsubscribe, and it doesnt affect if someone else on the project also doesnt know about this and still tries to unsusbcribe somewhere
My guess is it (setting to null) might be slightly faster but I doubt you would ever notice any performance difference.
i said it more cause it makes more sense logically. you invoke an event that only ever happen once per instance, everything gets notified, then you want everything to "forget" about this event
(Assuming your enemies cannot die more than once)
unity does this with some editor event i forgot which exactly. something delay related
Tbh I'd rather not modify any state at runtime if it can be avoided
(Obviously you have to to some extent but yknow)
what do you consider state to be in this scenario? neither of the suggestions affect if your objects have or modify state
setting a delegate to null is the same outcome as everything unsubscribing
Oh, like if you're keeping a delegate field and you set it to null, that delegate would presumably be mutable state on the object
its mutable anyways, i think you have a misunderstanding of what state really is (or what we mean setting it to null)
why would you have a readonly event?
I don't think readonly events work at all yeah
you have to rewrite the variable when you add a subscriber
Oh wait - when you say "set it to null", you're talking about the event?
I thought since you were referring to a delegate you were talking about the subscriber
yeah the event
this is the first time ive heard of anyone not wanting to modify state in unity, so i assume you got this fear from another aspect of programming (web dev?). Every game object you have will have state, you modify its position
the event is the delegate, event is the keyword used to restrict how a delegate can be used
so yea set the event to null
Okay yeah that makes more sense, didn't realize events were considered delegates (I'm thinking of UnityEvents specifically, never used regular c# events but maybe I should switch over)
yep - event is a modifier for delegates
it means like "only the class that owns me can invoke me or assign me directly"
everyone else can only do += and -=
I'd rather get used to unsubbing, tbh. Setting to null doesn't solve the problem when the listener "dies" first. (Although it may not be a possibility in this case.)
you arent restricted to only setting it to null. other entities can unsubscribe on death with no negative effect
the only thing this changes is entities dont need to unsubscribe when the event is invoked
Why would they need to unsub in that case anyw... ah, because pooling? 🤔
I'd still go with the standard pattern and only deviate if performance requires it.
Yeah, web dev lol
It's not that I don't want to ever mutate state it's just that if there's a option to not do it, seems like a good way to avoid errors in implementation
if you need to modify a value on an object, you are modifying state. this will happen throughout almost every feature in your game. it is not like there is an alternative to "not do it".
a lot of overengineered web dev things just dont apply here
There's often an option to not do it when it comes to internal state for a script, which is mostly what I'm talking about
immutability and performance are often enemies
True, I'll have to reconsider if I run into performance issues. For now though it's pretty performant so I won't really optimize for that
state is still modified here, it doesnt matter if the class itself does it or its done externally. i think you're just talking about restricting access (access modifiers) though right?
Not really haha
When I say "state" I'm just referring to fields on an object that are not readonly, really. As an example, say I want a "fade" function on a script - I could store a stateful value like currentFade or something, and have it increment/decrement on every Update. Or like what I imagine most people would do, I could start a coroutine or async method to loop and fade asynchronously, not mutable fields needed
Sure - just know that a coroutine is itself a state machine. The state is still there, it's just stored on a different object.
I feel that's a bad example. Those are state and the worst kind - one that you don't control 😄
im aware what state is, but the assumption there that state doesnt exist because you use a coroutine is just not right. it still exists even though you dont see it, now its just in the coroutine
and you likely also will store the current coroutine incase you need to stop it. thus more state
But i do get your point about not storing state on the MonoBehaviour in that case
in fact that coroutine case means the state is only stored when running it, otherwise not
I think the main "no state" thing was their option 2 for the colliders - to do an overlap circle when they need then instead of storing state, which is indeed more stateless.
yep
I think it exchanges memory and state handling for worse performance. Which might be a fine tradeoff
I mean I guess you're right depending on how unity implemented coroutines or async/await - but honestly I'd rather have them manage that rather than do it, bespoke, on every monobehavior where that kind of async behavior
I mostly think about it from the perspective of how the code I'm writing is storing state, and even if I can isolate state interactions into one point of failure, that becomes way easier to check for bugs
Like, every script that doesn't define any new, mutable state, is a script that is a lot less prone to local bugs, in theory
I don't think there's anything wrong with your philosophy
in some cases youd also want to consider managing it yourself because starting a coroutine does allocate memory. which ties into what Praetor just said above
Usually i design things around whats easiest to read and extend upon. Like sometimes a coroutine is just easier to use, sometimes update is easier. I never find logic so complex that id even begin to worry about state in the first place
just be ready to profile and optimize where necessary
Yeah 100%, if/when I start to hit performance issues I'll definitely have to reevaluate, but hopefully then I can come at it from the perspective of optimizing the most costly parts of the code rather than generally making everything everywhere optimized for performance and sacrificing some of the other stuff I was talking about
The only performance hit I ever noticed with coroutines was the 1 frame delay before they start. This won't affect framerate, but if coroutine yields on another coroutine which yields another etc. then you'll notice the delay build up
is this still the case even if you do StartCoroutine(Thing());?
dont they run immediately until the first yield?
I personally prefer async over coroutines but they do have their own issues
Yeah I've been using async more, used unity a good amount a few years ago and I just learned async exists in c# like 2 days ago haha
Yes, but if you nest more than one with yield start Coroutine it creates noticeable delays if you have enough of them nested. I was building a turn based framework and in some spots I had a cascade of various coroutine listeners responding to events, and it built up a delay between the player choosing an action and it completing.
async and/or UniTask (which is async under the hood) are both good alternatives
I use UniTask as im still stuck on 2022 but Awaitable seems good too.
Unity thankfully added destroyCancellationToken and a token for application exit which really helps.
Me too!! Wait is UniTask not prefered anymore lol
I think it is because Awaitable is missing some functions such as WhenAll
and UniTask has good extensions for Addressables
im not sure how many you had nested but thats not the behaviour im seeing at all.
if i yield return StartCoroutine(..) it still goes immediately until the first yield, on the same frame
i wouldnt expect that behaviour to depend on how many you had nested either but idk i never really nest coroutines either.
Each layer had a few dozen listeners. The delay immediately went away when I switched the methods to UniTask
I have a very event heavy game, where everything sends out events before, during, and after completion, so that responders can interrupt, modify, or react to the action in question. All necessary to handle the conditional RPG logic
And since it's all turn based, everything waits its turn, and sometimes there's lots of nesting as a listener generates its own events if it's reacting
turn based is already a flex.. i love a good turn-based game loop
even starting 100 coroutines, each from within a previously started coroutine, im not seeing the behaviour you describe.
i tried it on thousands but quickly hit a stack overflow
i assume you were hitting a yield return null at one point unknowingly
Don't know what to say then. The delay was definitely occurring. Actions would end up with multi frame delays during and after execution, and the delays disappeared when I replaced the methods with UniTask without changing any other logic.
But this was half a year ago, so maybe I missed a detail in my explanation
yea im not doubting that your scenario had a delay, was just testing for myself to see if it was true based on yielding a StartCoroutine alone. then trying to replicate it to see if I could get the same result
it's the awaiting that might be problematic... the resume isn't immediate but on next frame perhaps (if the awaited coro finishes on the current frame, after the containing one has been "checked")
(I'm not sure what the exact implementation is though, so that's just a guess)
i would assume thats expected but yea a likely guess
{
transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
}
if (transform.position.x > xRange)
{
transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
}
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);```
When my character moves to the end of the range on the right, it stops and doesnt move any further, but when it moves to the end of the range on the left, it teleports to the end of the range on the right. I'm not sure what in this code is causing that
xRange is a float set to the value of 10
if (transform.position.x < -xRange)
{
transform.position = new Vector3(xRange, transform.position.y, transform.position.z);```
seems pretty clear that's what this code will do
did you mean to put -xRange there in the Vector3 constructor?
yes
really you should just use clamp I'd say:
Vector3 pos = transform.position;
pos.x = Mathf.Clamp(pos.x, -xRange, xRange);
transform.position = pos;```
That can replace both of those if statements entirely
i definitely do prefer single line code to if statements, they make more sense to me
im just not sure whats causing the if statements to loop when reaching the end of the -xRange side when I didnt use a loop statement anywhere..
thank you
Also you should be doing the clamping AFTER you call Translate
what do you mean by loop
sorry im more used to writing python bash and posh
there's certainly no looping happening in this code.
YOu might be getting confused because Update gets run every frame
Update is therefore, sort of implicitly in a loop
Yes I know what a loop is, it doesn't mean something different in Python than it does in C#
this code simply doesn't have one
thats why i was confused
so I'm not sure what you mean when you say "the if statements loop"
u may need an else - if statement instead of 2 ifs..
not sure thats an issue here or not
but the clamp is better potion
The issue is with these two lines that praetor pointed out - you're checking if the x position is less than -xRange, but then setting the x position to xRange, so you're presumably making a big jump from position.x near -xRange to xRange. It looks like it's looping cause you're setting the position to the right boundary xRange upon hitting the left boundary -xRange
note this isn't a "loop" in the code, just a "loop" of the object's position.
Only one thing is happening each frame
So the code is interpreting moving the object once it hits the less than value of -xRange then instead of stopping, the next statement is causing it to jump to the top of the greater than xRange in this case, once the character position value hits -10, it jumps to 10?
yes, that's what your code says to do
so that's what happens
"if position is less than -10, set position to +10"
the object looping is what i meant earlier
Thank you for your help
the Clamp line works better and its easier for me to interpret
im super confused if the code from the picture is using unity's new input system, because it looks super different from the input system tutorials i found on youtube, or is it just a newer version of the input system??? this code is from unity's third person starter asset package, and im using unity 6
None of this code is specifically related to input or input system. It's where it is called that might be related.
Also, there are many different ways to use the input system. I image subscribing some methods to the input events is one of them. The first 3 methods look like they might be doing just that.
yeah but this is the only input related code in the whole code
using UnityEngine;
using UnityEngine.InputSystem;
public class CharacterInput : MonoBehaviour
{
[Header("Character Input Values")]
public Vector2 move;
public Vector2 look;
public bool jump;
public bool sprint;
[Header("Movement Settings")]
public bool analogMovement;
[Header("Mouse Cursor Settings")]
public bool cursorLocked = true;
public bool cursorInputForLook = true;
#if ENABLE_INPUT_SYSTEM
public void OnMove(InputValue value)
{
MoveInput(value.Get<Vector2>());
}
public void OnLook(InputValue value)
{
if (cursorInputForLook)
{
LookInput(value.Get<Vector2>());
}
}
public void OnJump(InputValue value)
{
JumpInput(value.isPressed);
}
public void OnSprint(InputValue value)
{
SprintInput(value.isPressed);
}
#endif
public void MoveInput(Vector2 newMoveDirection)
{
move = newMoveDirection;
}
public void LookInput(Vector2 newLookDirection)
{
look = newLookDirection;
}
public void JumpInput(bool newJumpState)
{
jump = newJumpState;
}
public void SprintInput(bool newSprintState)
{
sprint = newSprintState;
}
private void OnApplicationFocus(bool hasFocus)
{
SetCursorState(cursorLocked);
}
private void SetCursorState(bool newState)
{
Cursor.lockState = newState ? CursorLockMode.Locked : CursorLockMode.None;
}
}
this is connected to the movement code
and it just references this code for anything input related
so is this code using the new input system?
or is there a new input system for unity 6
cus its kinda confusing
Likely yes. Try finding references of these methods..
Oh, I see they have 0 references. They are likely referenced in the inspector though.
Look around where this component is and see if there are any other components that might be referencing it and using these methods as callbacks.
no, it's just old system (input manager) and new system (input system)
the default was changed in unity 6
so the input system from unity 6 is the same as ones from previous versions right?
yeah
can anyone please help me with some code, im making my first ever game and am heavily stuck 😭
Ask the question here and people can help...
why doesn't this destroy the bullet
i am trying to walk up to a cube and press "f" for example and then i will teleport from one cube to the other.
i think those if statements have to be in the update method
but i cant refrence BulletIns if i put them in the update method
then add the new bullet to a List and loop through that in Update to check this condition
This is basic c# knowledge so you may need to learn the basics
what
Create new bullet, add to list, loop over list in Update () to do your destroy check.
Same way you already are, instantiate. A list is an expanding collection.
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/list-collection
You need to re visit the basics of c#. You make a new instance of list (as a class member) and use .Add() later to insert a new element.
is there a different way to approach this other than lists
ok i added BulletIns to the list
so basically something like this?
this doesn't work idk why
Define "doesn't work"
Also, you never remove the deleted bullets from the list
At least in the code fragment you shared
First configure your !ide before receiving help.
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
so basically, this code is supposed to delete the bullets when they go offscreen
and it doesn't
when i play the game i get this error
What line is this?
I suppose it's the list
Please provide the full error
in the unity console
Which line. Everyone know that it's in the console
You need to check what line this fails on. The error indicates this, including the faulthy file. From there it's clear what goes wrong
And what is line 30?
wait
And which line is line 30, you cut it out of the screenshot.
You left out the lines from your screen shot
Yeah, the list
Okay, so the list has never been created
If this is intentional, wrap it in a null check. If not, make the list
It would really help if you shared all your !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/
📃 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 List is a reference type, you have to assign a value to it
then how do i create it
List<GameObject> BulletList = new();
oh ok
If you want to default to an empty list, create the list.
- List<GameObject> BulletList;
+ List<GameObject> BulletList = new List<GameObject>();
For future reference I strongly suggest you enable nullabillity context
https://stackoverflow.com/a/78598918
If you do this, it will be clear what parts might be null in your code
yeah, i cant understand what this does exactly
Hard to explain. You can find a .csproj in your current project which has this as well (and much more)
Basically you can't modify it because Unity keeps replacing your additions so the props file explained in that post is an alternative
its like a configuration file for your project...
It should automatically adjust your csproj file with this, but I have heard it might not work properly
hey man as long as the code works i am happy
Remove the TargetFramework part if you do plan on adding this
Pretty sure LangVersion can also be bumped to 13, which gives more language features
i dont wanna add stuff i dont understand
Then ask
pretty sure imma come across this again when i am an expert
This is very basic stuff. It's jsut that Unity doesn't add this yet. Modern .NET does add this to projects by default
Alrighty
Changing this in the cs project is not gonna do anything. Unity doesn't compile your code with the visual studio toolchain.
At best it's gonna create compile errors, since it's compiler doesn't support these features.
Lame
In that case you can also add the #nullable enable directive on top of files to enable it. Would be nice if it could just be enforced globally
it is possible to increase the language version, but you only get access to the syntax sugar stuff. anything that actually relies on stuff added in newer .net versions won't work
How does that work? Wouldn't the compiler spew errors, since it doesn't know about this syntax?
I wonder if you could add PolySharp to support some of these features
yeah that could probably work for some of them
i think if it can get dumbed down during compilation to stuff that already exists its fine but if its a brand new concept it doesnt know how to handle it?
Syntactic sugar is downgraded to the old syntax whilst lowering the code. As long as there are no special features this likely works for a lof of things
Like file-scoped namespaces just have their blocks readded during lowering.
this is what i've come across to help with the process https://github.com/DaZombieKiller/UnityRoslynUpdater
But who/what is gonna dumb it down?
gotta update the roslyn compiler to support it
So mess with unity compiler toolchain?
You know the C# compiler does multiple steps during complication. One of these is lowering the code to a more general syntax
All the nerds having their fun with nullables while i wait to use statics in interfaces
Sure, but of the compiler doesn't know about the feature at all, it wouldn't know that this needs to be simplified.
See this example: https://sharplab.io/#v2:D4AQTAjAsAULB2BDAtgUwM4AdEGNUAIAxAe2IG5ZYQBmfcfAYXwG9Z9382Ob8BLeAC74AQogBOLfAHNUAsvnSz5AXy7s1dWiAAs+ALIAKAJQsNqmMqA=
- File-scoped namespaces adjust and have their blocks readded.
- Properties get expanded and have a backing field added
Stuff like this happen in that process
This is based on language version, not necessarily what version of .NET you use
I assume this is related to your compiler being up to date and knowing the feature
Ok, that makes sense, but it's basically engine modification:
NOTE: This will modify your Unity installation folder, administrative privileges are required
The compiler is provided by unity. It's not really "yours".
not sure if im wrong but i dont think you need to go that far?
last time i was messing with it the changes we're limited to just project
https://www.reddit.com/r/Unity3D/comments/13ke5ev/any_way_to_switch_c_from_version_9_to_10/
So Unity can provide a newer compiler
I wonder how much Unity does in terms of compilation, though. Is this part of an installed version? Does it even provide one?
The extension will insert Analzyer element into .csproj when generating the project file. As a result, you can run Roslyn Analyzer when editing code in Visual Studio. (of course, you can use it before 2020.2!)
i seee
Indeed. But they don't. That's the whole point.😅
All of it.
this is because in (at least) 2022+ unity apparently embeds the .net 6 sdk. updating the roslyn compiler is necessary for language versions higher than the 11 preview
https://github.com/Cysharp/ZLogger?tab=readme-ov-file#unity
It might rely on third party stuff(like for il2cpp), but it relies on a very specific version of it presumably.
oh shit i did not know c# 13 let lists and ienumerables go into param[]'s. that would be cool to have
need those static extensions too
I also wonder how acceptable it is to upgrade the compiler from the perspective of the terms of service.
At the very least they would probably decline support for such projects. If they can detect it somehow.
Always curious how much certain studios stick by terms of service
I went to a cool talk where a studio was using Harmony in editor to do some cool stuff with assembly injection for workflow and quality of life
Like some cool setup that was able to link specific assets and in-scene objects to jira tickets and shit
probably not tos-friendly
Yeah. Unity is kinda shitty in this regard. I really like how unreal basically gives you the source code and let's you do whatever you want with it. As long as you're not trying to compete with them.
right
Can't go into it too much but a friend was showing me how to tip toes into the c++ side of things and im really curious to mess with that purely just to know whats going on behind the scenes with a couple things
made an enemy and gave it a boxcollider2D, i want the bullet to destroy the enemy upon impact, but this code doesn't work for some reason
Don't use the name to check what object it is. Give the bullets a tag and compare the tag
Start debugging it. Add a Debug.Log and print the name of the object you entered
something like this?
You didn't need to delete the existing code but yes
it doesn't show anything in the console
my console is filled with wakatime things
Go through this troubleshooting guide: https://unity.huh.how/physics-messages
Thx it works now
this is really helpful
OnInteract is not being called
Inputmanager:
using System;
using UnityEngine;
public class InputManager : MonoBehaviour
{
private InputActions inputActions;
public event Action OnInteractEvent;
void Awake()
{
inputActions = new InputActions();
inputActions.Player.Enable();
inputActions.Player.Interact.performed += ctx => OnInteractEvent?.Invoke();
}
public Vector2 GetMoveInputNormalized()
{
Vector2 moveInput = inputActions.Player.Move.ReadValue<Vector2>();
return moveInput.normalized;
}
}
player.cs:
void Awake()
{
inputManager.OnInteractEvent += OnInteract;
}
void Update()
{
Vector2 moveInput = inputManager.GetMoveInputNormalized();
Vector3 moveDir = new Vector3(moveInput.x, 0f, moveInput.y);
HandleMovement(moveDir);
HandleAnimation(moveDir);
HandleInteractions(moveDir);
}
public void OnInteract()
{
if (selectedCounterScript)
{
selectedCounterScript.Interact();
}
}
my player is going inside the counter when trying to enter from the corners
player.cs
private bool IsCollision(Vector3 moveDir, float moveDistance)
{
return Physics.CapsuleCast(transform.position, transform.position + Vector3.up * 2f, playerRadius, moveDir, moveDistance + 0.1f);
}
private void HandleMovement(Vector3 moveDir)
{
float moveDistance = moveSpeed * Time.deltaTime;
bool isCollision = IsCollision(moveDir, moveDistance);
if (isCollision)
{
Vector3 moveDirX = moveDir.x * Vector3.right;
bool isCollisionX = IsCollision(moveDirX, moveDistance);
if (isCollisionX)
{
Vector3 moveDirZ = moveDir.z * Vector3.forward;
bool isCollisionZ = IsCollision(moveDirZ, moveDistance);
if (!isCollisionZ)
{
moveDir = moveDirZ.normalized;
}
}
else
{
moveDir = moveDirX.normalized;
}
}
float rotateInterpolation = 5f * Time.deltaTime;
transform.forward = Vector3.Slerp(transform.forward, moveDir, rotateInterpolation);
transform.position += moveDistance * moveDir;
}
is it possible to check if an dictonary contains a key that was pressed???
which dictonary
like an dictonary that contains keycodes as the first parameter
just add debug.log
Sure, check which key was pressed and then check if it's in the dictionary
you mean to cheak if the key pressed is in the defined in inputmanager or not
howww
do i check which key was pressed
ask chatgpt
thats a basic thing
use a input manager ( new unity input system )
or do Input.getKey("keycodee")
but i want to get any key that is in a dictonary
so i cant do it this way
they cheak if its included in the dictionary after that
you have to
for sure there are other ways
use switch case get the key pressed (any key) then put in switch case and run each case
You can always just iterate over every key in the dictionary and check Input.GetKeyDown(key);
if keyPresed is in dictionary
someone
it should go to either x or z
why is it going inside the cube
@vital zodiac Please stop spamming, if you have something to say, send it in a single message.
i did
I'm talking about your later messages.
foreach(KeyCode key in keyDict.Keys) {
if (Input.GetKeyDown(key)) {
// Do something
}
}```
wouldnt it be laggy in the update function???
wait it probbably wouldnt
Try it and see
depends how many keys i have
if (Input.anyKeyDown)
That wouldn't check if the key pressed is in the dictionary.
It would just return true if any key is pressed.
why exactly do you need a dictionary of keys?
void Update()
{
if (Input.anyKeyDown)
{
foreach (KeyCode key in System.Enum.GetValues(typeof(KeyCode)))
{
if (Input.getKeyDown(key) in keyDict.Keys)
{
Debug.Log("Key pressed: " + key);
break;
}
}
}
}
Once again, it doesn't check if the key is in the dictionary.
just add that condition
now fine
what problem is being solved by looping over an entire dictionary? when Input.GetKey is able to tell you when a certain key is pressed
its not every single key
first we get if any key is pressed or not then do the processing
it will be faster
You're still iterating over every single possible key, what don't you understand?
why u want to cheak if the key exist in dictinary
im driving crazy. my buttons doesnt work in world space
it will definately exist
What if he wants to add only 5 keys to the dictionary? Do you have any clue how many keys there are?
A lot of them are not even related to the keyboard
This sounds more like a UI bug rather than code, no? It would help if you shared some context.
If you're going to do this then I suggest you migrate to the new input system and iterate Keyboard.current. What you are doing is horribly inefficient and I highly suggest against it.
Pretty sure it also has this build in so you don't need to do all this
Here it is, it has events for you: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Actions.html#started-performed-and-canceled-callbacks
there wont be any performance difference
this code is pretty bad, ngl
every frame you'll check if "literally any key is pressed", so for most games that will be almost always happening
then you loop over a dictionary, but unless the dictionary contains every single key that can be pressed, it will be wasteful (imagine the letter G is never used in the game, but I decide to hold G down)
but also each iteration in the loop, youre doing an if statement to check if a certain key is pressed (first if condition already establishes that a key is pressed, a second check is pointless) and if it happens to be in the dictionary you return early, just hope that the user isnt pressing the key thats the last one in the dictionary
its probably like 0.4ms process
i generate buttons from an Prefab, this seems to work perfectly fine, they are shown. but when i try to click them, nothing happens. i made a new canvas in world render with a single button and i cant click this aswell. im trying so much rn but idk i cant get it to work
its "if literally any key is pressed, check every item in the dictionary, but lets check again if the user is pressing a key, and if they are pressing a key is that key in the dictionary"
Still a lot more than it should take for such an easy task.
You're overcomplicating it
Sounds like they are not part of the correct canvas? Do you have an EventSystem in your scene?
This is better asked in #📲┃ui-ux
whats the reason why you want to do this dictionary lookup thing?
^ It was him who wanted to do this
This whole thing is probably just an XY problem anyway and it is getting snowballed into poor solutions even though it could be fixed a different way
sounds like pre-optimisation "I might in the future have more keys" type thing
if you dont actually have many keys right now, dont try and fix a problem that does not exist right now
Why do you want this? Why are keys in a dictionary?
By all means not a bad thing, but definitely something that might have a better solution
if you do want to use a dictionary for this, you could do https://stackoverflow.com/questions/7247235/dictionary-search-with-linq
linq is a very powerful thing
First of all, why not use Unity's physics system to handle collisions?
lots of strange things in the code
Vector3 moveDirX = moveDir.x * Vector3.right```
We don't know what moveDir is, but I assume it's x for left/right and y for up/down? Why are you multiplying it by Vector3.right? Vector3.right is (1,0,0) so you are multiplying by 1 which doesn't do anything. Same with moveDir.z * Vector3.forward
The reason for your problem is probably that you are checking for a Z collision inside your If statement for the X Collision.
the amount of messy and overly long if statements and for loops that often take multiple lines, can often be shortened down to a single linq method
We don't know what moveDir is, but I assume it's x for left/right and y for up/down? = yes its comming from the inputManager (new)
Why are you multiplying it by Vector3.right? Vector3.right is (1,0,0) so you are multiplying by 1 which doesn't do anything. Same with moveDir.z * Vector3.forward = i am actually throwing ray to both x and y for not making the charectes stop when the collison is happend, for example if the moveDir is 0.71 at x and y it will not move toward x because of rayhit so i am doing that to make that happen
and i have figured the issue just now
Actually at the corner both the x and z ray are hit. and this condition is not in the code, causing it to just continue to move in the movedir
i prefented that but adding that and doing return from the function
but this is faster than the physics collider
what is faster?
I was saying linq could be a cleaner way to check a dictionary to see if the current key pressed exists in the dictionary
oh i thought u were talking about my code
I hadnt totally worked out what was going wrong in the code you posted earlier
I get the sense of what its doing
Not in Unity, what you suggest just makes it worse
linq is at a disadvantage when used with unity?
If they do a normal iteration without LINQ it will be a lot better than using LINQ with it. It's still bad, but at least not much slower
LINQ is not optimized in Unity. Modern .NET has done significant work on improving it, making it nearly on part with manual implementations and even much faster in most cases.
its fine for one offs and quick and dirty things but yeah do not use linq in things happening every frame
also there is nothing linq can do that you just cant do with some loops
ah, I thought there wasnt much of an issue with its performance
I would say that, unless you start chaining lots of things together, the readability at least provides some benefit
also its main issue is not speed but allocations and garbage
doing things manually allocations become very obvious and easy to just reuse things or use stuff like pooled collections to avoid them
but yeah i will totally use it in like startup logic or things that happen rarely
Speed definitely also plays a part. Modern .NET does something with hardware accelleration to an extend, which goes beyond my knowledge, and it is definitely a lot faster.
For one off actions it's very good, also if you only call simple methods. When it's more often or bigger you might want to reconsider it for now
thing is speed is still a relative thing, I'd be certain their original nested if statement where its is any key pressed, foreach the dictionary, check again if a key is pressed and compare it to the current item would be far less optimal than the simplified linq version
its just that the linq version would be less optimal than writing the original block in a way that sucks less
the linq at least (in theory) allows them to simplify things down into a way "that just works"
using the actual input system is really the best option, not any kind of check like that what theyre doing
If they cache Enum.GetValues(typeof(KeyCode)) then it is nanosecond work
hello. lampMaterial.SetFloat("_EmissiveIntensity", 0); its why not work correctly? im change the emissive intensity but its changed only the inspector, the graphics not modified
So speed really doesn't matter here, it's the fact they are doing something obscure when they could just use the new input system and do it properly
Only Enum.GetValues(typeof(KeyCode)) is bad because in older .NET it would do a lot under the hood, which doesn't change with the next iteration so it should be cached.
I'd like to know what the dictionary is for in the first place, what the key-value-pair is in it
I asked, no response
It has nothing to do with keys, though. I assume it's a later feature being added.
I mean regardless, iterating the dictionary is not bad either. Enumerations are incredibly fast
I feel like this conversation is base don a lot of assumptions that the logic is slow when it's not. It's just being made slow with a lot of excessively complex logic
not directly, but it looks like it would be used where you press "the give money key", which could find the givemoney item and as a result you get the action used to call GiveMoney()
just imagine pressing E tells some method that it should give it the string givemoney
the new input system is designed to automate this kind of thing
just tell it what keys are able to be used to do a certain thing
That's why I initially said to just use the new system for anything that doesn't require basic input checking
yeah, i saw them say they didnt want to use it
I'd guess that might be because their current code is only designed to work with their specific approach
hey, someone knows why my sounds have echo? sounds robotic and with echo wich is creepy, is when the states with sound are called
{
animator.Play("Base Layer.MortemRifleSight");
audioSource.PlayOneShot(troopersight);
detectoValeria = true;
delay -= Time.deltaTime;
if (delay <= 0)
{
delay = 0.2f;
currentState = MortemState.Chase;
}
}```
You're playing the sound many times
You should play it only when you first transition to the state, not every FixedUpdate
I would adjust your structure here so that instead of directly setting the currentState variable, you call a function that handles enter/exit events for the states too
ah nice thanks, i already did it
how?...
i recently turned an if and else AI into a enum statemachine one ;-;
all the methods i found did multiple actors for one object and i found that slighty confusing for me, so i rather to nah just use this
can I ask questions in this channel
because I have a problem with a coroutine that stops playing after a yield return null and it is not because the gameobject is desactivated or the monobehavior disabled
Debug.Log("delay");
yield return null;
Debug.Log("delay2");
the delay message is shown but the delay2 message isn t
and the console shows no error
Do you stop all coroutines or this coroutine on the mono? the only reason it would stop is if you stopped it, things were disabled or there was an exception.
If the mono/gameobject was destroyed that would also explain it.
Try logging Debug.Log("delay", this); and click the log message. Verify the game objects exists
A coroutine does not stop unless explicitly stopped or the game object is gone, so let's verify it truly still exists
Otherwise look for StopCoroutine calls in your code
I have tracked with events if the mono was disabled or destroyed and no where in my code i have a stop all coroutines
Is the game object disabled?
no
Sorry, you already mentioned this
that s why i can t figure it out
I assume this yield is the first instance of a yield appearing?
Can you post the full thing maybe?
no I also have a
yield return new WaitForSeconds(typingSpeed)
that has no problem
here s the full Ienum
public IEnumerator TransitionScenetoScene()
{
Debug.Log("defaultstate1");
sceneset.DefaultState();
dialoguemanager.indialogue = false;
avancee.canselect = true;
dialoguemanager.stage = 0;
DialogueBox.SetActive(false);
foreach (Transform child in ChoicesNAvancee.transform)
{
GameObject.Destroy(child.gameObject);
}
foreach (Transform child in IntantiatedObjects.transform)
{
GameObject.Destroy(child.gameObject);
}
Debug.Log("delay");
yield return null;
Debug.Log("delay2");
sceneset.LoadNextScene();
}
You are positive you don't accidentally destroy the game object this coroutine is called on? Can you try the log?
Another reason could be that you use Invoke. Is this something you use?
I'd triple check the game object is not destroyed, nor disabled, with this log. Lastly also check for Invoke and if you do use it, double check the length added is a valid number, and not NaN. This can silently break coroutines.
the Debug.Log("delay", this); shows that the gameobject still exists
If something Invoked it stops the coroutines ? even in others scripts ?
every Invoke in my project have a 1f parameter
I'm struggling to design a system for storing types of projectiles. I can't quite get the balance of Behaviors vs ScriptableObjects right.
Every projectile has a set of data associated with it (sprite, weight, damage, speed, etc). I feel like this is a good candidate for ScriptableObject data.
But then we also have a set of behaviors associated. For instance, one projectile might have an "explode on hit" behavior, or a "poison on hit".
Ideally I would love to define these behaviors as a configurable item in the interface. I want to create an instance of ExplodeOnHitBehavior, set its Radius, and then attach it to a ExplodingProjectileData as one of its behaviors.
I'm having issues with being able to drag/drop scripts, or knowing which ones to make behaviors vs scriptableobjects.. it feels like I'm fighting the separation of data and behavior here.
Are there any references for how folks have put together systems like this before?
If I can't figure this out, the caveman approach in my head is just to define a series of projectiles as MonoBehaviors and hardcode everything - no reusability, just reimplementing OnHit functionality in each of them.
https://github.com/mackysoft/Unity-SerializeReferenceExtensions
this is probably what you want. You can create your OnHitEffects as a normal C# class and then add a List of them to your SO.
[System.Serializable]
public abstract class OnHitEffect
{
public int radius
}
public class PoisonEffect : OnHitEffect
{
public int duration;
}
```Then you can add them in the inspector and assign the fields there
Why not make each projectile a prefab with whatever it needs?
My goal was to sort of rip out behavior into reusable modules
So, sub-prefabs perhaps?
So, one behaviour is one prefab, it can have whatever it wants (more than one Mono), but you can drag and drop it as part of another prefab and it'll add the behaviour
Mmmmh... that might be the play.
I feel like ScriptableObjects don't have a place here then
SOs tend to be good if you just vary data (and maybe a tiny bit of behaviour... non-extensivle behaviour, perhaps 🤔)
I believe these behaviors are going to hold state and component references too, which also further pushes me away from SOs
Like, having 50 of the same thing with different params, where you would only want to modify the params to distinguish the things, and you don't need to customize the thing that uses them
so we might have..
public class PoisonOnHitBehavior: MonoBehavior, IOnHitBehavior
{
public void OnHit(ProjectileController p, GameObject o)
{
if (o.TryGetComponant<EnemeyController>()..)
StartCoroutine(PoisonEnemey(enemy));
}
}
Something like that.
So I could see each projectile being a prefab, assigned a series of these behaviors, and then instantiating them when we spawn the projectile and letting it rip as it hits enemies.
They'd be part of the projectile prefab, so they'll be instantiated with it... but yeah, that's the general idea. 🙂
Got it. It makes sense, I think I got lost in the sauce thinking SOs were a good fit here, but not so much. Need to re-review their use cases.
Thank you c:
i gonna start with a use case, this function will only be called when player join other rooms, so its really once in a while
lets say player will open X amount of UIs, it would be many, >=1 or >1, without recording/storing reference of the opened UIs, can u accept using GetComponentsInParent or GetComponents to turn off all existing UIs?
an alternative would be reloading the scene, such that every UI will be dropped
You're worried about an efficiency of using GetComponent... calls when closing all UI panels? If you're just finding them all one time, then closing them, it shouldn't really be a problem. Especially if the only other option you are considering is reloading the scene, which will take forever relative to the GetComponent idea.
This doesn't sound like the best way to handle this system, but it should work.
Re loading a scene to "reset it" quickly becomes a shit solution
all method that i can think of do have some drawbacks
- find them all at once and destroy them in loop
public void CloseAllUI()
{
ICommonUIFunctions[] allAssociatedUIs = FindObjectsByType<MonoBehaviour>
(FindObjectsInactive.Exclude,FindObjectsSortMode.None)
.OfType<ICommonUIFunctions>()
.ToArray();
foreach (ICommonUIFunctions element in allAssociatedUIs)
{
Destroy(gameObject);
}
}```
2. reload the scene only to drop all the UIs (switching session in my game does not require reload scene)
3. have a dynamic list where u update it in realtime, if u spawn one UI then add it to the list, if u destroy the UI then delete it on list
2 is overkill, and too unnecessary
3 gonna make the code scatter everywhere
thats why i chose 1
even if i find "all monobehaviors", if its only once in a while, then it will definitely less expensive than reloading a whole scene right?
Why not track the things that can be closed later in 1 place when you open them...
e.g. central script for opening UI popups/dialogs/modals that tracks what it opens so you can close things later
okay so i got a new xbox controller and set it up on unity. made sure all the code should be correct but i still can only get my character moving one direction and not controlled with the xbox controller. Any thoughts?
you should probably show code if you post in a code channel..
thats 3 + a singleton manager
I agree with rob. 3 is probably the best bet. It will take some work, but will give you actual control of what is going on instead of just brute forcing stuff.
actually i planned all 3 implementation already
don't post code like this its unlegible mess, use links provided in !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/
📃 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.
if the loc of ur code is >50 i think u better use some external pastebin sites
never used one before but thank you i willl
plz delete ur code wall first😭
i thought of 3 before, but imagine i need to create a list and a manager . Plus i need to update the list frequently just for turning off UIs
but if thats the best bet i will go for it , ty👍
Games I work on where I work have a central "Root UI" that you can open, close and get dialogs from.
dialogs get opened with a provided addressable address (to load the prefab asset) and can be retrieved later with their unique string ID
where is exactly the part that controls any directional movement ? I only see animator stuff
Would that not be in a seperate play input script?
where is the part that actually moves the player ?
i dont have a root UI, all of my UIs are free
All that means for my example is 1 controlled parent to spawn them all in
sorry im a bit confused shouldnt the player input for the controls be another script and being referenced in this current one?
i think an UI manager suits me better, if i want to implement "going back" instead of closing them all at once i can build on top of it either
what do you mean? I only see stuff in animator, whats pushing the character forward in the video ?
ty
could i send the vid to you?
send it the same way as you did b4
Ofc do what suits your situation best. I presume if they get opened in a central place it makes it easy to use a Stack to close them in reverse order later.
Learn to move characters in Unity 3D with this beginner-friendly explanation of Unity's new input system and root motion!
With this deep dive tutorial, you will not only have a better understanding of root motion and Unity's new input system, but you will also have an animated character by the end of the video!
SUPPORT THE CHANNEL:
💛 http...
so you are using root motion / animator to drive the transform ?
i am unsure on the second one
the xbox controller seems to respond to the game when i press forward left stick so maybe I missed something that doesnt give me full control. or i didnt add something correctly
and yes i am using root motion
yes sounds like you maybe messed up 2D vector composite it animator maybe
where could i check?
wait did you watch the rest of the video ?
he adds rotation right after the part you sent
HandleRotation()
Oh if its on the charactermovement then i did not. But i mostly follow tutorial as he goes, so i thought it would work the same
well it does work the same if you had not stopped before the part he adds rotation lol
the timestamp you sent his also just moves forward only
ah, my bad. Well i will look over it again fully
15:00 min starts the rotation part
Yes, I feel silly about that sorry
no worries
Thank you I got it
IT WORKED😭 😭 😭
now im using an UI manager to record/track all opened UIs, and turn them all off using this
public void CloseAllUI()
{
foreach (GameObject element in AllActiveUIs)
{
Destroy(element);
}
}```
was planned to use a stack but its way too vulnerable
i gonna use functions to simulate stack instead
if u dont know what i mean
heres two UI , lets call the big one A and small one B
if i opened A and then someone send me a request (B)
stack will be populated as {A,B} right
if u gonna pop(remove) element, ur forced to start from B(smaller UI)
if i put all of them into stack, there will be error if i close A first right?
and theres no way u gonna force users to deal with join request first
sure, which is why I don't see that this particular UI lends itself to a stack structure
but maybe I don't understand it
you wouldn't have those on the same stack, they don't have dependencies on each other
they aren't nested menus
maybe an extra list then?
A stack would be for like modals, or for a tree-style menu
@nimble apex perhaps take a step back and think about how you're thinking about the problem
you're thinking "how do i make these 2 things work with a stack", which is the wrong direction to go
figure out what you want to do, then how to do it - not the method, then the behaviour
you should instead consider what relation those 2 have, and how you would implement that - once you go from that direction, it should be clearer that a stack doesn't fit into that relationship at all
okay i got this working but i am having a bit issue having them slow down. Is there a thing i missed so it doesnt move back into a slow to stopped animation. I did have a idle one within walking and running animation. @rich adder
I used a blend tree a few times, but i dont think that is needed if i just want them to slow down and stop on command
can you clear up on what you mean by "so it doesnt move back into a slow to stopped animation"
I don't see whats happening in the video tbh
So I am trying to slow them down with left trigger or even just stop moving the joy stick but they just keep moving. The model is still under the command of the controller but I don’t know what I did wrong to only keep them running.
In the animation state it goes from idle > walking > running with true and false booleans for both
can you make a video showing the animator + transitions again while in playmode, also transitions inspector
I cant see what are the values of the paraemeters in the animator through video you have Layers selected instead :\
also I'd probably rewrite this though.
animator.SetBool(isWalkingHash, movementPressed);
animator.SetBool(isRunningHash, runPressed);```
or better yet, use blend tree
blend tree would be good but i rather just add some commands still
the parameters just are what i see right here, because its just true or false boolean.
rewrite to what?
I know but you have to observe what happens at runtime when you let go of key while running
I still dont see where that is even while in play mode
wdym where it is ? its exactly where you showed screenshot of, you just need to look at it during playmode to see what the bool values are doing
oh well the iswalking bool keeps cutting out at times i did notice that?
I mean i guess i am confused still if it supposed to bring up a number or something?
bring up a number? no idea what you mean.
I'd check the video and see if everything was setup the same
Yeah me either, I am still learning everything I can.
if ((!movementPressed || !runPressed) && !isRunning)
{
animator.SetBool(isRunningHash, false);
}```
should be
```cs
if ((!movementPressed || !runPressed) && isRunning)
{
animator.SetBool(isRunningHash, false);
}```
thats why i mentioned to check carefully how you copied video
tbh these if statements just seem so unecessary..
wow that worked, yeah I just keep missing those small details
generally is a good idea to watch the video a couple of times before copying it yourself, you pay less attention when you are just copying info as it comes while you are learning new things all at same time
That is a good point, Ill start doing that. The thing is i feel like i don't retain unless i am doing something but i rather not miss simple code
hi, i'm making a dialogue system for my game and im currently stuck on how to make text effects. i've made a tag reader that detects text in a tag and adds it to an fx text list.
so for example if a character was saying "this is <w>super cool wavy<w> text!" the fx text would be "super cool wavy". im just stuck on how to actually apply these text effects onto the dialogue box?
my typer/tag reader script
https://paste.mod.gg/zimvffpdivko/0
dialogueui script:
https://paste.mod.gg/czwtamdlocip/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
Id just use a ready made package such as this: https://github.com/Luca3317/TMPEffects
You can modify the tmp mesh after its made so that is how you would do your own effects like this
there is an event you can sub to react and modify the mesh each time it changes
some of the tweening librarys can do tmpro stuf too
Save yourself the headache and get
https://assetstore.unity.com/packages/tools/gui/text-animator-for-unity-254677
🏆 winner!
lol.. as someone thats made a typewriter script ^ id def buy that if i were doing text stuff (or anything heavily dialog based)
I've done my own "reveal text typewriter" thing before and its not that hard
anyway plenty of options available, free or paid
Hey, I have a button which on click instantiates a preview of a building it will create on left click. on trigger enter of another collider it'll set the preview to invalid, but if I have a building behind the button, when the preview is instantiated it'll infinitely trigger ontriggerenter until I move the cursor which breaks my validate check. is there a way to stop that?
what trigger is it hitting
another previously placed building
This is kind of a game design/logic problem than a specifically code one
What do you want to happen in this situation?
In any case infinitly triggering OnTriggerEnter doesn't sound correct. Are you sure that's what's happening? Is the collider moving out/in into collision?
OnTriggerEnter is incrementing an int which is tracking how many "obstacles" the preview is over, so it's incrementing a bunch until I move the cursor
OnTriggerEnter in theory should only run once per time a collider "enters" the trigger collider. if the preview building isn't constantly exiting and entering the collider that shouldn't be ticking up
OnTriggerStay is what constantly invokes if a collider is inside the trigger
I added a debug log to on trigger enter and once I click the button to instantiate the building preview, as long as I don't move the cursor and there's a building already behind the button it'll keep triggering ontriggerenter
Can you record a video showing what's happening?
Ideally with the inspector, hierarchy and the console visible as well.
does this help?
edit: oh the cursor didn't record, when the log fills up I'm just leaving the cursor still after clicking the button
How exactly are you switching between the preview and the red building?
Can you share the relevant code?
Could be. Try adding logs there as well and see if they print every frame as well.
Still not clear how you switch between the cyan and red preview. Are these different objects? Or just changing some material property?
Oh i'm just changing the material when SetPlacementMode is called
it is being called every frame but it looks to be acting as expected. and I can't find any other reason why the preview would be being set active
After messing around I noticed it is being set active properly (I removed a line making it active when it shouldn't have), but ontriggerenter still triggers a few times when the cursor leaves the button
Try logging this and the other object names on trigger enter and exit.
It's kinda working most of the time now... Might just need to do some digging
It's harder to break it now 😅 I'll keep those logs on in case it happens again, thanks for the help!
How do y'all generally organize your player input controls when using the new input system? Do you keep all the actions related to the same Action map in the same player controls script or do you separate the actions into different scripts based on the feature? I understand it's probably one of those "how ever you want to do it" but for now I'd rather just do what the majority of people do lol.
For example, I have a pretty basic player controls script but am starting to add complexity by adding an Inventory action. Should I enable/disable the inventory action in the inventorymanager and then just reference the playerinputactions? Utimately causing some actions to be handled by some scripts and some others? Maybe down the road I'll just have a movement scripts, inventory script, combat, etc?
guys how do I get the velocity of a Rigidbody
this discord isn't exactly substitute for things that are easily googleable
try typing it into google exactly like that and you will get your answer
CustomInputClass -> PlayerInputHandler -> ScriptWithAction (used with methods)
PlayerInputHandler will talk to all the scripts, that need input from player.. They don't directly know anything about Inputs.
eg a Movement script has a Move(Vector2 input) method that accepts a vector2 , it doesn't care where the input comes from.. it can be Player Controlled or like EnemyAI can be moved with a Simulated input by AI
Hi i just made a multiplayer game and it works locally, how to buy it a server?
you need a vps or use something like Relay/Lobby or unity dedicated servers
I really dont understand it, but i saw the dedicated server package should i install it
you don't understand it? why exactly are you working with networking if you don't know / lookup anything I mentioned
Just thought it would be neat like i know its out of my league but come on its fucking cool why not???
Like C# yeah im getting the hang of it so just got excited thats all
its cool but the skill threshold for this is very high and your skill level is pretty low (not to be taken as offense) without the experience, mentioning anything would be kinda moot if you cannot comprehend what is told to you
Hi :(
But like atleast tell me the steps like ill work it from there
Couldnt be that hard right?
I mentioned 3 solutions you can use, but you have to do the research yourself. I can only point towards stuff and answer some questions
the cheapest way is probably doing the unity Free Relay/Lobby stuff
or dedicated server if you dont want to do p2p
VPS cost money but less usage limits
generally is based on CCU (concurrent users) per month yes
the free tier unity has is pretty generous to get started, many people never come even close to the limits
Alright yeah im getting it, ill be screenshoting this convo for when ill get more expirienced i think you are right
good idea lol
Thank you dude appriciate it
btw if you're just trying to test it with like a friend or something like that, you could also temporarily open your port in router and give them your IP with port to connect to if you host.
Huh that sounds complicated
this is complicated
I think after ill understand all the terms stuff would get easier
there was a time where all this (port forwarding) was pretty common thing to do especially when hosting to play with friends over the wire, dedicated servers were more expensive lol
I have this simple code, the if statement, sees _destructEffect as "null" and not null
why is that?
[SerializeField] GameObject _destructEffect = null;
void Destruct()
{
Destroy(gameObject);
if (_destructEffect is not null)
{
Instantiate(_destructEffect, transform.position, Quaternion.identity);
}
}
Like with hamachi correct?
you should be using == or != with GameObject / Object derived
Tho i remember it being free then nvm
hamachi lets you skirt opening ports (pretends everyone is on the same network / LAN ) but you cant host like a dedicated , say a Battlefield server or something
hamachi wasnt a thing before
basically unity overrides the equality check so the standard c# ones?? and is don't give correct results cause of how unity handles those Object in engine
how would you make something where if the player gets close to it text appears and when the player gets far it would disappear
if i'm using a canvas to show the text and a gameobject to act as a sort-of hitbox for the range of it, how would i be able to do that
activate and deactivate the text object as needed
Trying to make a basic top down shooter and it's going great so far, but I'm a little stuck on how to get the enemies to face me when the game is playing.
I've gotten them to go towards the player, but they'll just point in any which way.
Wait, nvm no they do actually point towards me, I've just got them positioned wrong lol
Yeah the moment you ask a question here you immediately solve the problem yourself xd
It only occurred to me to check the collider once I asked the question lmao
Turns out, there’s a very helpful line that tells you what the “front face” is for the circle collider
I have been learning and messing around with the new input system as well. Took me a good while to wrap my head around it.
public class GameInput : MonoBehaviour
{
public static GameInput Instance;
private MainInput mainInput;
public bool isRunning;
public Vector2 movementInput;
public Vector2 mouseDelta;
public static event System.Action OnPlayerShoot;
public static event System.Action OnPlayerInteract;
void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
Destroy(this);
}
}
void Start()
{
mainInput = new MainInput();
mainInput.Enable();
mainInput.PlayerControl.Move.performed += ctx => movementInput = ctx.ReadValue<Vector2>();
mainInput.PlayerControl.Look.performed += ctx => mouseDelta = ctx.ReadValue<Vector2>();
mainInput.PlayerControl.Run.performed += ctx => isRunning = !isRunning;
mainInput.PlayerControl.Shoot.performed += ctx =>
{
OnPlayerShoot?.Invoke();
};
mainInput.PlayerControl.Interact.performed += ctx =>
{
OnPlayerInteract?.Invoke();
};
}
}
I don't know whether it's the most optimal, but I split all input reading away from my player controller class to its own class which is singleton so I can easily access the Vector2 values for instance.
Then I can just subscribe to those shoot and interact events from anywhere I like
Uff
}
}
}
}
}
}
}```
I think I read a coding tip somewhere that said, if you ever get more than like 4 indents deep, you need to rethink your decisions lmao
Yes
My life got better when I realized I could invert most of my ifs and just say return
or continue 😄
There's a method in one of my projects that consists of a switch with 5 cases, and each case has 4 nested ifs inside
Pasta is ready
Guard clauses!
music slider and sfx slider work in editor but dont work when i build the game
If you build a development build, you can connect your player to the editor console for easy console output. When that isn't telling me enough, I'll usually connect my player to the debugger in my IDE and set a breakpoint in the function, and then step through it line by line to see if the code executes as I expect it to.
Hello there :D
I want to check for a button press via the getkeydown thing.
Should I put that into update?
I do not want to trigger the function that I will connect to it every frame, but only once per button press
GetKeyDown() inside ur Update
Then you'll have to create some toggle to only call it function once
Hey :D GetKeyDown is true only for the frame the key is pressed, so even if the user holds the key down, the check in Update won't continue, so your logic will only execute once until the key is released and pressed again.
public SO_ItemConfig itemConfig;
public void Interract()
{
if (itemConfig.GetType() == typeof(SO_WeaponConfig))
{
Debug.Log("it is a weapon");
}
else
{
Debug.Log("it is not a weapon");
}
}
How would I correctly check the type of the scriptable object in question? The SO_WeaponConfig inherits from the abstract class SO_ItemConfig. Currently this returns false even though the itemConfig is infact a SO_WeaponConfig.
I mean I could just make them seperate things I guess
wouldn't it be itemConfig is SO_WeaponConfig
Both of those would work fine, this is kind of an anti pattern though
can even get the cast like
if (itemConfig is SO_WeaponConfig weaponConfig)
GetType() == would make it false if you have a subtype of SO_WeaponConfig
would be curious to know what your actually checking because yeah ideally you shouldn't need to care to know what it is
move to #🖱️┃input-system and show your interactions set up
(once you've copied the question over, remove it from here to avoid getting double help)
I made this in like 30 seconds in paint, sorry not a proper diagram but this is my pattern currently.
The interface is actually badly named because I plan to use it for pushing buttons and interacting with similar objects
so is it more like IInteractable?
you may want to do your inheritance in a kinda sibling esque way so you have a Weapon : Item class that overrides Item's implementation of IInteract
Okay yeah that makes more sense
Would I need to do Weapon : Item, IInteractable ?
I'd rather have a separate interactable object that has an inventory(or just 1 item slot)
you would implement Interact as a virtual function in Item
For dropped items
(It's possible my suggestion is not the prefered way to go, many different ways you can do this tbh)
@grand badger ?
Yea I'm mostly just trying things around
Yes that should work too
well, if not all items are interactable, this isn't a good approach
I am going off the context of the information they have provided
if there's a IUseable item in the plan then this pattern is solid imo
Why is this always returning true? bool grounded = Physics2D.Raycast(transform.position, Vector2.down, 0.1f); if (grounded) { print("Grounded"); } else { print("Air"); }
because it may be hitting the player's collider. You should use a layer mask that checks SPECIFICALLY for the ground layer.
oh yeah, good point
I need to test it some more to figure out if it works for me
I only recently started messing with more flexible patterns after reading this ebook https://unity.com/resources/level-up-your-code-with-game-programming-patterns
if you're a beginner, it's a trap 😛
what's your scope for this game, specifically? (in e.g. months + target/goal, like release, portfolio, etc)
I am using a layermask and it is now returning false all the time
Ye for smaller games might not matter that much but I feel they are useful to learn still
great! You should move the root position closer to the player's feet. Right now it's on the center of the player
The raycast is hitting the ground
I am checking with debug.drawray
And the ground platform does have the Ground layer applied
some people prefer using feetTransform.position, some others prefer using transform.GetComponent<Collider>().bounds.bottom + Vector3.up * 0.05f;
Oh wait
yeah, but the debug drawray likely doesn't match your raycast's hit. Currently, you're using 0.1f as length
I see what you mean
I just realized that
Haha, no, no, I mean -- "proper" architecture can EASILY turn a small project into a huge one if you're not careful.
for beginners, my advice is to experiment with what's believed to be wrong, and find out for themselves why other solutions are proposed.
what's believed to be wrong: not exactly, but more like "What YOU believe is good, with your current understanding", even if other people/best practices are against it.
Well I have some older projects that use GameObject.Find() for literally everything. At least I'm past that stage lol
ya that's what my first project was like as well xD
soon refactored to use references, then refactored again to use OOP, and so on
👍
I am having a bit of trouble getting the bottom position of the bounding box of the collider
I am using 2D
if that helps
you could use 0.6 * the height of the collider
or you could add the extents.y to get the bottom
I got it at the bottom now
or you could set the pivot to the bottom
The raycast just always returning false for some reason
have you set the layermask correctly?
I think so?
show your current !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/
📃 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.
private float playerInput = 0;
// Horizontal player speed
[SerializeField] private float speed = 250;
private Rigidbody2D rb;
public float jumpPower = 10;
void Start()
{
// Get component references
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = new Vector2 (rb.velocity.x, 0);
print("jump");
rb.AddForce(Vector2.up * jumpPower, ForceMode2D.Impulse);
}
playerInput = Input.GetAxisRaw("Horizontal");
SwapSprite();
IsGrounded();
}
void IsGrounded()
{
Debug.DrawRay(new Vector2(transform.position.x, transform.GetComponent<Collider2D>().bounds.min.y), Vector2.down, Color.green, 0.1f);
bool grounded = Physics2D.Raycast(new Vector2(transform.position.x, transform.GetComponent<Collider2D>().bounds.min.y), Vector2.down, 0.1f, LayerMask.NameToLayer("Ground"));
if (grounded)
{
print("Grounded");
}
else
{
print("Air");
}
}
void SwapSprite()
{
// Right
if (playerInput > 0)
{
transform.localScale = new Vector3(
Mathf.Abs(transform.localScale.x),
transform.localScale.y,
transform.localScale.z
);
}
// Left
else if (playerInput < 0)
{
transform.localScale = new Vector3(
-1 * Mathf.Abs(transform.localScale.x),
transform.localScale.y,
transform.localScale.z
);
}
}
void FixedUpdate()
{
rb.velocity = new Vector2(
playerInput * speed * Time.fixedDeltaTime,
rb.velocity.y
);
}```
you should probably use a serialized field for the layermask
ok
make sure the layer name is accurate, including casing stuff
the spelling is correct
btw though, you shouldn't use GetComponent every frame like that, if you're going to use it a lot like here you should put that in a field that you set in Start/Awake like you've done with rb
the drawray isn't accurate though btw. you need Vector2.down * 0.1f for the drawray
Ok, I'll do that
Where?
where you have Vector2.down now
drawray doesn't take a separate distance parameter like raycast
oh
what you have as 0.1f in the drawray is how long to draw the ray for
anyways, make sure the ground is on the right layer and has a non-trigger collider
Wouldn't checking if player is touching the ground with something like OnColliderStay also work here?
It is not set as non-trigger collider, I will fix that
scratch that
it is not trigger
my brain farted
can you show the inspector for the ground object
Took me a while to memorize this chart. It's the first thing I check if something isn't colliding lol
well depends on the level layout
it would be more complicated if you ever interact with the side of a platform or something like that, you'd have to check the contact normals and stuff
I think the chart lines up with what I have
and its layer?
Difference between collider and rigidbody collider?
rigidbody collider there refers to dynamic rigidbody + collider
Imma just google an example this is too frustrating
but yeah i think that chart is somewhat misleading in saying "trigger rigidbody" as if it's a property of rigidbodies lol
it's not relevant to the raycast check though
ah the issue was the layermask lmao
oh
Now I am using the method the website suggests and it still doesnt work
the public layermask one, I am about to try the other
did you actually set the layermask in the inspector?
Yes
No
What
II swear I set it
Anyways it works now
I must of set it whilst it was running
probably yeah
When the square hits the ground, it kinda pushes itself into the ground and then moves back up
Is there an easy way to fix that? Or is that just how the physics work
imma just get back to it tomorrow
Is it possible to load/copy methods from a file?
load/copy to where?
I'm trying to make a character selection thing similar to a fighting game, where every character has different attacks, and I think it wouldn't be smart to put a method for each attack of every character into the controller class so I wanted to load it in from somewhere
This is the case for scriptable objects I believe
so I make the character controller a scriptable object instead of mono behaviour?
no, you would just supply the attacks via scriptable objects
I don't understand how to use this
did you find the manual page?
yes but I don't understand how this applies to my case
unless I replace the whole controller with one of these objects
Make a script, make it a scriptable object, fetch the so from another script, call the method in the so
No, your controller needs to accept a scriptable object as input. Inside the object you have some values and methods for different attacks. That is quite literally "loading methods from a file" .
I think at least that's the use case here.
my original thought was to have a general character controller and to load in all the values and methods from a file
Thats what a SO is
Yes you can also turn scriptable objects to files
ah I see
so I'd have one scriptable object per character with all the data relevant to each?
Something like that
ok cool, thanks
Different characters can have different health values, but if I store the health value in the character's scriptable object and two players choose the same character, will their health values be the same variable?
So when one character gets hit, both lose health?
Or will they be separate instances since they're loaded for separate players?
that's something you can control
There is ScriptableObject.CreateInstance
changing the health of the so vs changing the health of the character
but you would treat the SO as stats and keep the actual current health on the character
I think the latter is better no?
My understanding is scriptable objects are best used as "templates" for data, not necessarily changing it at runtime?
Ugh, I finally decided it was time to restructure my code.
Never again. Nothing was worse than 4 hours of namespace errors
Any time I will one day save by not having collisions
I have burned through in the worst way. Possible
How do you get that many namespace errors? Renaming bunch of stuff or something?
Yeah I went from function to feature based
Basically all my UI code used to be in my UI name space
Now if it’s like, character editor UI. It’s I. The character editor namespace
Helped with dependency
Still ate my soul
I let an LLM do the renaming and moving
So this one is on me
anybody knows why when I drop a spreadsheet with an animator on canvas, it's always behind? Tried playing with layers and z and it won't come up. Tried talking with my bff chatgpt but just tells generic things
Try moving them around in the hierarchy. The bottommost gameobject in the hierarchy is the "top layer", kind of confusing.
Can I load different parts of a scriptable object into different controllers or do I have to make a separate scriptable object with the data relevant to each controller?
yes
In this case, stats like health, attacks and special abilities would be handled by different controllers
Maybe I'm still not understanding these scriptable objects properly but I haven't been able to find information on how to properly use these in a case like mine
And the manual is completely useless
Can I just store the data in json instead or something
You can store it wherever you like. ScriptableObjects allow you to change the values in the Inspector directly while for a JSON file you'd have to use an external editor or make a custom editor.
If you use SOs I would not change any values at play time. Only use them to set your start values.
yeah that's what I want to do
but I can't figure out how
public class UnitData : ScriptableObject
{
public int startHealth = 50;
}
-------------
public class Unit : MonoBehaviour
{
public int currentHealth;
public int maxHealth;
public void Setup(UnitData unitData)
{
maxHealth = unitData.startHealth;
currentHealth = maxHealth;
}
}```
so in this case I would load the whole scriptable object into each controller but only get the relevant variables in each?
was the scriptable objects intended to be for the attacks? just skimmed through from the above conversation.
for what you were asking above, I would also just consider having each attack be its own monobehaviour if it requires state just to attach it to a prefab. Then you can drag them into your controller.
If you wanted to supply the attack methods by putting them in a scriptable object, they cant store any state inside the SO. So you'd have to find a way to copy this
though its not too clear, what are these relevant variables?
I have different controllers for handling player stats such as health, attacks, special abilities, animations, etc. But I would save all of that data in a scriptable object for each character. Or do I have to make a separate scriptable object with the data relevant to each controller?
you would have 1 scriptable object per character that needs it. the stats would be easy to do. the attacks, abilities, and animations depend on how you've actually defined an attack/ability in the first place. I don't see a great reason for those to be on the scriptable object
because the attacks and abilities are different for each character
You can do it how you like. You can also have a "main" ScriptableObject that has references to the sub-ScriptableObjects and then the Unit script passes the sub ones to the specific modules.
public class UnitData : ScriptableObject
{
public AttackData attackData; <- is a SO
public HealthData healthData; <- is a SO
}```
basically, each attack and ability has different code
im aware, i did address this partly up here #💻┃code-beginner message
i still dont see a great reason to put these attacks on a scriptable object really. it would be a lot easier setting up as a component if the attacks need any mutable data on them at least
you'll need different prefabs for each character anyways
If you try to just reuse one prefab where you change out everything from scriptable object data, it will get a bit complex
I don't understand. The data has to come from somewhere right? So either I code each attack in to the controller, or I load it in from a file/SO after character selection
or a component and drag that into the controller.
ScriptableObjects can be made into files by [CreateAssetMenu], then you can just create a bunch of them with any data you want and plug them wherever you want. The data being usually values like health, name, damage, etc.
And methods?
you wouldnt be loading attacks/abilities from a file unless this was changing at runtime so that one shouldnt be considered.
You can easily define stats inside a scriptable object, this is common. but that doesnt change the problem in trying to assign specific attacks/abilities to a scriptableobject.
is there something you arent understanding about just being able to use a component for this?
because at this point im just repeating it while you repeat that attacks/abilities are unique
I'm trying to understand how to do this. So I create a component for each possible attack and attach them to the player after selection?
You would ideally already have them attached as a prefab. This will be the easiest way
So each character would be a prefab with relevant components attached?
and a scriptable object for values like health
Or is there something I'm missing still?
and then each prefab has their own copy of all the controllers
yes, this is how i would start. im not sure what your controller is but ideally this would be the same code across characters when possible. all you'd need to do is drag in different attacks
yeah the controller is basic methods like movement etc
maybe you're conflating stats and state? health isn't a stat, max health is, but current health is a state
yeah max health is the stat but changing health and keeping track of current health would be in the controller
or is current health in the prefab/SO too?
its up to you if you want to provide the current health as well, if the starting current health is different from the max health. they usually are the same but thats game design. you just make sure to copy the data so you arent modifying the SO in any case
health is definitely also a stat
no the characters start at max health so that's not an issue. I would have the controller create a variable that stores the current health
unless I'm not supposed to do that
thats fine as well
prefab/so aren't equivalent
you would more likely have the controller as a prefab?
you generally work with instances of prefabs rather than the prefab itself, in which case you would have health on the instance of the prefab
but not on the SO
yes, I mean max health would come from the SO
im referring to current health there
so if I understand correctly, I have a prefab for each character that imports the controllers for basic methods and components for attack methods, and it gets instantiated with the stat values from the SO
controllers being the same for each character
does that sound right?
So just to clear things up, you'd have a base stats SO that you'd create multiple instances of as assets and have your characters reference those SO instances to initialize your stats. You'd have the characters current stats on each character and not the SO.
i think you're kinda conflating the prefab idea with the SO idea
Just to clarify, you'd probably have one Character prefab and multiple instances of that prefab
hello i recently made my first game and build it into mobile but im noticing a significant performance issue and input lag any reason why it is happening
the whole initial problem was about getting different attacks per character. the easiest way being through different prefabs for characters
you need 2 things here - a runtime controller, and a static place to store stats
option 1 - a unified, single prefab for the controller as the former, and several SOs to supply the latter
option 2 - prefabs for each individual character, possibly as variants of a base controller, where you could then have the static stats on each prefab individually (the runtime aspect would be instances of that prefab)
if you have separate prefabs for each character anyways then there's no point for the separate SOs for stats, you can just have stats on the prefabs
you'd have to use the profiler to figure out whats causing issues. theres nothing we can say as to why its happening
ohh
okay
and i saw a method of sprite atlas should i also implement that?
I feel like you understood what to do up here before, this seems like the same question , #💻┃code-beginner message
Maybe just try it out and see where you get stuck because it really just looks like repeat of the same answer
if you need one, then you use it
I'd use an SO if you've got data to share between multiple prefabs - reuse. If you're just needing to input/setup unique data from the inspector, you'd be able to do so on a prefab instance.
OK so I don't actually need the SO, I just make a prefab for each character which already contains the initial stats, and has attached components for each attack
If I turn a GameObject into a prefab and later add something to the object, will the prefab change as well or do I have to edit each prefab individually in that case?
afaict, I have to start by turning my player object with the controllers into a prefab
A prefab lives in your project folder. It is considered an asset. From the moment you grab that asset and drag it into your scene, you create an instance of that prefab. A living copy.
If you modify that living copy(the one in your scene) and you do not apply the changes, then changes will not apply to the prefab(the asset, the template).
If you modify the actual prefab, so the one residing in your project folder, or if you apply the changes to the living copy you brought into your scene, then those changes will be reflected upon all copies of the prefab.
The exception happens when you modify living copies and do not apply the changes. Say you have an apple prefab. Apple has an exposed field with 20 hitpoints. You create an instance of that prefab by dragging it into the scene, and you change the hitpoints, in the hierarchy, to say 15.Then this specific instance knows it has a different value for hitpoints, and whenever the prefab is modified, it won't be reflected onto that specific instance
The plan is to have about two dozen characters ultimately and I am worried that if I find and fix a bug in one of the controllers for example, I will have to do this individually 24 times for each prefab
If you expose fields in your controller(e.g. public fields or fields marked with [SerializeField], then yes, you will need to manually tweak the values across all of your prefabs since they each will have their own values
not values, I mean things like movement methods
Right now I have a player object with different controllers handling stuff like movement for example. But I have to make a prefab for each character, and each character uses the movement method from the controller
But the controller script would be part of each prefab no?
Do all prefabs require a controller? If so, then yes, each prefab has a controller.
It is perfectly acceptable to have several prefabs with the same components
yes they do, each prefab uses the same movement controller but different attack methods
and if I later find a bug in the movement controller, I have to apply the fix individually to each prefab?
It's a bit rough but it's perfectly acceptable
No, you apply the fix to the controller script, this has nothing to do with the prefab.
If you need to change which components are used for whatever reason, this is where you'll need to modify prefabs
the logic behind unity data organization is so obtuse to me for some reason
Right now, what confuses you the most?
