#💻┃code-beginner
1 messages · Page 686 of 1
C# having the ability to allow if statements to not need { } when they only have 1 following line, is a feature I get has utility, but i really wish wasnt a feature
im not really sure why its allowed in the first place besides from have a shorthand like if (foo) return;
why do you dislike it?
I find its confusing when reading code where you get lines that lack the braces, mixed in with other code
I have to pay more attention to figuring out that two lines that seem like they follow, dont actually follow because theres an brace-less if statement above it
on the other hand it saves 2 lines of code, so advantage for reading
but if it was all surrounded by braces, even for that one line, I can immediately parse the code when reading
it really varies on the context of what the surrounding code looks like
for very basic early returns out of methods, its not so bad
Hi, what's a good way to handle JSON serialisation for abstract classes?
For example my inventory is a simple List<Item> where Item has abstract classes for specific categories, for example Weapons
If a Weapon also has a a damage attribute, whats a good module to use to serialise the list in a way to avoid storing unused attributes on other classes?
Something alone the lines of maybe
{
"itemId": "straight_sword",
"quantity": 1,
"extra_attributes": {
"damage": 1
}
}
you could create a "SwordSaveData" class that has an int for damage and quantity
How would I then serialise my List<Item>?
I was thinking about using JsonUtility but I can use Newtonsoft too
you wouldn't serialize the item itself, just the save data
Yeah, but since my objects are stored as a List<Item> I'm not sure what I'd have in the serialised JSON list
If I made an Item.ToSerialisable() method that returned a SaveData and then created a List<SaveData> I'd still have the same issue
Why return a SaveData?
Basically if I, for example, wanted a method to convert from my List<Item> to and from JSON I'm not sure what steps I can take when considiering polymorphism
Probably a better name would be SerialisableItem, and instead of storing the references to the sprite, etc it'd just have the iitem ID
Then when I load from JSON I can convert my SerialisableItems to Items using a database to get the prefabs, sprites, etc
Well I think a string just works better for saving, especially if you're using JSON
Yeah, but how do I construct that string
I could consturct iti manually
but I'm wondering what'd be a modular way to do it since unity has stuff like JsonUtility
If I constructed it manually polymorphism wouldn't be a problem since I could directly have a virtual ToJson method that serialised an Item, but I'm just curious if there's a better way to approach it
Not necessarily, but I thought it made sense because I won't have that much data (only my friends will play this) and it makes it easier to read and ediit save data
And yup, locally
Oh I should've prefaced its a multiplayer game but I guess thats not totally relevant
I'm ok with alternatives like serialising to bytes if converting to JSON would be a headache, but I'd like to convert to JSON for readability more than anything honestly
I don't think JSON would be needed if you aren't worrying too much about anything other than reading and editing data
Right right
It depends what you're saving though, you mentioned inventory, but is that all?
So if I directly serialise to bytes can unity handle polymprhism etc?
Do you save things like currency too? Or is that also an item?
Inventory, equipped items and some trivial attributes like levels
I'll just save it as a uint
I can't really answer anything with terminology as I only do code, not dabble in terms
[System.Serializable]
public class PlayerData
{
public List<Item> head;
public List<Item> torso;
public List<Item> legs;
public List<Item> resources;
public List<Item> weapons;
public Weapon weapon;
public Armour headArmour;
public Armour torsoArmour;
public Armour legsArmour;
}
Oh right I basically just mean that if I have Item as abstract and for example have stuff like public class Weapon : Item
Makes sense, it shouldn't affect it then
Then is unity able to serialise a List<Item> properly even if it can be different types of Items?
Alright nice nice
You can save only what's in the item class, and load directly into the item class from your other classes
I'll probably just do that then and serialise my PlayerData correctly then
Right
One thing is that I will have to convert from Item to SerialisableItem
You can also use reflection for things inside the classes themselves if required
since Item has stuff like references to prefabs and the sprite, so I could hav ea SerialisableITem that instead has a string ID that can be linked in a catalogue to stuff like the sprites for items
Yeah, you can have a helper class for figuring all that out
Alright I'll see how I can save objects to files then
Tysm
I'm sure there are utilities to read serialised data in a file if I really need to anyways
Yeah, would be a bunch as it's a big topic
im not really sure why you were given the suggestions that you were above. Json is completely fine for writing all the data
https://dotnetfiddle.net/zmmr4S
The claim that a "string works better here" makes no sense. JSON is basically just a fancy string
A tool for sharing your source code with the world!
hi is this movement controls written well? or is there better way
there are many better ways. if this works for your use case then 🤷♂️ it works
there are hundreds of movement tutorials out there
you should also see the code I put in my message above because your suggestions for their problem is very misleading or just wrong
#💻┃code-beginner message
it works but i have one issue. when i keep pressing wasd and space at same time wasd keys are not working
I'm aware it's fine, I was just saying it's not the only option
then possibly all your if statements are true, and all the forces you apply are counteracting each other. You should look up tutorials or guides on what to do. Actual movement code is a lot more complex than this usually
yea i changed those values little bit now it works
Also, I was implying string as a return type to compile into a save file, just to be clear, if that was misunderstood, apologies
Is there a practical use of 'internal' in Unity C#?
why not? if you're using multiple assemblies
i see, yea i misread that part. the messages kinda read like "construct the string manually"
Then apologies for the misunderstanding, I'll be more clear with my meanings next time
If you use an assembly definition then you can use internal to have access to code all from within your assembly while keeping it hidden from outside the assembly
So like if you make a tool and you need scripts within the tool to talk to each other, but you don’t want the end user to have the same level of access
even without asmdef also, say I have a static function / class / method in Dynamic Library / Class Library, i wouldn't want to necessarily mix that with gameobject code / unity components
i dont exactly bother using it in my own game, but if you're going to make tools for the asset store it could be pretty useful so people dont go using stuff they shouldnt be touching
its an access modifier. they're all useful as a developer and dont affect your actual end product
I never go below internal for access, just keeps it limited to my own code rather than letting external code access it
Hi everyone, sorry if i ask this wrong sub. I think my question is beginner so put it here is okay.
I’m reading about vector rotation and I have a question about this formula in the book:
P'=Pcos(θ)+Qsin(θ)
- Is P′ supposed to have the same length as P?
- Why is the perpendicular component of P′ equal to Qsin(θ)?
I also included my own derivation in the last image.
I'm not sure there's a code question in here 🤔
sorry, could i put it in #unity talk? 🥲
I would say:
- Yes
- Not sure what the question means.
i think I don't really understand how they came up with this linear combination in the first place.I know that any vector in the plane can be written as a combination of two orthogonal basis vectors, but the cos and sin come from no where.
it doesn't explain in what you shared. They are simply showing a rule here of how to create the rotated vector from a linear combination of P and Q (also how to create Q from P) based on the angle theta
It doesn't explain how it was derived as far as I can tell
but it's a neat trick
Based on this I guess https://en.wikipedia.org/wiki/Orthogonal_basis (still no derivation here)
hey does somebody know how i can change animator parameters through code?
Have you checked the scripting reference? https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Animator.html
I guess in a sense it's actually kind of simple
if you just think about the equation for a circle
it's x = sin(theta) and y = cos(theta) for any point at angle theta right?
oh thanks
So this is just adjusting that for some rotated orthogonal basis based on an arbitrary vector
it's a way of using that simple circle point formula for an arbitrary 2D axis system rather than world x and y
so like - in a normal circle your P and Q are just the x and y axis, aka (1, 0) and (0, 1)
this is just a generalization of the formula for any such pair of orthogonal vectors
ahh i see, that actually sounds right.
i just wrote some stuff down, and p' = p * cos(theta) + q * sin(theta) actually matches what i derived with P(x,y) and Q(-y,x)
but because of that, i'm still confused about the length of p' because i assume r is 1.
I think |P| = |P'| = 1 because r = 1. What if r not equal 1? I wll write down some.
I'm having an issue with my buttons on my pause screen not working the 2nd time going into the pause screen. Everything works great the first time and I've removed all cleanup and disabling code to see if that was the culprit but still having the issue. Any Ideas on this one? I've been banging my head on it for awhile
Solution was to re-register UI elemets and callbacks every time the pause screen is shown
P and P' will have the same length because you're just picking points on a circle and the definition of a circle is a collection of points at the same distance from the origin
i can finally grasp it. thanks for the very conversation.
i remember you helped me many times before, probably because of the car avatar
I hate Rider. what is the point of this feature except too confuse people
yea, rider has no chill
riders always been too much for me.. some people swear by it.. but i can't deal with its constant nagging 😅
Yeah, the main issue here being i dont know which of the 2 options to use
if (target) or if (target != null)
🫤
i'd leave it as is
if u do target == null u can use an early return
thats pretty much the only difference.. (can do away with the extra else) of the if statement
if(target == null)
{
return;
// rest of code (code u want to run if target *is* assigned
}```
rider suggests using if(target) because it gives clear intent that you are doing a unity object lifetime check. if(target != null) is not clear intent for the lifetime check because it could be confused with a simple null check
I disagree completely
Literally just turn the suggestions off
You don't even have to go into the settings to disable inspections you dislike
i use vscode now b/c its more universal (works out for me and my many projects) but ill keep that in mind 👍
I'm not sure what's specifically universal about VS Code
i use it for unity, webdev, and embedded work (platform io)
Using the implicit conversion is more error prone in my experience, there's plenty of time I've found it making code worse by accidentally converting to booleans when it wasn't meant to be. If I could have it be an error to use it I would!
If you want to do an explicit null check then you would use a modern null checking operator or ReferenceEquals, using an equality operator on a UnityEngine object already communicates intent, because that's default behaviour.
There's no difference in intention when you choose to use implicit boolean conversion (except that in Rider it won't show an implicit conversion icon, which removes that clarity).
Hey, it is a good idea to use State Enums in the Player or no?
I mean cuz, for an NPC Ai it is... But for a player?
There's no universal reason not to, it comes down to what you're trying to do
If it makes sense to track a certain state on the player, why not?
The issue is, under my opinion, not fully, but im scared i may repent later
using UnityEngine;
public class SpawningScript : MonoBehaviour
{
[SerializeField] private float Waves = 1;
[SerializeField] private float SlimeCount = 5;
[SerializeField] private float SlimeAmount_ToSpawn = 5;
[SerializeField] private float SlimeAliveCount = 1;
public SpawnRadius spawnRadius;
private Vector3 spawnPos;
[SerializeField] private GameObject Clone;
[SerializeField] private float Timer = 0f;
void Start()
{
spawnPos = spawnRadius.SpawnPos;
}
void Update()
{
spawnPos = spawnRadius.SpawnPos;
Timer += Time.deltaTime;
if (Timer >= 3f)
{
Instantiate(Clone, spawnPos, Quaternion.identity);
SlimeAliveCount -= 1;
Timer = 0f;
}
}
}
``` for some reason after timer reaches 3 it infinitely spawns clones even after the timer resets to zero
sorry for interuptting i didnt notice until i sent my message 💔
depends.. if ur game depends on knowing what the player is doing.. sure. makes sense to have a state.. say for example you have stamina that lowers when u sprint..
you could just assume ur sprinting by checking the players input..
or u could go ahead and make it a state.. then the stamina would Lower when the player is in a sprinting state.. applies to if ai would need to know.. if the ui wants to display it to you etc..
its really just up to you and ur goals wether or not ull need to keep up with states
Its like drawing, but drawing logic. Depends on what i need to do
Makes sense
Thanks :3
Perhaps your Clone object itself has a spawner or something?
ohhh your right
The easiest way to know whether a state machine is useful is to chart out the state machine and see if it makes sense
hold on let me try something and ill get back to you
That makes sense
watch this variable in the inspector
you should not be spawning more spawners. Make the spawner a separate thing entirely
thank you both <3 i got it working i had the script on the object i was cloning
inception lol
I assumed they meant that my tojson method should return a string
My question is more how to construct a json string when dealing with inheritance in unity since jsonutility can't
After more googling I'm likely gonna use Newtonsoft with a custom jsonconverter
Yeah the dotnetfiddle example you sent seems perfect
you shouldnt need anything custom for writing. reading the values back might be awkward though since you need to provide the type of class.
im not sure what you're saving either, like do the values on the items themselves change? what exactly are you trying to save
Yeah the issue is only some values must be saved
I have a scriptableobject ItemData with the base attributes
Sprite, name, description etc
My Item class has a reference to an ItemData
When serialising I need to save the ItemData ID, and when deserialising obtain the itemdata from its id
But I do have to save custom attributes like quantity or upgrade level
I thought a custom converter would be the best for that but I'm not sure
Negate '!=' expression (change semantics)
Replace '!=' with '=='
so it's saying the latter doesn't change semantics...?
they're equivalent
I want to modify this script, such that it can instantiate prefabs in the editor view. Purely for design purposes. I'd rather do that instead of doing DrawCube with gizmos (my old method), because it doesn't give an accurate idea of what's actually being built. I asked chatgpt about it and it did give me something that worked, but god was it an ugly implementation. I want to make sure there's a better idea out there before committing to it. The current paste is without any implementation for a "preview" in the editor. If yall need any other info, let me know! https://pastebin.com/y0xciwHW
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Test your C# code online with .NET Fiddle code editor.
Better example
I want some way to essentially omit the dontSerialise field
So I can get it back
Is just using the JSON ignore property sufficient?
i still dont think you need any custom converter here. the problem isn't with reading or writing data, it is with knowing what class to associate save data with so you can assign values for the correct item class.
You could even just save a string representing what class it came from (not necessarily the class name but it could be) so you know how to convert it later.
usually id just create a specific class with the data you actually want to save so you dont need to worry about this stuff in the first place. like an ItemSaveData class
Ah okay, cool
So should I then have a method to conveert from Item to ItemSaveData and then serialise that?
If so, how do I deal with the inheritance chart: Just mirror the Item inheritance chart with ItemSaveData equivalents and serialise those with newtonsoft?
Also, newtonsoft can do this trivially with JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; thankfully
Item could create an ItemSaveData. whatever class has a list of items could also create a list of ItemSaveData since newtonsoft would be able to handle that by default
i never used that setting before, will have to try it
Alright thats perfect then
Tysm
Then I can do my ScriptableObject lookup when converting back from ItemSaveData to Item
is Item a scriptable object? im not sure if youve shown this class before. also hard to picture the entire design you have here. either way if its not a scriptable object asset, you could probably just pass the save data in the constructor or through a method
is there a specific thing you're trying to ask in relation to this script? for "instantiate prefabs in the editor view", nothing is stopping you from doing this.
there are methods like this https://docs.unity3d.com/ScriptReference/PrefabUtility.InstantiatePrefab.html
a preview just means you spawn a temporary object. its up to your code to spawn the prefab and destroy it later, making it temporary
ItemData is a scriptable object, Item is an instance with a reference to a ItemData with extra attributes like quantity, custom name (if the player names their sword), etc
So itd be like
Armour myHelmet
ItemData type = (helmet itemdata, id "helmet")
nickname = "My Helmet"
upgradeLevel = 10
and Id like to serialise this to
Yeah I saw that reference. My only concern is properly setting it up. The whole warning about using OnValidate concerns me because that was my first thought into where I would put something like that (at least as far as in my current script)
{
"$type": "Armour",
"id": "helmet",
"nickname": "My Helmet",
"upgradeLevel": 10
}
So that instead of a reference to an Itemdata (which has stuff like sprite, model, etc) I just store an ID which my deserialiser can lookup to get the appropriate itemdata
i see. yea should be relatively straightforward to do though i can imagine it getting a little tedious if you're setting up 3 classes for a new item type. the ItemData scriptable object, a derived class of Item and then its save data
Yea true, but I want it to be modular to abstract from static data like icons and models as much as possible
so thats why I thought this 3 class setup made sense
is there anything that'd require you to use OnValidate? im not sure really what you're trying to do but a preview sounds like something thatd happen based on user input, like they press a button and a preview shows up. They press a button again/let go of previous button and preview disappears
private int _seconds;
public int seconds
{
get { return _seconds; }
set
{
_seconds = value;
OnSecondsChanged?.Invoke(_seconds);
Debug.Log("Ticked!");
}
}
Why isn't the Debug.Log() firing in my script?
Basically, if any of the fields change in UI_InstanceBuilder, I want to automatically show a preview. That's why OnValidate came to mind
i mean first thought would be is that running
(also not that it matters but could be worth considering checking if the incoming value is different from current before invoking that event)
you arent setting seconds anywhere, or theres an error happening in OnSecondsChanged stopping this from running
Oh right. I set _seconds instead of seconds. Simple mistake xd
hm i still dont exactly know the flow here, since thatd require me to know exactly how you want this feature to work. One work around could just be instantiating the object at a different time. I assume you wouldnt want to constantly be spawning new objects. adjust it OnValidate based on the values
Would it help if I said I want it to be like gizmo drawing, but with the actual prefabs being visible?
Because previously I used gizmos and DrawCube to preview a prefab, but that comes with the obvious problem that whatever I want to preview would need to be a cube too
i feel like my suggestion above would still apply then. spawn the object once then just adjust it OnValidate if you want. Maybe tie into some editor update functionality if you need to move it along with other objects
Ah but it doesn't work like I thought it would. I get the seconds from by rounding and dividing current time by 60. Even thought the seconds doesn't change, it still technically sets it every frame
Which means this runs every frame
if(value == _seconds) {
return;
}
Newtonsoft supports adding [JsonIgnore] attribute on whatever you want to ignore (plus 10 other attributes for controlling it)
And I'd only bother with a special serialization class if it's vastly different. As in, if this is a data class already, you don't also need a savabale data class for it.
Hey everyone, I ran into the same issue as the person in this post: https://discussions.unity.com/t/rigidbody-knockback-with-capped-movespeed/851638. I'm trying to implement dashing and sprinting, which both go beyond the walking speed cap i set. In addition I'm trying to set a different max walking speed if the player is on a different type of ground (ice). Any suggestions for this?
i'm getting an error when trying to use SetActive on a private object and i don't understand why
The usual solution for knockback and dashing is that you don't apply the cap when they're happening
and for sprinting you use a different speed cap
pretty much what the forum post suggests
You'll have to show the error message and the variable declaration
I guess you're meaning this error ??
Light is not a valid component. It must be a Component in order to use these methods.
Please properly share all !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.
how do i know what to base the switch cases off of? (holding down the sprint key, checking floor types and such?)
That depends on your code but usually you make a boolean that you set true and false when the action starts or ends
https://paste.ofcode.org/iPsD97ybyQRWYPMRc4X9cM
There you go, i'm following a youtube guide but unfortunatly i didn't found anyone with that same mistake
private object Light; this will not give you any form of methods specific to a clas because an object is the base type for all classes
Pretty sure the tutorial doesn't have private object Light
I'd double check what the tutorial does, I very much doubt they used this variable
oooh noted, so might as well ask before i get to it, if i wanted to implement knockback, i'd be giving a set amount of time to go beyond the normal speed cap?
Likely they used GameObject, not object
Oh yeah they did, it was pretty obvious
ayt, many thanks
{
[SerializeField] private AudioSource ding;
void OnTriggerEnter(Collider other)
{
ding.Play();
Destroy(gameObject);
}
}```
this probably detect all collided, how do usually detect specific target to collide tho?
struggling to get my groundchecks to work on all sides of my object, any help appreciated
you'll need to provide some more detail than that
either set layer collisions appropriately or check other for the things you want to check for
@naive pawn btw thanks for verifying that my dialogue approach with timeline would work the other day, managed to sort it!
uhhhh i have no recollection of that convo
just learned that i can implement character movement with the Character Controller and that the new input manager exists xd. I've been learning based off of Brackey's tutorials, are there any suggestions for updated tutorials?
Can I have multiple identical monobehaviors containing the same event, and have one listener?
could you try rephrasing that
it's not super clear what the situation you're referring to is
multiple components of the same class, or components of multiple classes?
what events, unityevents?
So if I have multiple instances of the same gameobject, invoking some custom C# event like OnTrigger, can I have another class listen to the OnTrigger event?
OnTriggerEnter/Stay/Exit aren't c# events, they're unity messages
or do you mean you're making your own c# event called that
I meant creating custom event with System.Action<> delegate
ah, gotcha
No but you can have OnTriggerEnter call a function on another object or invoke a static event or something
so OnTrigger would be non-static?
I don't care which one of the objects invoked the event, I simply need something to happen when any one of them invoked it.
if it's static, then all instances of the component share the same event thing, and any instance or static context of some other class can access the event, but all subscribers will be informed if any of the instances invokes the event
Okay gotcha, that should work then
Hi, is there a way to remove a component and before removing it also remove all the components that depend on it?
Like, I wanna remove an audio source but can't because there might still be some effects.
Is there no way to forcefully remove it and all the effects at once?
Please @ me and thanks in advance!
not exactly your question, but you could restructure it to where you could just destroy the gameobject entirely
i feel like that'd be easier
Put the source on child object and destroy that?
and yes, I can keep the track of the effects, of course, but it'd be nicer if there was a 1 liner to do this
yeah this is what i do
kind of defeats the purpose of what I'm trying to do here, I don't need workarounds but a solution
i'm trying to suggest something that would make your life easier lol
This field is all about workarounds :P But yeah I get it
yes, I agree, but lets just say that I am curious to find out if there's a way to do this even if I don't need it
I think you're asking an XY problem actually
probably reflection to check requirecomponents
would be nice if unity implemented this feature, will go with child objects ig, thanks
would be a lot of work to hide behind a single method name
make it 2 methods then, remove dependencies and remove component
could have them all implement an interface and then use GetComponents<MyInterface>() and destroy them all.
doesn't really work, it needs to be recursive
good point
yeah, that's a valid option, I'll just store the effects I add in a list tho
void SafeRemoveComponent(Component c):
dependants = new Map<Type, List<Type>>
components = GetComponents<Component>()
for (c in components):
dependencies = c.GetType()
.GetCustomAttributes(typeof(RequireComponent))
.SelectMany(rc => [rc.m_Type0, rc.m_Type1, rc.m_Type2])
for (d in dependencies):
if (d):
dependants[d].Add(c)
for (d in dependants[c.GetType()]):
for (dc in GetComponents(d)):
SafeRemoveComponent(dc)
if (c) Destroy(c)
realistically it'd build dependants only once
yeah pseudocode
but accurate (hopefully) reflection methods just to show the amount of work
I am assuming it could be simplified a bit with recursion but I could be wrong, might give it a try later
this already uses recursion
oh, my bad, I missed that line
otherwise you'd use a stack (instead of utilizing the call stack)
I am assuming the unity team could do something lower level to keep the track of dependencies and speed up+simplify this process tho
probably could, but seems like they don't do anything of the sort
RequireComponent is documented as only being used for AddComponent
also, it'd introduce some problems
if you have components A a1 and A a2, with a B b that depends on A, would deleting a1 also delete b?
yeah that's a good point, could be a bool param to determine that tho
but it'd be a lot more work
if you are refering to performance, an additional method instead that would behave slightly differently
i think the practical issue would also be in maintaining it to be not overly inefficient
yeah if (in the scenario above) b should not be deleted, it'd be more work to check if a2 exists
after discussing it for a bit, I can see why it would be a bad idea to have this built in, could lead to some weird stuff in certain cases
ive been going over old scripts for the game Im making and look what I found
yikes....
(float)0.5
hilarious
there are beginner resources pinned, and see !learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yanderedev ahh code
it can get worse
in other words im redoing the entire thing from scratch!
I mean if it works it works
it works until you have to edit it a few months later
public Vector2 _pPosGet() {
_pPosition = new Vector2 { x = this.gameObject.GetComponent(typeof(Transform))?.position.x };
_pPosition = new Vector2 { x = pPosition.x, y = this.gameObject.GetComponent(typeof(Transform))?.position.y };
_pPosition = new Vector2 { x = pPosition.x, y = _pPosition.y + (float)((double)5/1e1) };
return (Vector2)new Vector3(_pPosition.x, _pPosition.y, 0);
}
dear god is that boss music I hear in the background
I cant edit my capsule collider
Does this object have multiple colliders on it? The edit button doesn't work on multiple colliders acting as a composite so they just disable the button
when it comes to implementing a sprint cooldown, is using coroutines or delta time better for performance (and possibly multiplayer implementation with state divergences)?
don't worry about performance
oh ok in that case which do i pick?
the one that makes your code easy to read and reason with
they're just different methods:
Coroutines are easier to use because the logic is contained inside of it (the coroutine). You don't have to keep track of extra variables, like a timer and the flag to end it, only the Coroutine reference. Starting many coroutines can be difficult to track and a coroutine will act on the next frame after its delay passes, so it's not as accurate.
Using deltaTime and an Update offers more precision as it checks and can update every frame. You can handle many timers at once instead of in a sequential order, but you have to keep track of a flag and a timer variable . . .
alright, in that case ill go for delta time since i dont mind learning about using flags and timers
thanks!
Hey I have been working on a Plane movement, above is the PlayerController script.
My plane basically has to move in the forward direction wrt it's Local Axis but it is moving the World Axis irrespective of its rotation
It'd be great help if someone can clarify this issue 🙂
!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.
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float speed = 5f; // Speed of the player movement
[SerializeField] private float initialThrust; // Initial thrust applied to the player when spawned
[SerializeField] private float rotationSpeed = 100f; // Speed of rotation for the player
[SerializeField] private float turnSpeed = 10f;
[SerializeField] private float yaw;
private PlayerInput playerInput;
[SerializeField] private Rigidbody playerRb;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
playerRb = GetComponent<Rigidbody>();
playerInput = GetComponent<PlayerInput>();
playerRb.AddForce(transform.forward * initialThrust, ForceMode.Impulse);
}
// Update is called once per frame
void FixedUpdate()
{
//Apply continuous forward movement to the player
PlayerRotation();
Debug.Log(transform.forward);
}
void PlayerRotation()
{
// Get the input vector from the player input system and perform movement and rotation
Vector2 moveVector = playerInput.actions["Move"].ReadValue<Vector2>();
yaw += Mathf.Clamp(moveVector.x * turnSpeed, -90, 90);
Quaternion targetRotation = Quaternion.Euler(-45f * moveVector.y, yaw, -45f * moveVector.x);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.fixedDeltaTime * rotationSpeed);
Vector3 forwardDir = transform.forward;
playerRb.AddForce(forwardDir * speed * Time.fixedDeltaTime);
}
}
can someone help me with my code. The camera is smooth when I run on windows but when I put it as a web version (itch.io) it jitters a lot, how do I fix that?
using UnityEngine;
using UnityEngine.UI;
public class PlayerCamera : MonoBehaviour
{
[Header("Looking Settings")]
[SerializeField] private Transform player;
public float mouseSensitivity { get; private set; } = 400f;
float xRotation = 0f;
float mouseX;
float mouseY;
[SerializeField] private Slider sensitivitySlider;
// Update is called once per frame
void Update()
{
//Changes the sensitivity of the mouse to the slider's in the settings
mouseSensitivity = sensitivitySlider.value * 10f;
//Gets the input from the mouse
mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
}
void LateUpdate()
{
//Subtracting the mouseY moves the camera up/down naturally
xRotation -= mouseY;
//Clamping the camera prevents it from doing a whole 360 over the player
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
//Changes only the up/down angles of the cameraa
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
//Rotates the player left/right with the camera
player.Rotate(Vector3.up * mouseX);
}
}```
if you want to check the bug https://poltergeiststudios.itch.io/frozen-yougurt
don't use deltaTime for mouse input, it's already frame-dependant
okk ill do that
hey do i cause any problems when flipping my 2d player by rotating it on the y axis so i dont have to make every animation twice?
i hate that sticker but your prolly right
(Chris has now been shot in the head for linking a reactionary meme)
IT HAS ITS OWN DOMAIN????
calm down.
lol. I think it's my preferred method, since it flips other things for you. Like... ahh it's been a while since I was in my 2d project, but I think vector2.right will change direction when your transfrom is rotated, making attack and walljump raycasts convenient and easy
yeah, a lot of "how to ask for help well" websites do
see also: nohello, dontasktoask, xyproblem, etc...
Vector2.right doesn't change direction, transform.right doees
im in a top down project too so i think i will be fine
i think ill
for a top-down view? 
i think just flipping the sprite (for the graphical aspect) would do better for that since flipping the transform wouldn't work for up/down
the only other thing I can think of to keep in mind is some shaders will be finicky. You want to make sure you're rendering both sides of sprites, since you're flipping it over, and also disable depth write, so it doesn't toggle behind/infront of your character
oh yeah, also that
can i do that when using animations?
i hate animating so much this animator is so complicated
as long as the sprite flip isn't controlled by the animator, it should be fine
ok ill try
you could, i guess? but it'd probably be better to not
oh wait i misread
i thought you said "can i do it using animations" lol
does anybody know about how I would make an enemy take damage from say, a bullet?
so yeah what valentine said
there's a ton of ways to do that, try googling around
ok
i tried it and saw, and it nearly worked first try (hes moonwalking now but this bug should be easy to fix)
lolol
right???
i mean theres a couple bugs left but the piles getting a lot smaller
don't worry, it'll get bigger soon
especially when making my inventory functional and not just a display of items picked up
thats why im doing animations right now
im scared
it didnt fix the issue
maybe the issue is in my movement script?
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private Rigidbody rb;
[SerializeField] private Transform spawnPoint;
[Header("Walking Settings")]
[SerializeField] private float walkSpeed = 30f;
[SerializeField] private float maxSpeed = 15f;
private Vector3 moveDirection;
void Start()
{
transform.position = spawnPoint.position;
}
void Update()
{
//Gets the WASD input
float inputX = Input.GetAxis("Horizontal");
float inputZ = Input.GetAxis("Vertical");
//Makes the direction relative to the players transform
moveDirection = transform.right * inputX + transform.forward * inputZ;
//Makes the Y direction to 0 so that it doesnt move upwards
moveDirection.y = 0f;
//Normalizes the movement so that it does not go faster diagonally
moveDirection = moveDirection.normalized;
}
[System.Obsolete]
void FixedUpdate()
{
//Makes new velocity using the direction and the speed
Vector3 velocity = moveDirection * walkSpeed;
//Makes the y velocity to the original so that the gravity/jumping doesnt change
velocity.y = rb.velocity.y;
Vector3 flatVelocity = new Vector3(velocity.x, 0f, velocity.z);
//If the force is less than the max amount of forced used
if (flatVelocity.magnitude > maxSpeed)
{
//Moves the player based on the input by the move force
flatVelocity = flatVelocity.normalized * maxSpeed;
}
rb.velocity = new Vector3(flatVelocity.x, rb.velocity.y, flatVelocity.z);
}
}
if it works well on one platform but not on a webbuild, I doubt the problem is in the code
why is it marked obsolete
also, where did you get this code?
rb.velocity instead of rb.linearVelocity
how can i make an object rotate to the player-object
do you mean move and rotate or just roll?
var dir = (player.pos - this.pos).normalized transform.forward = dir;
...what?
just rotate on the x axis
rb.velocity is obsolete
i'm talking about FixedUpdate being marked with [System.Obsolete]
If you get the warning for using an obsolete property, like velocity, then you can choose to mark the whole method as obsolete to make the error go away instead of fixing it
Which is not a good idea
won't that just make an error in the build
Yes. Which is why it is not a good idea
gotcha
It just kicks the can further down the road
yeah that's what vs recommends so i assume they just clicked it without knowing that it's wrong
I don't think it will cause an error unless you pass isError: true 🤔
huh. I did not know that. Very neat
I haven't actually tried to build with an obsolete Unity Message function, I don't know if it would give a build error or simply fail to do what you expect. Either way I'd suggest changing it
can someone tell me why i get a NullReferenceException on line 24 when triggering it? https://paste.ofcode.org/UiK9PTEsa6hhmC5EgWztWL prolly the biggest spaghetti code ever but it works mostly
Because something on that line is null but you're trying to do stuff to it anyway
either playerController wasn't set or it didn't have an Animator.
i don't see you setting playerController anywhere
also the animator controller you're passing in is private, so how are you setting that ref?
it's serialized
oh. mb
i cant imagine it lies in playerController as it works the same in other classes
Where do you assign a value to that variable
also, typically types are in PascalCase. having them in a different casing from variables (in camelCase) helps differentiate them at a glance
you can just do a debug.Log chain to figure out what's what
if(playerController == null) Debug.Log("pC is null");
if(playerController.GetComponent<Animator>() == null) Debug.Log("anim is null");
etc
maybe that causes an error as they are named the same? camelCased it by accident havent fixed it yet
that doesn't cause an error, no
it's just a nightmare for readability
(though it could be an issue in some languages where types and variables kinda occupy the same space, like js or c/c++)
oh
maybe because i tried getting a component from a component
ill try referencing the player and not the PlayerController class
i think it should work 
as long as they are on the same game object
I can't recall, tho
Calling GetComponent on a component is the same as calling it on that component's GameObject
that doesn't matter
i don't see you setting
playerControlleranywhere
Where do you assign a value to that variable
it works now but maybe because im referencing the player through a serializefield now and not through code which seems to not have worked
you're still referecning the player through code
you set a reference via the serialized field
you never set the variable before
You can 100% use a variable of type playerController here.
You just need to actually set it to something
how do i set it?
=
or i mean, since you're already doing the CompareTag, you could just GetComponent from the collision component
drag it in usually
good point
its my code
Im getting a warning when doing this but it does actually work, is there a reason not to do null propagation like this?
[SerializeField] private Button restart;
private void Start()
{
restart?.onClick.AddListener(ClickRestart);
}
private void ClickRestart()
{
SceneChange.instance.LoadScene(Scene.Combat);
}```
restart?.onClick.AddListener(ClickRestart); this line gets a unity engine warning but it works the way I want it to
You shouldn't use ?. on any UnityObjects, since they don't use == null the way normal C# objects do. Unity overrides == null to also return true while an object is in the process of being destroyed but hasn't actually been cleared up yet. The ? operator does not do this. This means there will be times that thing?.function() can still throw a Null Reference Exception
it would end up being a Missing Reference Exception rather than Null Reference Exception. unity throws the MissingRE when accessing a destroyed object
So if I guarantee that it will never be possible to access these buttons during cleanup I'm fine?
You should just use if (restart) instead of the ?. operator
if (restart) restart.onClick.AddListener(ClickRestart); correct?
even if you are sure it can't happen, you still shouldn't use the null conditional operator with unityengine objects. it is better to completely prevent the issue rather than just hoping it won't happen
alright
yes
or, since this is in Start, you could just not have any check at all and let it fail-fast if restart wasn't set (depending on what you're using this for, of course)
What I posted is an abridged version of my class. I realized I had coded all the buttons too many times so I just made a ButtonController class that only works if there are null checks. ```public class ButtonController : MonoBehaviour
{
[SerializeField] private Button mainMenu;
[SerializeField] private Button newGame;
[SerializeField] private Button loadGame;
[SerializeField] private Button restart;
[SerializeField] private Button settings;
[SerializeField] private Button exitGame;
[SerializeField] private Button saveGame;
private void Start()
{
if (newGame) newGame.onClick.AddListener(ClickNewGame);
if (mainMenu) mainMenu.onClick.AddListener(ClickMainMenu);
if (restart) restart.onClick.AddListener(ClickRestart);
if (loadGame) loadGame.onClick.AddListener(ClickLoadGame);
if (settings) settings.onClick.AddListener(ClickSettings);
if (exitGame) exitGame.onClick.AddListener(ClickQuit);
if (saveGame) saveGame.onClick.AddListener(ClickSaveGame);
}
private void ClickRestart()
{
SceneChange.instance.LoadScene(Scene.Combat);
}
private void ClickMainMenu()
{
SceneChange.instance.LoadScene(Scene.MainMenu);
}
private void ClickNewGame()
{
SceneChange.instance.LoadScene(Scene.Combat);
}
private void ClickLoadGame()
{
Debug.Log("ClickLoadGame()");
}
private void ClickSaveGame()
{
Debug.Log("ClickSaveGame()");
}
private void ClickSettings()
{
Debug.Log("ClickSettings()");
}
private void ClickQuit()
{
Debug.Log("ClickQuit()");
#if UNITY_EDITOR
EditorApplication.ExitPlaymode();
#else
Application.Quit();
#endif
}```
attached to anything with buttons
probably clunky but its made me type less
the idea being that often most of the buttons will be null or I guess "unity null"
You know, you could set these functions in the inspector for the buttons without needing to assign a function to them in start
You can put this script somewhere central and have all those buttons call functions on it
see that probably makes a lot of sense
not a code question, see #🖼️┃2d-tools or #💻┃unity-talk
this is most likely due to sorting axis
Does anybody know why my text doesnt go away?
using UnityEngine;
using TMPro; // Nodig voor TextMeshPro
public class Pickup2 : MonoBehaviour
{
[Header("Effects")]
public GameObject particleEffectPrefab;
[Header("UI")]
public GameObject pickupMessageUI; // Koppel hier het UI-element in de Inspector
public float messageDuration = 2f; // Hoelang de boodschap zichtbaar is
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
if (particleEffectPrefab != null)
{
Instantiate(particleEffectPrefab, transform.position, Quaternion.identity);
}
if (pickupMessageUI != null)
{
StartCoroutine(ShowPickupMessage());
}
Destroy(gameObject);
}
}
System.Collections.IEnumerator ShowPickupMessage()
{
pickupMessageUI.SetActive(true);
yield return new WaitForSeconds(messageDuration);
pickupMessageUI.SetActive(false);
}
}
```cs
!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.
Do you know how to fix the text problem?
You are destroying this object immediately after starting the coroutine.
How do i fix it im very new to unity and almost everything in that code is made by AI
If you want this object to do something in the future, don't destroy it before it's supposed to do that thing
I want it to destroy the object and show the text and then after 3 seconds the text goes away
Then you would need the timer to be on an object that does not get destroyed instead of this one
start the coroutine on something else or disable the graphics first and destroy it later
If you want the coroutine to finish before destroying the object, perhaps disable the renderer/collider and move destroy to the end of the coroutine? 
using UnityEngine;
using TMPro; // Nodig voor TextMeshPro
public class Pickup2 : MonoBehaviour
{
[Header("Effects")]
public GameObject particleEffectPrefab;
[Header("UI")]
public GameObject pickupMessageUI; // Koppel hier het UI-element in de Inspector
public float messageDuration = 2f; // Hoelang de boodschap zichtbaar is
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
if (particleEffectPrefab != null)
{
Instantiate(particleEffectPrefab, transform.position, Quaternion.identity);
}
if (pickupMessageUI != null)
{
StartCoroutine(ShowPickupMessage());
}
gameObject.SetActive(false);
Destroy(gameObject, messageDuration);
}
}
System.Collections.IEnumerator ShowPickupMessage()
{
pickupMessageUI.SetActive(true);
yield return new WaitForSeconds(messageDuration);
pickupMessageUI.SetActive(false);
}
}
Like this?
cause it doesnt work yet
Or have the coroutine be in a different script and attached to the ui message object. Where you'd call a method from the other script providing some string message and duration. Letting that other script manage the coroutine and allowing you to immediately destroy this object etc
No one way to go about this.
Disable the collider and renderer. Not set the object inactive.
And move destroy into the coroutine.
Its still not working... Could someone maybe add something to the code or rewrite it?
cause everything i do doesnt work
hey should i call rb.velocity in fixed update and input in Update or should i put it somewhere else?
- Create a field called collider and have it referenced in Start using Get Component
- Create a field called renderer and have it referenced in Start using Get Component
- Replace your Destroy call after the inner-most if-statement with the disabling of the two components
collider.enabled = false;
renderer.enabled = false;```
- Call the Destroy at the end of the coroutine (no delay necessary)
```cs
Destroy(gameObject);```
@obtuse zenith
Thx its working
Im using IpointerEnter and Exit to change cursor when hover
but if the UI just turn off, like disable the cursor doesnt change back
do i just make like an edge case with OnDisable setCursor = null back? feels wrong. how do you guys handle cursor changes
Hello guys for some reason my item's rotation and position keeps changing during playtime. I disabled all scripts and colliders but the issue is still there does anyone know what is causing this?
hmm but wont I need it for when I am dropping the item??
it doesnt work 😭
it doesnt lock the obj rotation ?
nope it should but the object is still changing values in terms of rotation and position
also I have the setup like this. Only IronRod_item has this issue the weaponholder and IronRod prefab remain unchanged
which one has the above rigidbody
the IronRod_item
ngl idk
Where is the code
sure ill give it btw how do you write code on discord
!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.
he disabled all the scripts in that object tho
It's kinematic it's already locked
thats true
i thought kinematic still allow to change obj transform ? static is locked isnt not
Kinematic can change the transform but nothing else besides script would affect it, unlike dynamic
,,,Cs
private void Drop()
{
equipped = false;
slotFull = false;
transform.SetParent(null);
rb.isKinematic = false;
coll.isTrigger = false;
rb.velocity = player.GetComponent<Rigidbody>().velocity;
rb.AddForce(fpsCam.forward * dropForwardForce, ForceMode.Impulse);
rb.AddForce(fpsCam.up * dropUpwardForce, ForceMode.Impulse);
float random = Random.Range(-1f, 1f);
rb.AddTorque(new Vector3(random, random, random) * 10);
gunScript.enabled = false;
}
}
damn it i messed it up 💀
Do you have a video of the issue.?
sure ill send a recording
using UnityEngine;
using UnityEngine.SceneManagement;
public class gamemanagerscript : MonoBehaviour
{
public static gamemanagerscript instance;
public GameObject pausemenugameobj;
Canvas pausemenucanvas;
private bool paused = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape) && !paused)
{
Debug.Log("escape pressed");
pausegame();
}
if (Input.GetKeyDown(KeyCode.Escape) && paused)
{
resumegame();
}
}
public void pausegame()
{
pausemenugameobj.SetActive(true);
pausemenucanvas = instance.pausemenugameobj.GetComponent<Canvas>();
Debug.Log("func entered");
pausemenucanvas.enabled = true;
Debug.Log("pausemenugameobj is null? " + (pausemenugameobj == null));
paused = true;
Time.timeScale = 0f;
}
public void resumegame()
{
pausemenucanvas.enabled = false;
paused = false;
Time.timeScale = 1f;
}
// Update is called once per frame
public void returntomainmenu()
{
SceneManager.LoadScene(0);
}
}
@tidal tide
and/or anyone really ive been going at this for literally 3 hours
@rich adder @rugged beacon here it is
The stick?
scripts in weaponHolder ?
yea
no its on the IronRod_item
interestingly the weaponholder is unchanged
Disabled scripts can still run functions
if this is trrue you should show the script item script code too
alr but im pasting it raw idk how to paste code like that 💀
Did uiu animate the stick with animator/animation?
The code seems fine and you're enabling and disabling the pause object well, which object is this code on?
no the hand is animated and the stick is inside weapon holder which is attached to a bone in the hand
Use the links
!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.
wait @tidal tide
i think i found it
i wrote this
Debug.Log("Scene: " + SceneManager.GetActiveScene().name);
Debug.Log("pausemenugameobj scene: " + pausemenugameobj.scene.name);
and they didnt match
that means that the gameobj im trying to activate is in another 'scene' (which is 'DontDestroyOnLoad' while the actual scene is 'Level 1'
Idk why this happens but apparantly unity dont say anything abt it and thinks its an active gameobj and that it exists which doesnt return a null error but i cant alter/change it at all
Ooh I understand the issue, so your references are not being carried over to the next scene, but I'm surprised it didn't throw a null error as well
Well done finding the solution though
like this ? https://paste.mod.gg/nsgmslajwloa/0
A tool for sharing your source code with the world!
and i think this happens because the pausemenu is a child to the gamemanger gameobj which has a dontdestroyonload on the whole gameobj
chatgpt found it tbf lol
@rugged beacon @rich adder here
btw there is another script called gunScript but it is just a dummy placeholder the script has no lines inside
So this does mess wit the picked object?
yea its suppose to allow me to pick up and drop the stick
If you disable this script, what happens?
just to be clear there is no script in the WeaponHolder parent object ?
nothing else reference to that obj beside itself?
yup
theres seem to be one other gunscript
thats empty
ngl idk
man should I just delete the item and start over?
delete the one at a time a guess, and im guessing removing the rigidbody will resolve it
i did remove rb doesnt help so yea best option is to restart
thx for your time guys @rich adder @rugged beacon i will come back if i found the answer
What about disabling animator
havent done that lemme try
i ddint see any animator fr
hes talking abt the ones im using in the arms and nope doesnt work
hmm I suppose try redo one thing at a time and see where it goes wrong
guys i found the issue its when I change the interpolate to exterpolate thats when the issue arrises now idk why that happens but i was follwing a tutorial and the person said to put that setting on
Hmm probably turning it off would've been fine as well.. iirc a side effect of interpolation being on kinematic causes movement
yea i turned it off
My concern is if theres code that's running that doesnt need to be anymore (when you reach maximum falling speed). does that make sense?
You might need to rephrase your question.
Nevermind, I'll keep thinking about it
not the core API no
you can make interop calls / libraries to C++ but thats not what the API built for
no.. API is the way you talk to the engine via code
if you want to code C++ switch to unreal
//black the screen
mycanvas.enabled = true;
Anybody know why this canvas wont enable with code?
It's inactive and not necessarily disabled
there is no context
I'm basically trying to just 'check' this box to enable it
this is SetActive not .enabled
SetActive
I thought that but it wont accept SetActive
because it needs to be on a gameObject not a component
myComponent.gameObject.SetActive
That makes sense, thanks folks
np
Is therre a trick to getting videos to work?
Want a looping video as my 'main menu' background
But can't get it to show up at all
Ah my bad
I see the iissue
Is it possible to expose a vector2 to the editor with some kind of marker similar to exposing variables to the inspector. Like, could I, in a script without any additional addons or objects, when I place an object in a scene, have a marker pop up on the scene view that I can drag around that I can use to affect my code?
i think you'd need to use an #↕️┃editor-extensions. although im not 100% sure if you can do it without. i'd be interested in knowing if there's a way as well 👀
I know I can use another object in the scene and pull it's pos info to fill the vector2, but if there's a way to do it without adding an additional object to the scene, even if I remove it at runtime.
im not entirely sure myself. im interested in knowing aswell, i've never really tried.
until someone else answers though i think Gizmos or Handles might be a good place to try looking
ok so i looked into a bit myself and it seems like yeah, you cant do it without an editor extension.
good news it that the code is pretty short atleast
there's some example code in the unity docs
there's a lot of other useful handles here too. i somehow never knew these existed 
i believe that is the "or" operator
so, if either condition is true the code will run
"as well as" (usually called and) is written as &&
"instead of" (usually called not equal) is written as !=
Can you try this sentence again? Really not sure what you're asking.
(someone might need to correct me on whether its 1 or 2 of the symbol, i get that wrong pretty often)
I found it out
&& is "and"
|| is "or"
Both are valid and behave slightly differently in C#. The double symbols are so called "short circuiting" versions of the operators and are usually preferred.
as dev is one of the strongest tools to have..google search and documentation
probably lol
Guys i realized FixedUpdate is more smooth for WASD controls but space for jumping is not that smooth
Update is more smooth for Jumping
FixedUpdate shouldnt be used for inputs
Is it correct or am i wrong
It depends on what part of it exactly you're talking about.
If it's input querying, that should be in normal update.
I can share the code
!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 tool for sharing your source code with the world!
Space is not working well inside fixedupdate. Wasd worked well
held keys are acceptable but single frame event such as was pressed last frame cannot be caught easily in physics loop and go in Update
Hey i have a question, why i have to use a coroutine for the delays? Why dont make delays work naturally?
I mean cuz is very annoying to make a value timer and an inf scenario until is zero for make it, instead of just putting delay
Because whenever your code is running the entire game engine is patiently waiting for your code to finish running
How would it know when to stop and go render the next frame, for example?
I mean, why coroutines? Idk how to explain it
Wait, i think now makes sense
Like an action
A delay would pause the whole system
Meanwhile a coroutine is just, an action
But anyways, apart of coroutines, whats a simple way to make it wait?
Async
Huh?
Unity - Manual: Asynchronous programming with the Awaitable class https://share.google/i1XhUoJWqY44ZcNIb
Why i neveard heard of this?
I only read abt coroutines or value -= time.Deltatime
Ooof
When what is it?
Just coroutines and value -= time.deltaTime?
Idk, i just want a simple way to make sequences and stuff
coroutines are like fake async
O h
Ok
I mean cuz
I have a combo melee attack that instead of the normal melees that are a click, this one remains dangerous for a sec
How i can do so?
a timer?
Just the value thing?
i don't see the point of using async here
Is not bad, but my problem is im flooded with values
And hardcoding values i feel like i might repent
Yet that would clean stuff up
could you explain a bit more what you tried to do earlier? and whats happening instead / issue
Havent tested yet. But the thing is affected in an instant.
Im not at my pc currently
Later i will reply with the issue explained
Sorry;-;
Can I make new objects at runtime off of ISerializationCallbackReciever.OnAfterDeserialize? I know it’s an issue during onbefore, atleast in an editor context
Actually also curious what the order of execution is there, does awake run before that callback?
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
public class ScreenShake : MonoBehaviour
{
public float ShakeDuration = 0.5f;
public float Magnitude = 2f;
private Vector3 origPos;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
StartCoroutine(Shake());
}
}
IEnumerator Shake()
{
origPos = transform.position;
float elapsed = 0f;
while (elapsed < ShakeDuration)
{
float offsetX = Random.Range(-1, 1) * Magnitude;
float offsetY = Random.Range(-1, 1) * Magnitude;
transform.position = origPos + new Vector3(offsetX, offsetY, 0);
elapsed += Time.deltaTime;
yield return null;
}
transform.position = origPos;
}
}
``` how can i make the shake to the camera smoother
ignore the high magnitude i changed it
Getting an error saying "cannot declare public variable of static type 'Path', anyone know why? I'm following a tutorial line for line, shouldn't be any errors unless I missed something.
public class PathManipulatorTool : EditorTool
{
public override void OnToolGUI(EditorWindow window)
{
if(!(window is SceneView))
return;
foreach(var obj in targets)
{
if (!(obj is Path path))
continue;
for (int i = 0; i < path.NumberOfControlPoints; i++)
{
Vector2 point = path.GetControlPoint(i);
EditorGUI.BeginChangeCheck();
point = Handles.PositionHandle(point, quaternion.identity);
}
}
}
}```
The path class is static, meaning it can't have instances
If it's too choppy, maybe use Vector3.Lerp, but it'd require a bit more work due to how lerp functions: https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
thank you!! ill check it out
Thank you, gonna try googling to see what I can figure out based on that. Not sure what he was doing here that allowed him to write it like this that I missed.
Define smoother. As is, you're teleporting the position of the object every frame.
Perhaps select a new position every half second (500ms) and have your position move towards that point, if frequency and interpolation is the concern.
All that'd do would move the camera to one random pos, rather than smoothly shake it
Lower intervals so it shakes works though
Per half second whilst moving towards that point (a shake, perhaps)
No?
You're just saying move to one position
Not several
It wouldn't lead to the result that's wanted
chat, i copied this from 8 different youtube tutorials, and some tiktok
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public GameObject playerObject;
public float flapPower = 6.928f;
Rigidbody2D rb;
bool initialized = false;
int counter = 0;
List<string> debugMessages = new List<string>();
void Awake()
{
playerObject = GameObject.Find("bird");
if (playerObject != null)
{
rb = playerObject.GetComponent<Rigidbody2D>();
}
else
{
rb = GetComponent<Rigidbody2D>();
}
}
void Start()
{
StartCoroutine(StartLater());
}
IEnumerator StartLater()
{
yield return new WaitForSeconds(0.00001f);
initialized = true;
}
void Update()
{
counter++;
if (counter % 2 == 0 && initialized && Input.anyKey)
{
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButton(0) || Input.touchCount > 0)
{
Vector2 flap = new Vector2(Mathf.Sin(Time.time * 0.01f) * 0.001f, flapPower);
rb.velocity = new Vector2(0.00001f, 0.00001f);
StartCoroutine(ApplyForceNextFrame(flap));
}
}
}
IEnumerator ApplyForceNextFrame(Vector2 force)
{
yield return new WaitForEndOfFrame();
if (rb != null)
{
rb.AddForce(force / 1.000001f, ForceMode2D.Impulse);
}
}
}
is that good?
its kinda laggy tho
I would bet
You should learn for yourself and make it properly
A lot of free resources at !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
but its work
somehow
no its not good
I would do something like this, given the original:cs private Vector3 offset; public float speed = 5f; public float delay = 0.500f IEnumerator Shake() { origPos = transform.position; offset = Vector3.zero; var target = StartCoroutine(Target()); var move = StartCoroutine(MoveTowards()); yield return ShakeDuration; StopCoroutine(target); StopCoroutine(move); transform.position = origPos; } IEnumerator Target() { while(true) { offset.x = origPos.x + Random.Range(-1, 1) * Magnitude; offset.y = origPos.y + Random.Range(-1, 1) * Magnitude; yield reutrn delay; } } IEnumerator MoveTowards() { while(true) { transform.position = Vector3.MoveTowards(transform.position, offset, speed); yield return null; } }(no ide - errors may be present)
Errors are present, but that's a given, also your coroutines never break, they'll continue endlessly unless the object gets disabled, and that's terrible for performance as each time you shake the camera, you end up stacking another infinite loop on the pile, which will eventually cause massive lag
Now you stop them, ignore that, but still not a great way as it'd snap back to the start pos
Very overcomplicated in my opinion
i meant this, atleast for what i know it will only "hurt" whatever is inside the overlapbox when i click it after the cooldown, but for the AirSlash i want it to be like Kirby's sword airSlash, to wich has to hurt anything inside the overlapbox a little longer, like a sec, how i can do so?
void HandleValeriaMachete()
{
Vector3 mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousepos - transform.position;
machetepos.rotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg));
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
machetepos.position = transform.position + Quaternion.Euler(0, 0, angle) * new Vector3(machetedistance, 0, 0);
machete_swingTimer -= Time.deltaTime;
if (Input.GetMouseButtonDown(1) && machete_swingTimer <= 0)
{
machete_swingTimer = machete_swingSpeed;
if (isDashing)
{
currentStyle = meeleStyle.DashSlash;
}
else if (!valeriaTocoPasto())
{
currentStyle = meeleStyle.AirSlash;
}
else
{
currentStyle = meeleStyle.Combo;
}
switch (currentStyle)
{
case meeleStyle.Combo:
MeleeAttack(machetepos, attackRange, meleeDamage);
break;
case meeleStyle.AirSlash:
MeleeAttack(transform, attackRange + 5, meleeDamage + 1);
break;
case meeleStyle.DashSlash:
MeleeAttack(machetepos, attackRange, meleeDamage + 3);
rb2D.linearVelocity = new Vector2(valeriaMove * dashSpeed, rb2D.linearVelocity.y);
break;
}
}
}```
in airSlash the player does a spinning animation, how i can make it that it hurts anything that touches it (the function remains) until it ends?
simplest way you could probably activate a bool and run the function in update or coroutine , use either Animation events for start/end or animator enter/exit state , maybe even checking the name of clip/state playing
You don't have to use animation at all, you can also base it on specific time of effect
time of effect?
timer i guess
oh! ok, thanks :3
hey also, how i can make a movement burst?
i mean, i tried to make a dash system for my player, but instead of making it dash, it makes it sprint
void ValeriaMovement()
{
if (Input.GetKey("d") || Input.GetKey("right"))
{
valeriaMove = 1f;
}
else if (Input.GetKey("a") || Input.GetKey("left"))
{
valeriaMove = -1f;
}
else
{
valeriaMove = 0f;
}
dashTime = Mathf.Max(dashTime - Time.deltaTime, 0f);
if (Input.GetKey(KeyCode.LeftShift) && valeriaMove != 0)
{
if (dashTime <= 0)
{
dashTime = dashCooldown;
dashTimer = dashDuration;
isDashing = true;
spriteRenderer.color = Color.cyan;
rb2D.linearVelocity = new Vector2(valeriaMove * dashSpeed, rb2D.linearVelocity.y);
return;
}
}
else
{
rb2D.linearVelocity = new Vector2(valeriaMove * runSpeed, rb2D.linearVelocity.y);
}
if (isDashing)
{
dashTimer -= Time.deltaTime;
if (dashTimer <= 0f)
{
spriteRenderer.color = Color.white;
isDashing = false;
}
}
}```
what im doing wrong?
the dash code and the move look the same
also there are many different types of dash you can do, freeform, specific distance, specific amount of time, etc
huh? how each one works? Im just trying to make the basic, Hollow Knight-like
i just need it to burst movement to the side the key is pressed
you tried just doing an AddForce Impulse for starters?
thats the freeform version more or less
i heard AddForce relies on friction so thats why im using linearVelocity
you could probably do a float.movetowrds or something during a coroutine
honestly i thought linearVelocity moved the player to the direction + the speed of the value like a burst, and yet is in fixedUpdate, it would be infinetly making it look like is walking...but since i tested this..something weird happened
like, doesnt dash well
huh? how?
or maybe i should just use AddForce
idk, im just trying to make it the most simple yet efficient posible
there isn't a methodology set in stone, you have to do what feels right/proper for your project
lookup a few dashes and how others do it then see whatever you can make your own out of it
each one has its own pros and cons
think most recent I did was a specific amount of time, but with that you would need to stop it at a wall with rays..so you don't feel stuck cause its still dashing into a wall..
oh
also, is there a way to make addforces dont use frictions?
not addforce specifically but you can put a no friction material on the collider
that can also be swapped at runtime
oh!
hey, what about using
rb.linearVelocity = transform.right * dashSpeed;
its better than using addforce or worse?
nvm doesnt works either
I mean it would work but you would probably make it feel nicer by smoothing out a speed value using a curve or some lerping
idk man, it just doesnt dash for now
i think the problem is something else
i dont know what
but something
or might be the return value?
you haven't explained whats happening so i have no idea lol
it doesnt dash
doesnt move
just...walks
when the if is shaped like this
if (dashTime <= 0)```
it works like a sprint
when is shaped like this
``` if (Input.GetKey(KeyCode.LeftShift) && valeriaMove != 0 && dashTime <= 0)
``` it doesnt dash
what im doing wrong?
these are pretty much the same thing, though depends what other code you put outside the dashTime check
whole script
{
if (Input.GetKey("d") || Input.GetKey("right"))
{
valeriaMove = 1f;
}
else if (Input.GetKey("a") || Input.GetKey("left"))
{
valeriaMove = -1f;
}
else
{
valeriaMove = 0f;
}
dashTime = Mathf.Max(dashTime - Time.deltaTime, 0f);
if (Input.GetKey(KeyCode.LeftShift) && valeriaMove != 0 && dashTime <= 0)
{
dashTime = dashCooldown;
dashTimer = dashDuration;
isDashing = true;
spriteRenderer.color = Color.cyan;
if (Input.GetKey("d") || Input.GetKey("right"))
{
rb2D.linearVelocity = transform.right * dashSpeed;
}
else if (Input.GetKey("a") || Input.GetKey("left"))
{
rb2D.linearVelocity = -transform.right * dashSpeed;
}
return;
}
else
{
rb2D.linearVelocity = new Vector2(valeriaMove * runSpeed, rb2D.linearVelocity.y);
}
if (isDashing)
{
dashTimer -= Time.deltaTime;
if (dashTimer <= 0f)
{
spriteRenderer.color = Color.white;
isDashing = false;
}
}```
dash is a quick burst of speed, you're coding it like a sprint
when what i should do
make a coroutine for it first of all so its not a crammed mess
lerps are cool too.. or MoveTowards
i mean, how that would look like, idk im just trying to make it the simpliest posible for now, enchancement later
MoveTowards for the value that is
how
start it to at give it a burst of speed (maximum) and Movetowards it down to zero) that being the value being a added on ur rigidbodies vel
huh
could also use AnimationCurve to switch up the easing / burst speeds
how that works
finalVelocity = moveInput * runSpeed + dashVelocity;
then when u engage dash() dashVelocity = Mathf.MoveTowards(dashVelocity, 0, dashDecay * Time.deltaTime);
i got lost
i sometimes call it 'damp'
okay... assume ur logic is.. (if were pressing wasd we just moving..
What you mean coroutine?
You mean make it go for the linearvelocity for an specific amount of time?
basically.. itd be kinda doing the same thing.. dampening a value that ur using to be an extra force on ur rigidbody
the rigidbody movement still happening in the fixedupdate
it depends on what kinda dash u want..
if u do a coroutine u'd basically be turning isDashing boolean or something on.. then waiting and then turning it off
there would be two options here... 1 would be a dash that starts strong.. and then decays (a movetowards or lerp in a loop)
or.. it'd be a dash that just gives u extra power for a certain length of time
Coroutine for running some code while an action is happening.. its just like another update loop basically or could be a fixed if yeilding fixedupdate
Huh? Idk i just want a simple dash i can understand, doesnt matter how it goes
I want it to quickly move to the key i pressed, like a lil push
Lil explosion
I mean
Is like walking but automatically?
IEnumerator Dash()
{
isDashing = true;
rb2D.velocity = new Vector2(facingDir * dashSpeed, 0);
yield return new WaitForSeconds(dashDuration);
isDashing = false;
}```
this would be an example coroutine
So it looks like a dash
Id use a while loop inside of it and do the burst in there with a curve modifying the speed
And without coroutines?
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftShift) && dashVelocity == 0)
{
dashVelocity = dashStartSpeed;
}
}
void FixedUpdate()
{
// Regular move + dash push
float move = Input.GetAxisRaw("Horizontal");
float finalX = (move * runSpeed) + dashVelocity; // **note the + dashVelocity.. if its 0 then it doesnt affect ur speed.. but when u dash it starts strong.. and then lowers back to 0
rb2D.velocity = new Vector2(finalX, rb2D.velocity.y);
// Smoothly decay the dash velocity
dashVelocity = Mathf.MoveTowards(dashVelocity, 0f, dashDecayRate * Time.fixedDeltaTime); // **because of this
}```
ofc with linearVelocity instead of velocity..
u could watch the additional dashVelocity starts at like 5... and then go down towards 0.. by w/e speed u want..
This is my logic btw
I guess this is simplier, isnt?
Without a coroutine, you'd have to manage your states to avoid operating certain lines codes during certain scenarios. If it's not too complicated, a timer or whatnot would suffice. Else, I pray for whoever has got to read the code in the far-near future 
Coroutines then
Well, i think this method works best
thanks
Starting and Stopping coroutines have some cost but likely it isn't going to be a game changer
Cost?
for a coroutine ud also probably want to countdown a cooldown timer for the dash
so u cant accidently spam it
I did research abt which method should i put my controls in. They say i should put input requests in update() and physics in fixedupdate() is it true? Or should i put every control inside update() and i didnt understand what if i dont use fixedUpdate for my controls. Its just WASD and Space to jump. Im just practicing.
Yeah, the initial cost but likely it'll not be your limiting factor
you'll probably end up with many coroutines in ur game.
if ur doing sequential stuff based off of any kind of timer ull have to use one
unless ur a wizard coder and can do it some other way..
Well, input definitely shouldn't be polled in Fixed Update as multiple fixed update calls can occur or simply not occur at all (relative to per regular update - frame)
So i need to put input requests in update and physics in fixedupdate
Im just trying to learn logic behind all of this
Some physics members can operate in regular Update like modifying the velocity property, adding force as impulse and whatnot but more often than not, Fixed Update is where physics operations that need to be synced should operate.
Okay thank you
A tool for sharing your source code with the world!
I wrote everuthing inside fixedupdate now i need to seperate physics and input request.
and you never use * Time.deltaTime inside addforce or .velocity
Thanks
As u can see. I wrote diffetent line for each key. Wasd. I wonder if there is more efficien way.
yes using Action map . either with events or using the Messages. with 2d composite
u can.. but u wouldnt want to
then ud have to be running both systems
use a 2d composite input
from the action map!*****
Where is action map. Im beginner i dont know
it looks like this in the project window
with w/e its named in urs or w/e u named it since u said ur using it
^ bam
Thanks
is it normal that i dont understand when i read this stuff
for example it says it uses same approach for keyboard but i didnt understand it
how can i make it
this is just one example not really relevant to what i mentioned, read the rest
its literally explaining the same exact thing in your code Keyboard.current.spaceKey.
Keyboard is a an inputDevice it mentiones it there
This only happens when I introduced reloading within the game
the dreaded object reference not set to an instance of an object
yea, but I'm pretty sure I do have an input mapping assigned to it
Can the player start disabled?
no, I do have a script that disable the player controller script, but it has no mentions of the input mapping
public static void Add<T>(this T[] array, T value)
{
array = new List<T>(array) { value }.ToArray();
}
can i do this or can i not reinitialize myself via extension like this
I coul pastebin rq if you wanna see the code
Okay, but if it starts disabled then Start won't be called, and when OnDestroy is called the input mapping was never created
You can fix this by just adding one questionmark anyway, it's so minor.
_inputActions?.Dispose();
it would have to pass by reference
Yeah ok, no dice doing that neatly in a extension yeah? Worstcase can chuck it in my utils
Just use ref
Looks like extension methods for classes don't support ref 🤔 I seem to be mistaken
thanks this did the trick
But I have another question, when I paused the game, I could not interact with the ui on the screen
Do I need to disable my current input mapping for the EventSystem to kick in?
Since EventSystem uses a different Input actions asset
I don't believe so
When I pause the game I could not interact with my ui
I'm wondering if any scripts could make this a problem
I'd check all the basics https://unity.huh.how/ugui/input-issues
I believe if you just did:
Array.Copy(
sourceArray: array,
destinationArray: array,
length: array.Length + 1
);
array[^1] = value;
it would work without any issues
Wait in the context of an extension?
w/o ref?
your righttttt just not easy for me to do that rn
lemme go do it
doesn't seem like raycasting works at all
I've checked that I've toggled all raycasting on
I think that's just all it shows with the input system annoyingly. I've absolutely no idea why
but for some magical reason, when I disable my player, it works
how
oh nvm I solved it
this was blocking my ui elements
It's weird how you can remove from an array using that syntax, I suppose it's because it's safe to reduce its length but there's no space to allocate more
Oh no, I'm mistaken, someone on my project just has a dumb API lol
their API doesn't resize the array at all 😆
i think i keep using a array indexof extension from a random unity input module lmao
we love random extensions
Should i care abt efficent code even tho it works fine
Only when it becomes problematic where it effects the quality/performance of your game . . .
in the beginning i'd worry more about code readability
its always fun when you come back to a script after 1 week and you dont remember anything you wrote
hello, FACING CRASH ON ANDROID com.unity3d.player.UnityPlayerActivity.onCreate,
ANR ON ANDROID [libc.so] __futex_wait_ex
anyone have idea about these?
heyo
just joined for some more insight
i just started with unity but i have worked with c++/c#/python before for years
i was wondering, i'm am developing an app and for ease of maintainibility the ui is all in c# but still using uitoolkit, so i can avoid the string look-up part for elements which could easily become un-manageable since it's based on string ids
how could i approach mouse over events for elements like foldouts?
just looking for general guidance, since i'm not sure if i should go with a custom foldout class or there is a build in method that google didn't show
do i really have to check if key down every frame?
is there any signal based approach to inputs
The new input system offers event based workflows
alright thank you ill look into it
What is that mean
oh i thought since i'm coding it and uitoolkit was in the artist tab it would not have fitted the channel
will move my message there, thank you 
You're definitely on a smart path — keeping everything in C# for UI Toolkit is a great move for maintainability and avoiding messy string-based queries.
For mouse-over events like hover detection on elements such as Foldout, you can use the built-in UI Toolkit event system — specifically:
foldout.RegisterCallback<PointerEnterEvent>(evt => {
Debug.Log("Mouse entered");
});
foldout.RegisterCallback<PointerLeaveEvent>(evt => {
Debug.Log("Mouse left");
});
This works with any VisualElement, including Foldout. If you're planning to reuse this logic or apply custom behavior, creating a subclass like CustomFoldout or HoverableFoldout is totally valid and clean.
oh thank you i didn't know ui toolkit had callbacks
that's perfect, it's just the early stages of the ui, might refactor into a custom class later but for now this is perfect
learnt my lesson with html using string queries for ui, never again lol
thank you again 
You're very welcome! Glad to hear it's working out for you so far and yep, callbacks in the UI toolkit can really streamline things early on. Refactoring into a custom class later sounds like a solid plan too once things get more complex.
And absolutely feel you on the HTML pain — string queries for UI elements can be a nightmare to maintain. You're definitely not alone there!
If you need help later when you start that refactor (or anything else), feel free to reach out. Good luck with the build! 🚀
yeah for now i'm doing on-the-fly prototyping, it's for a modeling software so starting now would be a pretty bad idea as much as using string queries for this
will reach out if i do thank you
How do I toggle checklist tick when snapping object
sorry for the ping again, for some reason it's not working again 🫠
What's the current error?
How's the script look like now?
I haven't made any modifications to the player script, but it still yielded the same error when i pressed restart
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Resume();
}```
i get the same error when I exit to main menu, looks like OnDestroy isn't triggered
but normally when you exit to another scene you will destory all current GOs
What is a PlayerInputActions? The new Unity Input Actions?
Are you disabling the input action at all?
no, I just dispose it on destroy
{
_inputActions?.Dispose();
}```
oh nvm i just disable it before disposing it and that seems to fix the issue
unity doesn't like it when I just straight up dispose it i assume
Could it perhaps, not have been destroyed because the reference was null?
I assume so yea, but wouldn't you always have a input system of some sort at play at any time?
The null conditional check would only hide the problem if you're actually not properly disposing of resources. The error seems to be informing you that you haven't disposed of the input actions.
out of curiousity, do you need to explicitly set _inputActions to null there or does the dispose do it cleanly (re: using the ?)
Is the variable being set to null somewhere?
Might be misunderstanding dispose in this context, if that's the case don't worry about that question 😄
Dispose seems to do it cleanly, once I disable it, leave the scene and return to the scene everything looks fine
Where do you assign _inputActions it's reference?
I don't think so, there's only one set of input actions enabled on void Start()
whenever you make the mapping, the script (and the class) is made
so there should only be one instance
Sorry to reply so late, but with what you specificly meant cost?
operational cost i assume, taxing on computing power
since coroutines is async
performance cost
fakesync
There's a tiny bit of processing power used to execute some code under the hood that manages the coroutine.
ic
Really only matters at like notable scale afaik
As long as they aren't starting thousands of coroutines per frame, they should be okay.
Can you show your Start method?
How are you assigning _inputActions it's value/reference, through the scene-inspector?
no, it's private, you don't need to assign it
As is, I'm assuming it's null and _inputActions?.Dispose() gets ignored thus not throwing an NRE but still throwing a memory leak error.
It's null by default so you have definitely got to be assigning it somewhere through code as it's a reference type.
private CameraInput cameraInput;
void Start()
{
playerCharacter.Initialize();
playerCamera.Initialize(playerCharacter.GetCameraTarget());
_inputActions = new PlayerInputActions();
_inputActions.Enable();
}```
Okay, so you've assigned it in Start
Are you assigning _inputActions a different value anywhere?
nope, not that I know of
Are you able to share the script so that we can check? !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 tool for sharing your source code with the world!
Looks like you've got some compilation errors (line 77 ;)
If the script isn't being compiled because of compilation errors, you may be getting errors that aren't up-to-date.
Only you would know (visible console errors)
No, empty statements are valid
doesn't pop up
I mean it did pop up a while ago but didn't seem to have trouble now
I'm not certain then as _inputActions is a private member and not re-assigning it's value anywhere other than in Start
Gameplay is referenced in Update but you aren't really doing anything dangerous with it that I'm aware of.
I would breakpoint inside the Enabled function and make sure all the calls are coming from what you expect
Hi! I have been working on c# for a while. I am still a beginner, have learnt the basics but now want to switch to unity mobile game development. All tutorials I found are usually "this is how I did x,y,z" rather than "this x and this is how it works" and etc. They are not exactly helpful or teaching, is there any tutorials I could use to start off of?
Currently I am mainly lacking knowledge about mobile input
(FYI I finished the whole w3schools tutorials and did a few projects to properly learn and practice the skills)
!learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Unity Learn and guides in the Unity manual should be the first place to look really.
But in theory is still better than the value -= time.deltaTime?
how many people uses coroutines oftenly? idk, it is a good idea?
Just use what's readable and what your partners are comfortable with. Realistically, you'd use the profiler to optimize the game - if necessary.
You've asked this question before for something else. Use a timer, not a coroutine, for things that are happening which can be interrupted or modified midway.
A dash is exactly something that can be interrupted or modified.
but i dont need it for the dash anymore
i need it for something else, to make the melee attack last longer than a click
[Whatever it is you're using it for] if it can be interrupted or modified in any way.
coroutines can be interrupted too
wdym better, "faster"? it literally does not make a difference
They're a hassle to maintain
use something that's readable and works, and hopefully generalizable
i never wrote faster, if i did, im sorry i may confused
it's not too bad tbh. i do it
neither is "better" overall
ok
this describes my entire developing experience
in fact there isn't even really a clear line between coroutines and counting deltaTime lol
you can count deltaTime in a coroutine as well
huh
idk for now, i want it to make anything inside the overlapbox to get damaged more than one click
i mean, constantly?
For minor stuff, I think if-statements are fine. I'm not too fond of coroutines as they seem a bit unnecessary but my nested timers and conditional branches with large compound conditions (states) quickly become ugly. The ease of helping folks on the Unity Discord platform without having to directly maintain (maintaining isn't a bad thing, if you've got the resolve and time) states has made me use coroutines often when helping others. Other than that, if the task is super simple a timer would be more than adequate. My opinion.
multiple things?
@acoustic belfry
If you want my 2 cents, use timestamps with Timer.Time (the page has a good example). Works for plenty of logic and is very scalable for whatever you might want to hook onto it. I understand you want a dashing mechanic, so you could use an "Dash end timestamp" and from there your code can apply force and effects based on the time before the dash ends.
ooh seems interesting
idk i just need the AirSlash and DashSlash (preferible AirSlash) to wait a lil longer before dissapearing
{
machete_swingTimer = machete_swingSpeed;
if (isDashing)
{
currentStyle = meeleStyle.DashSlash;
}
else if (!valeriaTocoPasto())
{
currentStyle = meeleStyle.AirSlash;
}
else
{
currentStyle = meeleStyle.Combo;
}
switch (currentStyle)
{
case meeleStyle.Combo:
MeleeAttack(machetepos, attackRange, attackRange, meleeDamage);
break;
case meeleStyle.AirSlash:
MeleeAttack(transform, attackRange, attackRange, meleeDamage + 2);
break;
case meeleStyle.DashSlash:
MeleeAttack(transform, attackRange * 2, attackRange, meleeDamage + 3);
if (valeriaMove != 0)
{
rb2D.linearVelocity = new Vector2(valeriaMove * dashSpeed * 2f, 0f);
}
break;
}
}```
animation events are also a thing
my og structure idea was to burn them, until i realized that for each animation event i would need a function, wich would be...lame
btw is there a way to use the events without functions?
probably with some manual checking but it'd be way harder
oof
but how would that go?
an event to activate and an event to clean up
that's my setup
but whether that works for you depends on how you want it to work, which i have no idea of right now
you mean booleans?
whatever it needs to
there's a ton of ways to do this
you're asking like there's only one correct way lmao
this is something you need to design
when a function is called how can i make it so that something starts happening every frame
Set some bool value to true and check that in Update.
If you want something to happen every frame, put it in update
but if i wanted to do this 10000 times i would be checking 10000 bools every frame?
You would check 1 bool, each frame, for 10000 frames.
If you're implying that that's going to be a performance issue, it won't.
If you have 10,000 objects all running update methods, that is your problem. Not the presence of a single CPU cycle of checking a boolean
sorry ive not worded clearly what i mean