#archived-code-general
1 messages ยท Page 265 of 1
Okay, but I don't know where it is trying to access it
I told you to debug the value of that variable.
oh like in vs
You'd check the script that is throwing the error
I tried
We don't know how you're handling null references
it showed me this
Then you didn't read the troubleshooting steps
I double-clicked it, and it took me here:
Does anyone else have the problem where you cant drag the stuff in the scene samples? Im new to unity so i dont know if its my fault
That isn't your code
I know
That's not referring to your code, so it's not an issue with your code
Then how should I fix it?
Clear the error and move on with your life
post that in unity talk or a channel not on code
And try not to do the thing that caused it unless you want to see the error again
oh mb
You did not make that script so you aren't able to fix that error. It's a false positive btw. @potent jackal
When I start the game, it shows again
It's a false positive...
So it's not a problem
Hello there. I'd like to ask which naming conventions are the best for classes, filenames, variables, you get it.
The C# naming conventions are pinned to this channel
I seem to prefer GameMaker naming conventions, but i dont see anyone using them in unity at all
For example, should i name my stuff scrPlayerMovement objPlayer mapGround animRun etc?
Unity is a considerably more open framework than gamemaker so it is unlikely for someone to figure out a widely adopted convention
That said, there are conventions in use for specific types of projects, but most are only used by a relatively small subset of developers
it very much depends on the projectโs architecture
What on earth is scr
script
Write full words
People generally prefer the first thing they use, dont be afraid of change. You'll find that a majority of unity developers will follow the c# convention from the Microsoft docs... because we use c#
Unless they think that convention needs fixing ๐คช
Common sense ends when it comes to code conventions
As long as the individual or team understands that it's all about preference instead of maintainability and whatever other jargon managers use these days.
Are you referring to naming the references in code or resources in the asset folder?
both actually
Anyway, I believe whatever one uses, it should suit the framework/engine/workflow and architecture, copying a convention targeting a different toolchain is generally not helpful
but ill just go with the official one i guess
For interfaces you add an I in front such as: IActivate
Abstract classes people like to use a keyword like Base: BaseAbility
For data classes, I usually like to add Data as a keyword, but since scriptableobjects are a thing I usually tack on SO: ItemSO
I use a Behaviour suffix for MonoBehaviours, but that's generally picked up from doing ECS
out of then millions of channels, where may i ask about rigidbody
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://paste.ofcode.org/MGMuUEVhcTsWFGuzzttSZ2
is there something fundamentally wrong with my ontrigger and collider stuff at the bottom? it only debugs "Collision with non-fish collider" and "Collision Detected"
posted here to not crowd the beginner chat..
log what it actually collides with
I've been trying to find a good way to store dialogue text efficiently, without these weird ui extensions. Is it really good practice to have all my dialogue loaded from start, if i had a ton of text(Scriptable Object)?
store them in json files
I wanted to make an inventory that has inventoryslots and which can have different content of different classes. I made a generic approach but find it a bad approach because a InventorySlot depends on other Monobehaviours. I have to create many classes which have to be derived with its type in order to put them in a gameobject. Because of that i end up having multiple empty classes.
Another idea would be to use interfaces instead. Any other idea?
{
private SlotUI<T> slotUI;
private T content;
I've tried that approach but eventually ran into a lot more issues. If you're only going to have a handful of types (weapons/armor/items/skill) I'd suggest just do comparisons
can have a single slot class, and then use managers to decide what can go into them.
HotbarManager, InventoryManager, EquipManager
oh yeah and you'd want a single type that all of these contents derive from
you can also implement behaviours at the base level like Use() where you don't need the know the type
unless there's targeting specifics, then you'd have to check for that
you can use interfaces like public interface Item instead
I already do that. With my question i meant how content from InventorySlot can hold different e.g. Controllers. I have an Inventory for Items and Inventory for collected Mobs. One has a ItemController and the other a MobController. Now with my Generic approach its very annoying that I have to derive from InventorySlot and create one for Item and Mobs which are empty in order to use them in Gameobjects. I think I will use Interfaces instead and Cast them to the needed objects.
my issue with generic slots is I eventually ran into a case where I needed to use covariance
which turned into me having to use interfaces anyway
i thought we could cast base classes to derived class if we want
you can, and that's my implementation of it up there
pass stuff around as the base type, but check for a more derived version when inserting into other slots
https://gdl.space/ovayequjun.cs why do my pins get stuck? The pin movement script is attached
if you're using chatgpt here I'm not going to debug it for ya.
otherwise tell me the exact methods that you're having trouble with and what you expect them to do
I set up a method where one pin should open depending on what key you press the right pin or the left one. The space button to reset I made it for when the pins gets stuck. Sometimes when you press a or d the pin gets stuck in the open position aka targetrotation
why is my navmeshagent not moving smoothly? i'm using the new navmesh
Edit: the problem appears to be in my enemy, i added a navmeshagent on a capsule and it's not laggy
Edit: the problem was caused by a RigidBody component
is there any way to know if an object is being destroyed? checking if null still returns the object if done after the destroy call was made but before the end of the update loop
how are you checking if null?
try contributor.gameObject == null. That should work
will do, thanks
a and b are arrays. When I do 'a = b' and make a change in b with the code, the same change happens in a. When I make a change in b with the code, I do not want the change to be in a as well. How can I fix this?
you need to make a copy not a reference
I've got another one. Can i read only a few lines of a json file, without loading the entire json into memory just to get these few lines?
Unity3D
no
So im back at the question what the most efficient dialogue system is then
database
ah
Your game won't have that much dialogue that reading it all into memory would be a problem
had to the component then the gameobject cause sometimes contributor is in fact null therefore errors when asked for its gameobject
still seems to return not null tho
I'm under the impression unity actually delays destroying objects for real when not using destroyimmediate but it's also not recommended
that's odd because the equality operator is specifically overriden to include an object pending destruction test
true, until end of frame
I saw a post about that but it's from 2014 so maybe that's not the case anymore?
I can always manually set a bool on the object to "pendingDestruction" on disable or something but if there's a cleaner way that'd be nice
which is why gameObject? and gameObject == will return different things
does gameObject? return the "correct" unmodified result of a null check? as in without unity's additional test
? is the pure c# method. So gameobject exists in C# so will return not null
even if marked as destroyed in Unity
ah
if == null is not returning correctly for you then I suspect that your Destroy is incorrect
also I just saw onDisable/Destroy are only ever called at the end of the frame so the component can't even manage that itself
oviously contributor cannot check itself for null, that would make no sense
this is the function that calls destroy
onShapeListUpdated then calls some other function which then calls the function that does the null check
have you debugged it? is destroy being callled?
I mean had the existing callback happened right on the destroy call rather than the end of the frame it wouldve been ok
yes, that object is then visibly destroyed in editor, which then causes errors with other components that reference it
the null check in response to onShapeListUpdated was meant to address that
destroy is called, the null check still passes, then next frame I immediately get an error from another component that previously referenced it, and wouldn't have if the null check worked
maybe the check would work if it was from another update call entirely (ie another component's update, still in the same frame but executed after the one that led to RemoveShape) & it's like some uncovered edge case
are you sure the onShapeListUpdated is being called because that is a silent fail
yes, I modified the null check to print with the object name if not null, hold on
& then on the next frame
that 2nd function is called by a function subscribed to onShapeListUpdated
didn't include it in the screenshot but that "on shape list updated editor" print is right after the other 2
so is contributor from the first method the same as _selectedContributor from the last?
yup
sure?. debug it
there's no other gameobject with that name
debug.log the GetInstanceID from both objects
okay
maybe getting the gameobject through the component instead of already holding a direct ref to the gameobject screws with the check?
would be nice if there was just a pendingDestruction bool or something else that's more explicit in general
Does anyone know what the problem here could be?
I have a OnCollisionStay void but it never gets triggered. I tried it with rigidbody hits rigidbody, and also rigidbody hits non rigidbody collider
I can understand contributor not being null because that would really screw the background processes but a direct check on the gameobject should return null
I'm trying to get the gameobject in a variable then check the variable instead rn
post screenshots of inspectors and code
didn't work either
one last thing is that the function calling removeshape is called from a ContextMenu function
maybe this also screws with the check indirectly because of "out of game loop" jank?
you have an OnCollisionStay method that returns void (:
OnCollisionStay is not "a void"
maybe add a bool isDestroyed parameter to onShapeListUpdated
https://unity.huh.how/physics-messages
This walks you through the possible problems.
I want to cleanup my spaghetti code a little: currently on my player class I have a "Throwing" monobehaviour which if the player has a throwable object picked up handles the input and animates the player to throw the object. It also handles the animations and inputs for melee actions AND the animations and actions for when the player is empty handed.
Can anyone suggest how to structure my player code? should the various interactions be separate monobehaviours? should they be enabled / disabled based on what the picked up (in hand) item supports? maybe the item should add a component to the player? or the item itself should get a reference to the input and player animator?
I feel so lost in unity in situations like that and I fear there's some expected layout I should follow to get the most out of unity.
I'm just gonna have the removeshape function set a pendingDestroy bool on the component I think
and later down the line have a dedicated action for shape removal
still weird
indeed, sorry to have not been more help
all good
whats your Unity version b.t.w.
2023.2.5f1
ah, 2023, I might have guessed, not a good choice
unstable?
very
whats new in UIToolkit that is not in 2022 LTS?
I don't remember it's been a while
actually might've been because the gif recorder package thingy wasn't working
regardless this project's nearly done anyway I'm not gonna bother rolling back versions
I dont remember reading anything that made me think, 'Oh, this is worth enduring the pain'
I didn't know pain would be involved
with Unity, Always!
with most game dev software over the past 5 years in general it'd seem
even their early LTS releases are crap, none LTS, forget it
LTS means that they'll support it for a long time
it doesn't mean it'll work right (:
It means Unity thinks it will work right
but wtf do they know?
they never test anything anyway
adopting the widespread industry practice of pretending QA doesn't exist
nah, DevOps and Unit Testing, the bane of my life
Does anyone know a simple Enemy and Damage/health script for a simple horror game really right now i just need a bean to kill my player
tried google
no help
i doubt that. there are probably hundreds of tutorials for collision detection/damage/whatever
about the 20 ive tried dont work
ok the manual pendingDestroy bool is currently good enough
did you check how they worked internally & why they might fail
mhm
in what way do they not work
pretty sure !learn has something that would fit
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
and if you truly have done 20 tutorials for it, then surely by now you'd have some inkling of how to actually accomplish what you want
nah, copy/paste
bean no move and no damage
yeah because you did it wrong. pay attention to the tutorials you follow
if you have time to copy paste 20 different scripts you probably have time to read through the code of just 1
i have
link me literally any tutorial on the subject that doesn't work
it sounds like you've just blindly copy-pasted random code and given up the moment it didn't do exactly what you wanted
this attitude will not serve you well
yeah google code isn't ever going to just work on its own, especially when you don't yet understand what it needs to work
You could try looking into state machines, its often used for simple AI but can also be used for managing player logic too, one advice I was given a while back as well is that it can help to pass references to the objects you need, a regular class that doesnt derive from MonoBehaviour or anything, can be serialized and show up in the inspector to set references, that as well, could be a base class for similar "states" or its own independent/unique state - your player controller mono behavior can then manage all those states and add/remove them as needed, if those states are things that exist in the world (such as shooting weapons only if you have a weapon "in hand"), that weapon itself can be a mono and referenced in your player controller, or you can make a "input manager" you attach to your player object that can sub/unsub the weapon - this way if you have 2 weapons in your scene for example, the weapon itself just handles "shooting" but no input, since both weapons would always shoot otherwise
Ah, yes, he missed the magic 'Make this do exactly what I want' button which is included in all tutotials
you can only brute force your way out of having to learn programming for so long
I was working on a system yesterday that batches up raycast requests and runs a big raycast command as a job, then distributes the results on the next frame
What a fool I was for not simply clicking the "Make game faster" button
you wait until you find the hidden 'Make Game Even Faster' button
i did that by turning off the camera
way to break literally everything
that just makes the game run even faster
the only thing it makes faster is me, running for the door
what's the proper way to add nuget packages to my unity project? 
I've tried dotnet add MyProject.csproj package PackageName but it seems like every time I restart unity, the manifest.json file no longer holds a reference to the package or maybe it happens when i restart my pc; I haven't tested the exact cause.
unity projects do not officially support nuget yet.
you'd typically use something like NuGetForUnity or UnityNuGet
i personally use the latter since it's just right in the package manager rather than a separate window
oh, neat, I didn't know about the second one
i will check that out
is there some kind of existing system for pausing the game in unity now or do you still have to have some bool/callback somewhere that all your game systems check/react to for pausing/unpausing & that you have to manage yourself
reducing time scale won't be enough for my needs
nothing built in, but it's fairly trivial to create your own PauseManager class with an event that is invoked when you pause/unpause so other objects can react to it
thank you
Say I want to make a card deck which has 2 features:
Shuffling all the cards in it
Taking a card out
What's the best data structure for this? Is it just a list?
How do i make any gameobject instantiated from default tiles to save changes made to them during edit mode? I am able to instantiate gameobject using tiles in the tilemap and rotate them using "GetInstantiatedObject(position)" but when i go into play mode those changes are neglected, i think it is because it re-instatiates the gameobject and thus removes any changes made to it. I though of instantiating them using the prefab itself but i heard that it would be less performant, especially when dealing with a large amount of gameobjects which is the case.
A list is fine
the most efficient way is to treat the last element as the "top" of the deck
For shuffling here's an extension method I adapted to Unity for a fisher-yates shuffle:
https://github.com/jschiff/unity-extensions/blob/338d306ba17f86efa7beea1618ef486132e42720/Runtime/Extensions/CollectionExtensions.cs#L91
anyone know why my Enemy AI floats when chasing my Player ๐
Not without more information.
How do you move the enemy?
just a simple chase and kill script and when im in the distance to start the chase he floats and chases me
Well of course it's a script, but that doesn't really tell me anything.
HOW does the enemy move?
Is it a navmesh, using transform, using rigidbody?
Just show the !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
new to unity sorry i dont know to much
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
im confused on how to do that i have it in a hastebin thing
need nitro to post the actual code
https://hastebin.com/share/uruvoticap.csharp
Your enemy is probably floating because it has a different y position than your player does. So when you do this:
Vector3 direction = (player.position - transform.position).normalized;
// move the enemy towards the player
transform.position += direction * moveSpeed * Time.deltaTime;```
it's moving up towards your player's y position
what you want to do is project your direction on the x/z plane so there's no vertical motion:
Vector3 direction = player.position - transform.position;
direction = Vector3.ProjectOnPlane(direction, Vector3.up).normalized;
// move the enemy towards the player
transform.position += direction * moveSpeed * Time.deltaTime;```
do i just copy and paste that?
Use your brain
I say always type it in
Your !ide is not configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
k i did all that jittery joo jah
what errors? Where?
might be blind
seems pretty self explanatory
and has nothing to do with the code I shared with you
do what it says
You have another copy of this script in your scene somewhere
on that other copy, the variable is not assigned
yup im official slow in the head
now he just goes inside my player and does nothing besides follow
What do you expect him to do and why?
kill my player
And do you have any code that should make that happen?
yea its in the same code
So start debugging
if (distance < deathRange)
{
// loads the active scene
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}```
Add logs here
make sure this is actually running and it's actually going inside the if statement
And that deathRange and distance are what you expect
thank you alot sorry for my low capability in the brain its all working now lmao thanks alot
you should probably go over some programming fundamentals
unity has some official tutorials on that iirc
made a big mesh, gives me very low fps, is there a better way to do this
is there a better way to do this
What is "this" that you're trying to do?
make a gravity well thing?
yea, i tried making a shader but it was harder
Is it the rendering that is giving you low FPS, or are you running code that's modifying the mesh that's giving you bad FPS?
If it's the latter, just use a vertex shader instead of modifying the mesh in CPU land
its fine until the objects go onto the mesh
idk how to do it ๐ง
possibly a compute shader too. Not sure how i'd do it exactly
Time to learn!
is there a tutorial somewhere on vertex shaders cause I couldn't find one that was similar to what i was doing
Any tutorial on how to make water would be a good start.
ok
why are you cross-posting?
Sorry
Don't ping specific people for help
You posted in #1062393052863414313, wait for an answer there
Can u help me though?
No, I never used DOTS
Oh...
Hence why you got redirected elsewhere in the first place...
No
Wait for an answer in the dots channel
Do not spam other channels with references to your question, see #๐โcode-of-conduct
print("๐ ");
Ok no problem
Still thanks though ๐
How would I go about extracting the text from a TextMeshPro text object?
You use the .text property
What channel is the best to ask about Unity.Spline Package ?
depends what question you have on it?
Hummm Usage with the Job System https://discord.com/channels/489222168727519232/1203770114084708412 I posted here but not sure the folks there can help me much
thank you
Hey, idk if this is the right place to ask but I accidentally renamed one of my scripts to "Random" and one of my other scripts was using UnityEngine's Random.Range so it was trying to get the Range from my own Random script and throwing an error. After renaming it to RandomText the error still persists, is there a fix to this?
Damn i should probably try restarting before asking here
Nope that didn't fix it, any suggestions?
did you rename the script and the class name?
when you renamed it, did you use the VS rename functionality? that would rename it in other scripts, so your other script might now say RandomText.Range
Nope, thank you! Completely forgot haha
that fixed it
That's enough brain usage for today
Yeah I dont know much of ECS esp in splines context sorry :\
If I have a script to place an object to my cursor and a script when I click on an object to open a panel.
How can I get rid of the situation to open the panel when I place the object?
if(!placingObject)
{
//open panel
}
that just creates more issues actually, i solved it in the meantime by placing the object with mousebuttonup and open it with down
i didnt know where to post this, is there any way to get rid of this error without messing up my colors?
did you read the message
also not a code question
yeah, I just switched to gamma and everything looks fine anyways, i was just getting scared cuz once i did this and messed up all of my mats and i have to give this project in 30 mins
sorry didnt know where to post build setting problem
okie. Anyways #๐ปโunity-talk for general editor questions
Although this was def #๐โweb
if you want Linear as it says you have to remove the WEBAPI 1.0
Produce less garbage
how do i see where msot memory is being alloctaed in profielr
The profiler has a whole column for GC allocation
b.t.w its not the amount of memory you need to worry about it's the number of allocations
ok
Hey everyone, I'm currently implementing an inventory system which will house a lot of different item types.
Right now I have all the different item types defined with bools on a single ScriptableObject class, however I don't think this is sustainable as the class will get bloated very fast. I don't think it's sustainable to create a ScriptableObject class for each Item Type either, as that will get bloated quickly as well. So my question is, is there a better way to do this? Thanks in advance.
public class ItemSO : ScriptableObject
{
[Dropdown("typeValues")]
public string type;
private List<string> typeValues { get { return new List<string>() { "Default", "Head", "Chest", "Hand", "Foot", "Pants" }; } }
public Color color = Color.white;
public Vector2 size;
public Sprite image;
public string displayname;
[Space(10)]
public float durability = -1;
[Space(30)]
public bool isEquipment;
[EnableIf("isEquipment")] public float defencePoints;
[EnableIf("isEquipment")] public float speedPoints;
[Space(10)]
[EnableIf("isEquipment")] public bool isBackpack;
[EnableIf("isBackpack")] public Vector2 backpackSize = new Vector2(0, 0);
[Space(10)]
public bool isGun;
[EnableIf("isGun")] public bool needsClip;
[EnableIf("isGun")] public int maxAmmo;
[EnableIf("isGun")] public float damage;
[EnableIf("isGun")] public float range;
[EnableIf("isGun")] public float spread;
[EnableIf("isGun")] public int bulletsPerShot;
}
private List<string> typeValues { get { return new List<string>() { "Default", "Head", "Chest", "Hand", "Foot", "Pants" }; } }```
Could be a single SO such as ArmorSO with an enum specifier
extending from ItemSO
Even gun here can extend from it
Yeah that was what I was thinking, but I'm afraid I'll end up with a lot of different so classes
well, the enums will cut down a lot of classes if they are of same behavior and data
I usually go with something a lot more flexible like:
public enum ValueType {
Number,
String,
Color
}
[Serializable]
public class GameAttribute {
public string Name;
public ValueType Type;
public float NumberValue;
public string StringValue;
public Color ColorValue;
}
public class ItemSO : ScriptableObject {
public List<GameAttribute> attributes;
}```
^ quick and dirty example - though I usually go with an enum for the attribute name instead of a string, but this is a quick and dirty way to start.
With a small custom PropertyDrawer for the value type selector it's quite easy to make things in the inspector with this
This seems like a good idea, thanks! Do I just use list.contains to get a specific gameattribute from a different script, or is there a better way?
WOuld probably use a Dictionary<string, GameAttribute> at runtime
for fast lookups
Ah all right. Thanks man
anyone know how to go from an index (ex: table item 9) to a point on an array? (ex, 9th item on array is 3,3)
but you can just subtract then add 1 to a c# method
also this is given we know the max x and y size of the array
note that in c#, which this question better be about considering this is a unity server, lists and arrays start at index 0
yeah I can translate it
wdym you can translate it? if your question is about lua, go ask in a lua server
I think I got the x bit
there is no offtopic here and this is a unity server which uses c#
Hello,
I'm having trouble with storing a reference to my instantiated player, I'm trying to avoid using a singleton. I think it would be cool to store the playerInstance in a scriptable object, but I'm having trouble getting it working. I'm not sure if it's even possible.
I have a scriptable object that has this:
public class PlayerData : ScriptableObject
{
public GameObject playerInstance;
}
Then in my GameManager I have this method that is actually a message from the "PlayerInputManager" that comes with the new input system.
This spawns the player and attempts to assign it, but I get "Type Mismatch".
Alternatively, if this is just a bad approach and I should look into another solution, any suggestions would be appreciated.
public PlayerData playerData;
void OnPlayerJoined(PlayerInput playerInput)
{
if (playerInstance == null)
{
// This is what I had previously
//playerInstance = playerInput.gameObject;
// Trying to assign the instantiated player to the scriptable object
playerData.playerInstance = playerInput.gameObject;
playerData.playerInstance.GetComponent<Player>().PlayerIndex = 1;
OnPlayerJoin.Invoke();
}
}
why are you avoiding a singleton, not sure there is even a point of doing this
now every script you want ref to player needs an extra field with SO
@rigid island I'm hoping to reduce the amount of dependencies I have for this game
storing the reference in an SO is bad for the same reason a singleton is bad. Either inject a direct reference from some sort of GameManager/CompositionRoot/DependencyInjectionContainer or use a simple service locator.
I'm cool with having a singleton if it provides a solution, I'm more curious to know if this is the best way to approach this
@Anikki Oh, I didn't think that was the case, but thank you for the feedback, would you suggest just using a singleton in this case?
Or is there another solution?
the best compromise for a small/solo team is a service locator (which gives you a bit more control and less dependency than singletons). You'd use that rarely and only in cases where you can't have static references, like for dynamically spawned objects that need to find their ManagerDaddy.
Hi, I'm having issues with a bobbing animation looping correctly. I have a script that makes the object follow the curve as shown here. Both endpoints of the curve are set to Free Smooth, Flat, and they are set to Loop. The SFlag object here moves up and down, but once it comes back up another time, it rebounds too early. Anyone know how to fix this? (The assets here are for a sample project)
I will look into this, thank you
Mind that service locators are still an anti-pattern (in large projects), but its a necessary evil if you want to avoid the boilerplate diarrhea of all-out dependency injection (which is very tedious/hard to teach to a team).
Fixed it, nevermind. Middle keyframe had to be set to Auto
how can I give every scriptable object of a type that I make have a unique guid?
Serialize it to a string field
Parse it from that string field in a get-property
can u elaborate
make a field public string guid;, write a guid into that with a custom inspector or context menu action that has a button to generate a new one.
and it wont get randomly reset?
Thatโs what the button is for
if they are assets i would just tie the logic that generates the guid into the creation logic
if its runtime instances would make to make sure you generate a new guid as you instance it
im using it to give each of my scriptable object items a unique ID
There are no hooks for duplicating an asset (SO in this case), so IDs need to be manually assignable
could u assign it in a constructor or do scriptable objects not work like that
no constructor
if you needed something like one would just call a method after creating one manually
they do get stuff like OnEnable but chances are it does not invoke wehn you want it too
so when you make a scriptable object it doesnt call the constructor?
i feel like constructors are rarely used in unity
its because most UnityEngine.Object derived thigns are not made in the C# side of the engine
its constructed by the engine for you, then you are given the instance wrapped the C# UnityEngine.Object derived thing
makes sense
also gets weird when you think about it like say for a compoennt when would you expect the constructor to execute
since you add it via the editor ui, its not like you can call it yourself with correct args
also not everything needs to be a SO or MB, you can have just regular C# classes for what ever uses
yeah of course, but most things are either SO's or MBs
i guess your mindset just has to change a bit with unity c# vs normal c#
really depends on what you are making
at work the projects i am on have a hell of a lot of non SO or MB type structs and classes
i guess it just depends on the complexity
lot of them are just containers for data, but some of them are just other systems that i create on awake on mb's
anyone have a HeadBob script none of mine seem to work
Use sin and set the y position of the camera to it as you move
Is it better to use static functions to make a globally accessable script or make a "new" instance of it in a script to use
wheres that
Nav beat me, but Googling "c# sin" would have come up with it.
hi i wonder if the UNITY_STANDALONE symbol complies for webgl also
Ability Instantiation Bug: Returning Null
Pretty sure that's only for the standalone platform(PC, Mac, Linux?)
yea idk either because i can't find the UNITY_WEBGL symbol
Find where?
I don't think it's defined anywhere accessible from your project, so ofc you wouldn't find it.
Where does it show it?
I've looked around the docs and aroung the internet but i'm mostly finding outdate or not relevant advice.
I have a ui for selecting towers to place and i use a raycast to find the position in the world to place them, i don't want this place logic to fire when the mouse is over the ui because you can't tell where you're placing an object, but i have not found a good solution to know globally if the mouse is over a piece of ui
I do wanna ask here but does unity not use visibility changes during runtime. Iโm seeing not that many documents on it and seems I need to call the mesh I need to disable. If anyone can check or know about how visibility works in unity
I read thatโs deprecated
It is
It does of course. Frustum culling makes it so that only objects visible in the camera are rendered. You don't need to disable meshes manually.
Shouldn't be. The page just moved to dedicated ui documentation.
Itโs missing documentation which is weird
It is in the ugui package documentation
alright so I have a system that generates a NavMesh path using NavMesh.CalculatePath(), as a way to cheat sound reverberating around corners (for my FPS enemies to respond to sounds). Problem is, the paths always return invalid, even though (a) I have the check set to all areas, and (b) the regular enemy AI pathfinding (which also uses Unity's NavMesh system) works fine.
Any idea what else I should be checking for when troubleshooting this?
The thing is this is for a character animation
This is what is supposed to look like
This is when its being run in the game
Not sure how that's related to frustum culling?
I already tried all animation visibility types
Not aure where you got that info from all of this
works perfectly fine no its not , even with new input system
void Update()
{
if (inputz.actions["Fire"].WasReleasedThisFrame())
{
Debug.Log("Fire pressed");
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("Clicked on the UI");
}
}
}```
Make sure that the positions you put into CalculatePath are on the NavMesh. Use NavMesh.SamplePosition and the hit.position that it gives you
yeah I figured that out, I didn't initially use that function because I thought it was calculated automatically
thanks though
private float thicknessOffset = 2f; // Offset between layers
void Start()
{
// Get the original sprite's position and z value
Vector3 originalPosition = transform.position;
float originalZ = originalPosition.z;
// Create thickness layers
for (int i = 1; i <= thicknessLayers; i++)
{
// Calculate the new position with the offset
Vector3 newPosition = originalPosition;
newPosition.z = originalZ - (thicknessOffset * -i);
// Instantiate a copy of the sprite at the new position
GameObject newSprite = Instantiate(gameObject, newPosition, Quaternion.identity);
newSprite.transform.SetParent(transform.parent); // Set parent to maintain hierarchy
// Remove the AddSpriteThickness script from the new GameObject
Destroy(newSprite.GetComponent<AddSpriteThickness>());
}
}```
why does doing
newSprite.transform.SetParent(this.transform) or
GameObject newSprite = Instantiate(gameObject, newPosition, transform.rotation, transform);
freeze editor?
๐ฅฒ
Probably recursive instantiation?
GameObject newSprite = Instantiate(gameObject, newPosition, transform.rotation, transform);
```what this gameobject do after instantiated
nothing because I destroy the script
the script is assigned to a sprite, start, makes copies of itself while destroying the script so it doesn't loop
but your editor freezes
that means your code is doing thing
so your destroy is useless
the code works, but I'm trying to change parent to actual parent not parent of parent
as in, have the copies be child of the original sprite
it loops 100% because memory goes brrr but I don't understand how that happens only when trying to assign the original sprite as parent of all its copies, better said have the copies be child of the original sprite
Instantiate(gameObject) will make a copy with the script that calls Instantiate in its Start
Destroy runs with a frame delay so its start is also being called
nu uh if you destroy the script
idk if intended but it does destroy it before start
i am not sure whether start will run immediately right after instantiate
but i know destroy() are queried
It only destroys it on the initial object. Then the spawned one executes the script again and so on.
Anyways, trying to fix a recursive bug like that by destroying the script is a terrible idea.
right
I will try a workaround but I just don't understand how the code just works until I simply change the parent thing
It's probably just a timing coincidence.
yeee exactly that is what I was thinking
thank you
You could probably figure it out if you debug it properly.
super beginner sorry, I know the destroy thing is terrible, just wanted to know why would it work in one scenario but not the other
Well, it's not entirely clear what you're doing to reproduce the issue to be honest. And what you change for it to not occur. So it's hard to explain anything.
unsure if it is a timing thing, tried this workaround now and it loops
{
private int thicknessLayers = 50; // Number of layers to create for thickness
private float thicknessOffset = 2f; // Offset between layers
public GameObject parentObject;
void Start()
{
// Get the original sprite's position and z value
Vector3 originalPosition = parentObject.transform.position;
float originalZ = originalPosition.z;
// Create thickness layers
for (int i = 1; i <= thicknessLayers; i++)
{
// Calculate the new position with the offset
Vector3 newPosition = originalPosition;
newPosition.z = originalZ - (thicknessOffset * -i);
// Instantiate a copy of the sprite at the new position
GameObject newSprite = Instantiate(parentObject, newPosition, parentObject.transform.rotation, parentObject.transform);
}
}
}
I assign it to an empty GameObject
parentObject being the GameObject I want to copy paste to make the illusion of volume. It is a 2d sprite.
Instantiating a parent object, implies instantiating it's whole hierarchy, including the children, which includes the current script. Which is gonna run it again and repeat it again and again recursively. Which eventually is gonna cause your PC or unity to run out of memory and crash.
but this is not the case? this script is assigned to a different GameObject
empty one
it instantiates parentObject which is a GameObject assigned via editor
Is it a child of the parentObject that you reference?
nope
Hello everyone, I'm having an issue with a script I wrote to change the skins of my characters in Netcode. Where can I ask my question?
Then take a screenshot of that object in the hierarchy
Take a screenshot of the whole editor with the current script inspector visible and the whole hierarchy.
Thank you ๐
Okay. If that's the case, then the issue is probably somewhere else.
this code does work, but my intention is to have the copies be child of the original sprite as I mentioned, don't seem to find the way for whatever reason
They should be it's children as it is now.
how now? the last code I sent? but that one doesn't work
Yes. How does it not work?
idk ๐ญ
I mean, how do you determine that it doesn't work..?
Try breaking with the debugger when the editor freezes.
If that code causes the freeze, it must be in combination with something else, which is not visible in that code.
if I change, from the last code, this
parentObject.transform to
transform.parent or just transform it will work
why ๐ญ
Again, it's probably in combination with some other code. It's really hard to say without knowing the whole project.
The fastest way to debug the issue would be to use a debugger and or some logs.
ikr just venting until I debug
even if I duplicate the parentObject and assign the duplicate it will still freeze, just in case
i love when i try to debug my code and changing things i thought were crucial never even mattered in the first place
i have a Vector3 position,
i would like a child to be at this position, but I would like to affect all childs and parent.
how can I move the parent so the child is at the position
Parent everything to that child and set it's position.
I cant reparent
Or calculate their offset beforehand
thats what i would like to do
rb.MoveRotation(rb.rotation * deltaRotation);
is there better math than this to make it stop lagging behind?
playerRotation is just a vector3(0f, yRotation, 0f)
Instead of multiplying quaternions keep track of it's rotation in Euler angles, add to them then use it in MoveRotation
an overly complicated inverted camera x axis in a vector3 from the input * sensitivity
No. Just keep it as a Vector3 or a float. Modify it from the input. This vector/float is gonna be the source of truth for your rb rotation.
If you don't want any lag then just use the rotation you want directly without multiplying by deltatime
I know you probably told me but I just realized instantiate does copy child too so since I set the parent inside the loop it will also copy every child and so on pff I better rest for now...
https://paste.ofcode.org/vqp7ZJpsMb6hZyBBPxk5gf this is the new input system code with movement and stuff
not sure if i follow
Yeah, mentioning that something happens in a loop was probably important...
you probably want to zero out playerRotation after consuming it in Movement
and, indeed, scrap the deltaTime
Less of a "need help" question and more of a how do I do this question, but how would I go about doing a battle system like this in the engine? From about 1:22 to 1:50. I'm using the Panoply unity tool for cutscenes involving motion comics and considering using the Dialogue System addon for the visual novel elements. But I wanted to get this aspect of it in as well.
Invincible Presents: Atom Eve Full Game Gameplay Walkthrough No Commentary PC
Become Atom Eve and take control of your own path as one of the most powerful superheroes in the Invincible universe! Unravel a mystery and balance the dangers and responsibilities of being a superhero with the relatable challenges of everyday life.
Follow me on Stea...
float yRotation;
//Update
yRotation += input * delta time;
//Fixed update
Quaternion actual rotation = //construct from yRotation and other relevant values
rb.MoveRotation(actual rotation);
Something like this.
Seems like just some moving ui and animated sprites. Don't really see any difficulty implementing it.
Hi, I am developing a playing card game like poker. For the cards, I used a SpriteRenderer and changing the sprite of the renderer with
_openSprite = CardManager.Instance.GetSpriteWithId(Data.Id); // Preloaded Sprite Dictionary <Integere, Sprite> with Resources.Load<Sprite>...
baseRenderer.sprite = _openSprite;
Is this a good way? I'm asking this because I am having many ANRS and high crash rates.
ANRS?
Angry null reference scripts?๐ค
Application Not Responding (in Android)
I doubt that code could cause those, have you narrowed down the problem to those lines specifically?
im using Unity 2018.4.27f1 and im trying to get a package from a github, but it says i need to add a Scoped Registry in Project Settings -> Package Manager
that doesnt exist - or at least i don't have it. wtf do i do thats the only install method
App Not Responding errors. I tried narrowing down but I couldn't get a specific error case? A friends' phone stucks in the middle of the game but I cannot see the logs from adb logcat, there is nothing sent.
I've read that Resources.Load<> causes some ANRs, but Sprites are loaded at runtime for once, then I use them from the dictionary. I don't load them in real time
Is there a better approach to show cards with different sprites?
If you can reproduce in local environment, maybe reproduce with the debugger connected? If it's crashing, it would break at the crash point. Otherwise, you can trigger a break manually to see what it's doing.
general question ab coding,
should ANY private variable, with no serializefield, be named with an '_'
eg:
private float _timerTest
I have connected to a local environment but it's not crashing, it's freezing the app (ANR). Probably main thread gets locked and nothing is reported on logcat.
No. It's a naming convention that you don't have to follow.
Hey ๐
this might be a strange ask but does anyone have any suggestions for resources or anything that utilises quake style air control as well as quake style movement direction calculation (wishdir, vel and accel) using rigid body movement instead of character controller?
is it typically widely used to showcase this or is it generally a split convention
Depends. I don't use underscores for example
The _privateField convention exists for the reason that if you have a local variable of the same name, you would have to use this.foo and foo to disambiguate them, and it also makes autocomplete worse. When you are reading code and you see foo = bar; you won't know if you are mutating a local variable or a private field, that means when reading code you have to commit mental energy to remember "the current class has these private fields and the current scope has these local variables."
It's a widely adopted convention in wider .NET world, but in Unity... people don't always follow conventions (and I personally think it's a bad thing that people don't follow, but oh well there's enough inertia of people going against the convention that it's not worth arguing against them)
I see, noted, thank you for that explanation
I have been using and aim to still use it, just made me rethink when most people's code on here seemingly does not follow this convention
Well, C# in the Unity world isn't known for having high code quality ๐
As a general advice, it's more important to be consistent, so choose whatever convention works for you and stick with it for the entire codebase.
But if you have the freedom to explore different conventions, I would really suggest following the C# conventions in the wider .NET world, or at least understand the reasons behind them and decide for yourself.
https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.0/manual/index.html does this package not exist in 2023? it's not in the unity registry in package manager for me
add it by name
is OnDisable called when leaving a scene or the app?
yes
ok ty
OnDisable is called any time the object is either disabled or destroyed, unloading a scene destroys the object
also random question :
can i "merge" multiple function so they do the same stuff
example :
// current
private void OnApplicationPause(bool pause)
{
SaveHightScore();
}
private void OnApplicationQuit()
{
SaveHightScore();
}
//idea :
private void OnApplicationPause(bool pause) OnApplicationQuit()
{
SaveHightScore();
}
i dont think its possible since the functions can have differents params, but i just wondered
also does OnApplicationQuit += SaveHightScore work ?
okay ty
so you cant merge function if they both have no args and are void ?
there is no such thing as "merging" methods. you can store methods in a delegate, but that isn't what you've described nor does it solve whatever it is you are trying to solve
It should still exist, as boxfriend mentioned you may have to manually add it, in the top left there should be a + sign, click that and you can add a package by git URL, try: com.unity.nuget.newtonsoft-json
thank you
is there any specific reason it's not searchable? is it unsupported or something
it's just not shown in the unity registry. this is true for many packages
I am using perlin noise to create deserts, and for some reason the corners are sharp instead of smooth. This is only a problem when I use values that are close together, and as I scale the noise down there is no problem. How can I get smooth edges around my desert?
The lakes are fine as the noise is scaled differently
show code
Hi everyone, I need help with a scene in unity development if anyone know hows to fix it.
I am trying to create a VR scene in unity, where the user needs to place some rings on hooks, however the rings do not go through the hook
private float TileTemperature(int _x, int _y, WorldGenerationData_SO _generationData)
{
float noiseMultiplier = 1f / _generationData.temperatureNoiseLayers.Length;
float totalNoise = 0;
int actualSeed = (int)_generationData.seed * 100000;
for (int i = 0; i < _generationData.lakeNoiseLayers.Length; i++)
{
totalNoise += Mathf.PerlinNoise(
_x * _generationData.temperatureNoiseLayers[i].noiseScale.x + actualSeed * (i + 1),
_y * _generationData.temperatureNoiseLayers[i].noiseScale.y + actualSeed * (i + 1));
}
return totalNoise * noiseMultiplier;
}```
float temperature = TileTemperature(x, y, _generationData);
Tile.TileType tileType;
if (temperature > _generationData.desertTempMinValue)
{
tileType = Tile.TileType.Sand;
}```
no they wont, presuming you have a standard collider on them. you will need to model the rings in something like blender and make the meshes separate around the ring
The temperature value is exactly the same for all the ones in the given "chunk"
I have an open question about general way of doing something. I have a 2D Canvas game, the level is read from a 120x68 image and represented ontop of a 960x540 image. (its one of those find the items game)
I got it working.. but i dont really like my code, its a bit off (expected due to loss of precission).
I have no idea on how to look for info regarding this beyond minimap questions that work similarly.. any help on this would be great. Does this have a name i can google?
im sure there has been a lot of work done in mapping from a low res image to higher res display, but im at a loss for the technical names to look it up xD
I think you're seeing floating-point imprecision here
actualSeed looks like a catastrophically big number
_generationData.seed * 100000
What's the range for the seed variable?
if noiseScale is a very small number and actualSeed is a very large number, then it's likely that several tiles will produce the same floating values that get fed into the perlin noise function
What you really need here is a 3D noise function.
X and Y will be world position; Z will be the seed
It's set to 1
the Mathematics package includes a bunch of noise functions
snoise(float3 v) being relevant here
that's 3D simplex noise (like perlin noise, but better in a way I can't articulate)
okay, so the closest floating point value to 100,000 is 100,000.0078125
If your scale is small enough that the difference betwen two tiles is less than 0.0078125, then two adjacent tiles will produce the same value.
and this will get more and more dramatic as you add more noise layers
since you multiply by i + 1
I would do something more like this:
float noise = noise.snoise(new float3(
_x * _generationData.temperatureNoiseLayers[i].noiseScale.x,
_y * _generationData.temperatureNoiseLayers[i].noiseScale.y,
_generationData.seed * 1000 + i * 100
));
bit of a handwave on the seed value there
Thank you for taking time to answer my question
if you don't have the Mathematics package already, you can install it from the package manager
I am working with 2D noise though
The point is to avoid mixing the seed with your tile position
Okay
so you don't have to start creating gigantic X and Y coordinate values
X and Y are tile position. Z is the seed.
The result is still a float, just like Mathf.PerlinNoise
I get it. Thank you ๐
You similarly can use 4D noise in a 3D game
I can construct a 3D version of the 2D perlin noise function relatively easily
Hey, I got a little problem using Coroutines. I'm currently doing a build system, and my build has animation and I have to wait until the build is completely done to do the next part. So here's the code i made for the first coroutine
public IEnumerator BuildEnded(Structure structure)
{
if(structure != null)
{
allStructuresList.Add(structure);
Structure builtStructure = currentTile.Build(structure);
yield return StartCoroutine(builtStructure.GetStructureAnimation().PlayAnimation());
Debug.Log("we finished building");
OnBuildDone?.Invoke(this, new BuildArgs
{
tileToBuild = currentTile,
structureToBuild = structure
});
currentTile = null;
} else
{
OnBuildDone?.Invoke(this, new BuildArgs
{
tileToBuild = null,
structureToBuild = null
});
}
}
And the second coroutine (which is "PlayAnimation()")
public IEnumerator PlayAnimation()
{
float currentTime = 0f;
isCurrentlyAnimating = true;
meshRenderer.material = animatedMaterial;
animatedMaterial.SetFloat("_FillRate", 0f);
effect.Play();
while(currentTime < animationDuration)
{
float animationTimer = currentTime / animationDuration;
float fillRate = Mathf.Lerp(-0.3f, 1f, animationTimer);
animatedMaterial.SetFloat("_FillRate", fillRate);
currentTime += Time.deltaTime;
yield return null;
}
effect.Stop();
isCurrentlyAnimating = false;
Debug.Log("isCurrentlyAnimating = " + isCurrentlyAnimating);
meshRenderer.material = endedMaterial;
}
I don't really know why, but the debug "finished building" is not written in console, but my 2nd coroutine is correclty ending up :/, does anyone know a solution?
so "isCurrenlyAnimating = false" is getting logged?
nothing else in console?
Is any game object being deactivated?
nope, i didn't deactivate any object
my game is a turn based game, so i have a main coroutine for the current player's turn, maybe is the problem ? (but the coroutine of "buildended" is not called in the main turn coroutine
sanity-check this by not doing a yield return when you start the coroutine
just blow straight past and see if you get "we finished building" in the log
if not, someone else is starting PlayAnimation
(you could also just log right before you yield return the coroutine object, I guess)
So you mean i just do StartCoroutine() without yield return?
Correct.
okay so without the yield return, the code after the start coroutine is correctly executed. However, the animation is not ended before it's executed
that's logic, but that's weird that with the yield return, the code is not executed just after the coroutine is ended up
According to the documentation, that should work :/
try return the ienumerator directly without startcoroutine
yes
okay let me try
With that :
yield return builtStructure.GetStructureAnimation().PlayAnimation();
My coroutine "PlayAnimation" is just doing the first frame, but it freezes, and never ends
I was under the impression that it would exhaust the enumerator before resuming the original coroutine
same
is there anything changing the animationDuration? you have logged it?
i can log it, but i don't think it's changed, it's a serialize field in the inspector, i never assign it through code
okay, and that is indeed how it works. I just checked.
IEnumerator Foo()
{
Debug.Log("Calling Bar");
yield return Bar();
Debug.Log("Done with Bar");
}
IEnumerator Bar()
{
Debug.Log("Bar started");
int x = 0;
while (x < 30)
{
x += 1;
yield return null;
}
Debug.Log("Bar ended");
}
because when i just use StartCoroutine(Method()), the animatino is correctly ending
so why it's not working with me ๐ฆ
This implies that the original coroutine is dying immediately.
Coroutines run on the MonoBehaviour that you called StartCoroutine on
I'm wondering if you have something like this going on
Could be some ownership thing
public class Foo : MonoBehaviour {
public Bar bar;
public void StartWorking() {
StartCoroutine(bar.BarCoroutine());
Destroy(gameObject);
}
}
public class Bar : MonoBehaviour {
public Baz baz;
public IEnumerator BarCoroutine() {
yield return StartCoroutine(baz.BazCoroutine());
}
}
public class Baz : MonoBehaviour {
public IEnumerator BazCoroutine() {
yield return null;
}
}
BarCoroutine is being handled by a Foo instance
when the Foo instance dies, the coroutine stops
BazCoroutine is being handled by a Bar instance, so it doesn't care, and continues executing
But when we tweak it so that we just yield return baz.BazCoroutine();, there's not a second coroutine. The Foo instance is responsible for exhausting the BazCoroutine() enumerator.
So when it dies, BazCoroutine "freezes"
okay i understand, but my build system (which is the class : MonoBehaviour) is a singleton, and never dies, so it's impossible, right ?
I'll need to see the code.
Show me the entire script that starts the BuildEnded coroutine
okay
public void ValidateStructure()
{
if(structureDisplayed.CanBeBuildWith(inventory))
{
StartCoroutine(BuildSystem.Instance.BuildEnded(structureDisplayed));
BuildSystemUI.Instance.DestroyAndHide();
} else
{
Debug.Log("you cannot build that structure");
}
}
As you can see, there's a method "destroyAndHide()", but that destroys some stuff in my UI system, (which shows the builds available which the current ressources in inventory)
public void DestroyAndHide()
{
foreach(BuildPossibilityUI buildPossibilityUI in buildPossibilities)
{
Destroy(buildPossibilityUI.gameObject);
}
Hide();
buildPossibilities.Clear();
}
the BuildSystem and BuildSystemUI singletons are never destroyed
It doesn't matter that the method is on BuildSystem.Instance
look at this example again
Bar is your BuildSystem
Foo is whatever this class is
What matters is who you call StartCoroutine on
I'm not talking about that at all.
no, it just contains the definition of ienumerator
public void ValidateStructure()
{
if(structureDisplayed.CanBeBuildWith(inventory))
{
StartCoroutine(BuildSystem.Instance.BuildEnded(structureDisplayed));
BuildSystemUI.Instance.DestroyAndHide();
} else
{
Debug.Log("you cannot build that structure");
}
}
Which class does this exist in?
I asked to see the entire script for a reason (:
StartCoroutine is an instance method of MonoBehaviour-derived classes
It's not some kind of magic static method
Oh shit u are right
It tells a MonoBehaviour that it's responsible for exhausting the enumerator you give it
It's in my buildPossibilityUI, which i destroy
by calling MoveNext() on it once per frame, by default
eg if you
public class A{
here start the coroutine
class AManager clear
}
public class AManager{
clear(){
destroy all As
}
}
The validate Structure is in a class that is destroyed just a few lines after
It would be safe to do BuildSystem.Instance.StartCoroutine(...)
assuming that's also a MonoBehaviour
I'm trying something wait
A further point to know -- it's fine if the object the IEnumerator came from gets destroyed
All that destroying a Unity object does is mark it as "destroyed"
It doesn't magically prevent you from calling methods on the object
It does make Unity throw exceptions if you try to access Unity-specific properties
whatever.transform // error!
whatever.myCoolInt // fine
so you could absolutely destroy the MonoBehaviour that you got the IEnumerator from. As long as you passed it to StartCoroutine on an object that hasn't been destroyed, it'll keep chugging along as usual
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
namespace Tomartyr
{
public class ControlHandler : MonoBehaviour
{
[SerializeField] GameObject detectingKeyText;
KeyCode[] controls = new KeyCode[(int)MInput.EndOfEnum];
MInput currentDetector = MInput.Forward;
public void Start()
{
detectingKeyText.SetActive(false);
}
public void PollInput(int input)
{
StartCoroutine(PollInputCoroutine((MInput)input));
}
private IEnumerator PollInputCoroutine(MInput input)
{
yield return null;
detectingKeyText.SetActive(true);
for (bool polled = false; polled == false;)
{
if (Event.current.isKey == true)
{
if (Event.current.type == EventType.KeyDown)
{
if (Event.current.keyCode == KeyCode.Escape)
{
controls[(int)input] = KeyCode.None;
polled = true;
}
else
{
controls[(int)input] = Event.current.keyCode;
Debug.Log("The inputs name is: " + Event.current.keyCode.ToString());
polled = true;
}
}
}
}
detectingKeyText.SetActive(false);
}
}
public enum MInput
{
Forward,
Backward,
Left,
Right,
EndOfEnum,
}
}```
Does anyone know what could be causing this error message
...unless the method tries to access transform/gameObject/layer/etc.
null reference exceptions are caused by one, and only one, thing
you tried to access a member from something that is null
Which line is that?
if (Event.current.isKey == true)
btw, to prevent future questions
for (bool polled = false; polled == false;){
if (Event.current.isKey == true){
some codes, no yield return inside
}
}
dead loop
oh yeah, that's weird
Event.current works only in GUI methods and such, as far as I know. It will be null elsewhere
ight
ight
Hey Guys ๐
I am working on a Rigidbody Player Movement system and am struggling to switch things up. Basically the current method of applying forces is like this
rb.AddForce(orientation.transform.forward * y * acceleration * Time.deltaTime * multiplier * multiplierV);
rb.AddForce(orientation.transform.right * x * acceleration * Time.deltaTime * multiplier);
ultimately the first line accounts for forward and backward movement whilst the bottom line accounts for side to side movement.
What i am trying to do instead is apply the forces similar to quake 3 movement
AddForce already multiplies it by fixedDeltaTime by default so dont use deltaTime with forces
As a side note
what should be used instead?
Just remove the deltatime multiplication
I found a solution, i just used an event handler on each buildPossibilityUI which fars an event to BuildSystem, and it's the BuildSystem monobehaviour that starts the coroutine to avoid some problems, thanks for everything ๐
And then adjust your multiplier values again - they need to be way smaller
nothing- never include deltaTime with AddForce
yeah holy i be zipping around now
whats the theory behind that?
so i can understand
FixedUpdate is the only place AddForce should be called
FixedUpdate is already framerate adjusted automatically
It also is the intended usage for AddForce and is the only way the units make sense.
So multiplying by deltaTime is just a pointless division of the force by 50
that made the acceleration value make sense
cause before i had it at like 5000 lmao
okay that made it make a lot more sense
that was a very good tip
thank you very much man
instead of applying the forces for the player for forward and back and side to side i want to apply it more like quake
i am struggly to apply the logic to rigid body
this makes for more smooth movement while also making air control feel much better
any tips?
i tried utilising this but struggled
https://adrianb.io/2015/02/14/bunnyhop.html
whats the difference between
(ns_in_second / (world_current_scale / GameSettings.timer_fps)) / GameSettings.timer_fps)
```and
```cs
(ns_in_second / world_current_scale)
as both yield the same result with
(ns_in_second / (world_current_scale / GameSettings.timer_fps)) / GameSettings.timer_fps)
```and
```cs
(ns_in_second / world_current_scale)
but both yield the different results with
(ns_in_second * (world_current_scale / GameSettings.timer_fps)) / GameSettings.timer_fps)
```and
```cs
(ns_in_second * world_current_scale)
if you are basing ur movement off of quake you should directly modify velocity directly instead of going through addforce bc that's how quake does it
most rigidbody stuff is for realistic physics simulation, which quake physics is not
is there no way to emulate similarities?
cause like i chose rigid body so that things like explosions, springjoint grapple and all that can still effect the player
the way quake calculates its force direction doesnt seem to be tied intrinsicly into their physics movement
unless im interpreting it wrong
i was able to get pretty close but something i could not reconcile is that when rbs collide they push eachother, which does not happen in quake
atm i have the following
which is ok
tho i have
+ "percieved time: " + ns_to_string((long)(ns_in_second * world_current_scale)) + "\n"
+ "remaining time: " + ns_to_string((long)(ns_in_second / (world_current_scale / GameSettings.timer_fps)) / GameSettings.timer_fps) + "\n"
what i was saying is that addforce assumes that you are adding a force to an object with mass, and quake guy is a massless being, so it makes more sense to direclty modify rigidbody.velocity
how does rigidbody.velocity interact with things that effect the rb?
just out of curiosity
so why tf am i dividing by my fps which is 60 ?
addforce just changes rigidbody.velocity but with more physics math inbetween (afaik)
couldnt you make it so that on collision with player tag it cancels the movement, similar to countermovement/friction? which would sorta emulate stopping?
or atleast it sends the reverse to cancel it out so it doesnt matter where the collision occured?
so it sends an equal reverse force to the player forcing them to stop
I do not understand your problem.
(ns_in_second / (world_current_scale / GameSettings.timer_fps)) / GameSettings.timer_fps)
(ns_in_second / world_current_scale)
a / (b / c) / c
= a / b * c / c, unfortunately this is true only if b and c are not int (or short or byte that something with no decimal part)
= a / floor(b / c) / c
it directly sets the velocity of the rigidbody. the rigidbody will use this velocity in the next physics update.
you would have to check your next position with boxcasting, and for multiple actors you would need a manager to handle all of them, and at that point it just made more sense for me to implement my own physics from scratch
instead of using rigidbody and trying to remove most of its functionality
good luck
most of the difficult math is in collision-checking and unity's raycasting system basically does that for you, so it was p trivial. just dealing with edgecases rn
guys
void Start()
{
micSource = gameObject.AddComponent<AudioSource>();
micSource.clip = Microphone.Start(null, true, 1, 48000);
micSource.loop = true;
micSource.Play();
playSource = Instantiate(new GameObject(),gameObject.transform).AddComponent<AudioSource>();
playSource.clip = AudioClip.Create("test", 48000 * 2, 1, 48000, true,OnAudioPlaybackRead);
playSource.loop = true;
playSource.Play();
}
private void OnAudioPlaybackRead(float[] data)
{
if (micBuf.Count >= data.Length)
{
micBuf.GetRange(0, data.Length).ToArray().CopyTo(data, 0);
micBuf.RemoveRange(0, data.Length);
}
}
private void OnAudioFilterRead(float[] data, int channels)
{
micBuf.AddRange(data);
Array.Clear(data,0, data.Length);
}
why does the audio sound like 2 times slower where do I messed up
You've decoded it with the wrong sample rate.
It's probably sampling at 96000hz
oh, I see what you did
couldnโt you add a box or capsule whatever you need collider around your player that only interacts with players
so that when the player collides with the โouter boxโ itโs like a wall removing player rigid bodies from interacting with eachother?
oooh
well, hmm, no, I thought you set the sample rate of the audio clip to 96000hz
but that's the lengthSamples parameter
yeah
that just controls how long the clip is, not how quickly it plays back the samples
oh i didn't know what that did to be honest
Do you have a stereo microphone?
nope
That would produce twice as many samples as a mono microphone, which, if naively copied over, would play back at half speed when interpreted as mono data
ohh
will this remove the need for cancelling inputs if the force goes over a threshold, overall simplifying my current movement function?
how do I get the number of microphone channels
every person has a different mic
it looks like Microphone only ever does one channel
yeah I changed the channels to 2 and it works now
wierd tho
hm, definitely unexpected
but yes -- you'll get slow/fast audio if the sample rate is wrong
yeah that makes sense now
It could be that your microphone can't provide the sample rate you asked for, but if it was too low, that'd give you audio that plays too fast
24000hz -> 48000hz is double playback speed
96000hz -> 48000hz would be too slow, and intepreting it as stereo data would "fix" it
but I doubt your microphone can only do that really high frequency
yeah max 48kHz
hi im trying to make a rigidbody player controller for my fps game. problem is that unlike the normal character controller, it does not take steps, like climbing stairs. how do i fix this? ive tried using raycasts to change its y position as it approaches a step
you could just replace the steps with a invisible ramp
ah
thanks for the suggestion though
its quite complicated if you wanna do it properly. I found a tutorial
https://www.youtube.com/watch?v=XC_g1MCxMXA
yeah do it ye old fashion way and just add a ramp
sorry, but as i said i'd rather not
you'll need to do step detection yourself, then
doing it with rigidbodies seems hard
something I'd tackle more with a custom character controller
this looks a lot like how I implemented vault detection in a parkour-game prototype
fire a bunch of raycasts to scan for a ledge, then fire rays down to figure out where on the ledge you can stand
alright, just wanted to know if there was some kind of easy way to do it. thanks though
You maybe able to take advantage of Physics.ComputePenetration
Although it'll probably just suggest kicking your collider out horizontally
now I wanna print this and hang above my desk for motivation
Hello so I am still having problems I asked yesterday about my enemy character not stopping moving on collision with the specific object i want it to. https://hatebin.com/ijqyhceaau
now I know you have been told about how to post !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sry just remembered
Yeah, that's kinda what I was thinking, but then there's also going down the stairs which I guess you can just launch them from the top, or do more raycast calculations downward
I find it funny how a lot of older nintendo games actually did stairs correctly, yet the invisible ramp way is still quite apparent in a lot of newer titles
did you debug
are the logs showing
problem is, if i like back up from the stairs, it detects it and still pushes the player up like it was approaching the stairs
u mean this
alr then your condition isnt met or it gets changed back by something else
yea but i cant see wat
Debug.Log the if statement
it tells you what you're hitting
#archived-code-general message
Only move up if you're actually pushing against the stairs. Only use the raycasts to know how high to move up, not to actually do it
so it worked and sent the message in but it is spamming it like 1000 times
which is fine because it is in update.
lmaooo
? what.
i like the "like ur mum" addition to the debugging
oh yea
always helps (fr)
๐
I got a issue with my scirpt. I'm trying to find the animation current state based on its name but for some reason it seems no not find it. Is there a issue with my code or is a issue with the actor
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class animatorScriptControl : MonoBehaviour
{
Animator anim;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
this.transform.localRotation = Quaternion.Euler(0, 135, 0);
}
// Update is called once per frame
void Update()
{
if (this.anim.GetCurrentAnimatorStateInfo(0).IsName("walk"))
{
print("HIIII");
}
}
}```
Why do you want to get the current state? You're probably better off using animation events or StateMachineBehaviour for whatever you're trying to do
What does that have to do with animator State?
the animation is at a 180 degree angle. It is getting mirrored on both sides. In the right i need it to be a 135 degree angle and in the left i need it to be 45 degree angle
that why i need it
I don't get it still, that's a very unclear explanation. It also still sounds like something you should do with an animation event or StateMachineBehaviour
alright i somehow fixed my issue
its kinda buggy but at least it works perfectly on some circumstances
well do you have a solution when it comes to animation events
Yes, make an animation event in your animation clip that does what you want
damn you were right. i was being very stupid
public void FaceSceneRight() => transform.localRotation = Quaternion.Euler(0, 135, 0);
And mide it clean too
Why "press e to interact" isn't popping out when the blue line touch the lightswitcher on interactlayermask? Did i do something wrong?
ScreenPointToRay takes a screen-space position. You are giving it a world-space direction
If you want a ray from the center of the camera, give it a coordinate that is half the screen size
Or use Camera.ViewportPointToRay which takes normalized coordinates so you can just give it (0.5f, 0.5f) for center
ok thank you
wait, im confused it's not working
i want a ray that comes out from the center of camera and it has the camera forward direction. I want to do that when the ray touches the lightswitcher that is on interact layer the "press e to interact" pops out.
The ray should be fine if you did what I said. There could be other issues
Put some logs so you know which if-statements pass and which do not
Log the object that you hit
ok
Make sure you aren't trying to get the component from a child, while the parent has the component
If it has children with colliders, that is
when i pick up the object, i update its position to lerp towards the transform i placed in front of the camera (desiredTrans). i tried using both transform.position and rb.move version to do this. they both failed at fixing the jitter. i tried all the rigidbody objects' interpolation settings, setting it to kinematic, freezing rotation and position etc... nothing fixes the jitter. this is my code for lerping rigidbody object's position towards the "desiredTrans" position btw: private void FixedUpdate()
{
if (picked)
{
rb.Move(Vector3.Lerp(transform.position, desiredTrans.position + offsetPos, rbLerpSpeed),
Quaternion.Lerp(transform.rotation, desiredTrans.rotation, rbLerpSpeed));
}
} help would really be appreciated been struggling with this for days..
@kindred plume Post your updated code too, just to be sure
ok, wait
Where is this code being called from?
You must make sure that it runs after your camera and the target transform has rotated/moved each frame. Not before
ah, so i change code execution order?
from fixedUpdate
Jitter is very often an execution order thing, yes
ill try it now
Also make desiredTrans visible so you see if that is jittering or just the rigidbody
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Also is rbLerpSpeed a constant value?
yes
private void HandleInteraction()
{
Vector3 interactDir = cam.transform.forward;
Ray ray = new Ray(cam.transform.position,interactDir);
if (Physics.Raycast(ray,out RaycastHit raycastHit, interactDistance,interactLayerMask))
{
if (raycastHit.transform.TryGetComponent(out Interactable interactable))
{
if (interactable != selectedInteractable)
{
Debug.Log("Interactable detected");
selectedInteractable = interactable;
SetSelectedInteractable(selectedInteractable);
}
} else
{
Debug.Log("Interactable not detected");
SetSelectedInteractable(null);
}
} else
{
Debug.Log("Ray is casting nothing");
SetSelectedInteractable(null);
}
}
@hexed pecan
it works but it doesn't detect the lightswitcher
Put some more info in your logs, log the object that was hit
ur right i forgot
what do i log about the object that was hit?
ok i log the name about the object and it logs the name of the lightswitcher like its components "cube" or "cube (1)"
@hexed pecan
Hence this ^
A quick fix is to use GetComponentInParent instead of GetComponent
no no, the lightswitch parent has the script
ok
Yeah but your ray is hitting its children which don't have that component
oh ok
Or if those cubes don't need colliders then just remove them
and i add the box collider to the lightswitch parent?
Yeah
So either:
Only the lightswitch has a collider and you use GetComponent
Or the children have colliders too but use GetComponentInParent
Latter option might be easier to work with later, if your interactable objects will have child colliders
i prefer that the lightswitch has a collider and i use the trygetcomponent so it is easier and efficient
omg it works
i can shut off the light
Thank you @hexed pecan
this is my code. i switch to rb.move when the picked up object collides with other objects. with a proper script execution order(MouseLook first and this one second), while using transform to lerp object's position, it has significantly less jitter (still little is left tho). but when it collides with something and switches to rb.move in fixedUpdate, it starts jittering crazy.
omg
Hey, can someone help me with my endless problem, I can't get my 2D game endless platform to generate
Ask your question
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Time to start debugging then
My whole game has become a debug since I started playing again
well better get used to it 80% of dev is debugging
I no longer have the idea of โโhow to deal with unity like I did back then
It would be very helpful if someone could look at my project to see what is useful and what could be deleted
thats up to you to determine
first debugging steps, check the functions are even running
what are the values of each, etc
if you understand these basics you don't need someone else to look over anything
damn, if you have no documentation, of course you will struggle returning to code after months
List<Block> matches = new() { startBlock.block };
BlockSO type = startBlock.block.blockType;
List<int> offsetMuls = new() { 1, -1 };
foreach (int offsetMultiplyer in offsetMuls)
{
int loopCount = 1;
bool failed = false;
do
{
Vector2Int nextBlockPos = startBlock.startpos + (offset*offsetMultiplyer*loopCount);
if (!grid.TryGetValue(nextBlockPos,out Block nextBlock))
{
failed = true;
continue;
}
//stuff that relies on tryGetValueWorking
loopCount += 1;
}
while (!failed && loopCount > 20);
}```
this while-do loop properly skips the rest of the code via that continue if the try get fails right?
Continue goes to the next iteration of the loop
In this case since you're checking that bool in the while condition why not just break though?
can i have some help please
Now it looks like this
How do I avoid mirroring ?
What does your code look like?
private bool TileIsLake(int _x, int _y, WorldGenerationData_SO _generationData)
{
float noiseMultiplier = 1f / _generationData.lakeNoiseLayers.Length;
float totalNoise = 0;
int actualSeed = (int)_generationData.seed * 2000;
for (int i = 0; i < _generationData.lakeNoiseLayers.Length; i++)
{
totalNoise += Perlin3D(
_x * _generationData.lakeNoiseLayers[i].noiseScale.x + 10000,
_y * _generationData.lakeNoiseLayers[i].noiseScale.y + 10000,
actualSeed + 200 * (i + 1));
}
return totalNoise * noiseMultiplier < _generationData.lakeMaxValue;
}```
i'm guessing Perlin3D is adding x and y together and computing noise based on that
let's see that method
private float Perlin3D (float _x, float _y, float _z)
{
// Source: https://www.youtube.com/watch?v=Aga0TBJkchM
// Get all three permutations of noise for x, y, and z
float AB = Mathf.PerlinNoise(_x, _y);
float BC = Mathf.PerlinNoise(_y, _z);
float AC = Mathf.PerlinNoise(_x, _z);
// And their reverses
float BA = Mathf.PerlinNoise(_y, _x);
float CB = Mathf.PerlinNoise(_z, _y);
float CA = Mathf.PerlinNoise(_z, _x);
float ABC = AB + BC + AC + BA + CB + CA;
return ABC / 6f;
}```
yeah, so this is just a way to kludge together 3D perlin noise from 2D perlin noise. it's not going to behave correctly
This is going to be symmetric around the Y=X line
why not just use the Mathematics package?
it provides a correct implementation of 3D simplex noise (it has classical perlin noise too, if you want)
install it from the unity package manager
it's in the Unity Registry, like a bunch of other common packages
using Unity.Mathematics; will allow you to use noise.snoise
float3 vec = new float3(x * xScale, y * yScale, seed);
float result = noise.snoise(vec);
roughly like this
It looks weird now
private bool TileIsLake(int _x, int _y, WorldGenerationData_SO _generationData)
{
float noiseMultiplier = 1f / _generationData.lakeNoiseLayers.Length;
float totalNoise = 0;
int actualSeed = (int)_generationData.seed * 2000;
for (int i = 0; i < _generationData.lakeNoiseLayers.Length; i++)
{
totalNoise += noise.snoise(new float3(
_x * _generationData.lakeNoiseLayers[i].noiseScale.x,
_y * _generationData.lakeNoiseLayers[i].noiseScale.y,
actualSeed + 200 * i));
}
return totalNoise * noiseMultiplier < _generationData.lakeMaxValue;
}```
what is snoise? is it simplex noise
This noise may have a different frequency than the perlin noise you were originally using.
Yes, simplex noise
You can use noise.cnoise instead to get classic perlin noise. I dunno if that will look different or not.
It'll probably be closer in character to Mathf.PerlinNoise
ples
uuhh why does the sound has "gaps" or "crackling" , when encoding and decoding audio fom microphone using opus, if anyone can help?
It seems like the values are different. What are their range? I know that Mathf.PerlinNoise() returns values from 0f to 1f
Ah, of course!
simplex noise is -1..1
You just need to remap it
float remapped = math.remap(-1, 1, 0, 1, result);
another Mathematics function (:
you could also use Mathf
float t = Mathf.InverseLerp(-1, 1, result);
float remapped = Mathf.Lerp(0, 1, result);
note that, in this case, the lerp isn't really needed
since the value is already in the 0..1 range
but if you want any other range (say, 0 to 3), you'd need the Lerp as well
You can mix-and-match the Mathf (built-in) and math (Mathematics package) functions
One thing you may be interested in later, though...
Computing perlin and simplex noise is relatively slow.
One cool thing Unity can do is called Burst compilation. It converts C# code into native code ahead of time.
Burst can only work with certain kinds of primitive data and certain methods.
Everything in math and noise is compatible.
wdym
[BurstCompile]
static class NoiseMethods
{
[BurstCompile]
public static float Noise(float t, in float2 vec, in float2 offset)
{
return noise.snoise(vec * t + offset);
}
}
I just realized I should be using 3D simplex noise here instead of an offset lol
do as I say, not as I do...
what dont u understa nd
NoiseMethods.Noise runs a lot faster than just calling noise.snoise directly, because Unity can Burst-compile this into native code.
This isn't something you need to do right now, but it's part of the reason I really like the Mathematics package!
what the problem is
the if statement is working and i onlywant it to stop walking and stop playing animation for walking when variable is false
show current code
yea but that is not going to really effect the code
Well it is not stopping walking when the walkCurrently variable is false
show the animator transitions
for false
fair point

