#archived-code-general
1 messages · Page 385 of 1
Why my NAVMESHAGENT doesnt go towars the target?
- it rotates towards it
- i can see the gizmo in the scene that its trying to walk towards it
- but for some reason its not walking.
is it layer? terrain layer is Terrain
Native arrays are basically a wrapper around a pointer so I would say no
Wouldn't it still bypass bound checks?
Your raw pointer ? Sure I guess but how much speed up is that
NVM FIXED
Do I have to?
I want to make an instance of myTile class to be able to be null
Without throwing a NullReferenceException
if Tile is a class then it already can be null
nullable reference types wasn't enabled by default until .net 6
Hey everyone.
In one of my current projects, we have an array to edit values in inspector for a dictionary<enum, float> mapping rarity to some values to apply some stat upgrades. We sorted them by rarity so far, ofc it's errorprone, but a problem for another day. My current "problem" is, when using .ToArray() on some of said dictionaries, can i assume order will be the same as displayed in inspector? In OnEnable the dictionary is cleared and array elements are then added one by one. How could i test this?
dictionaries do not have an order, so no.
If you need the order to be preserved, don't use a Dictionary.
You can make a struct and just have a List or Array of that struct
how should I silence warnings from plugin code?
do i have to modify the script with this issue or are there settings in unity somewhere to ignore warnings from a specific folder, for example
just use the new function
don't ignore issues, just solve them 🤷♂️
takes one second to switch it to new function
look how easy it is.
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
Obsolete: This function is obsolete, use Object.FindObjectsByType instead. This replacement allows you to specify whether to sort the resulting array. FindObjectsOfType() always sorts by InstanceID, so calling FindObjectsByType(FindObjectsSortMode.InstanceID) produces identical results. If you specify not to sort the array, the function runs significantly faster, however, the order of the results can change between calls.
there is also a way to silence a warning with a pragma warning disable in your script but its obviously better to fix the warning
it's in leantween
So kinda understandable to want to just mute it
We should yell at leantween maintainers though
Theres already a premade unity gitignore. You should use that instead
I'm looking for some direction regarding implementing a game bot behavior. I've implemented Context-based steering, so I can force my bot to go towards some target. However, I'd also like to give the bot directions towards a target, maintaining some distance ~D. The game space is on a horizontal plane, so I essentially want my bot to keep its position on a circle with center C and radius D. How might I modify context-based steering to account for this?
I can probably hack something together, but I imagine this has already been solved, and I do need my solution to be performant.
You should not be ignoring the Packages and ProjectSettings folders
those are necessary folders for the project
You often need to update the game state much more often than the framerate of the game, especially for physics. You only update the visuals when needed.
Is it best practice to fix plugin code yourself? Idk I feel reluctant to touch stuff - what if there’s a lot of warnings and it’s not a good use of time to sift through it
not usually but this case would've been okay, but its not big deal since it probably will still work till a few version
its up to leantween mantainers to update the actual asset to the new Unity 6 api
Thanks for the answer 🙂
next time. dont crosspost, in a coding channel especially
k, sry
Hi, I need help with a design pattern for a bullet hell game. The bullets have a wide range of properties: some rotate, accelerate, stop periodically, change direction randomly, or resize based on distance to the player. I’m struggling with a large, inefficient script to handle all this, especially since I’m limited to using primitives for bullet updates (no classes or inheritance). Any suggestions for a cleaner, more efficient approach?
Ideally it's easy to add any super specific behaviour without clutter...
To better explain, my old script had like dozens of parameters to create any behaviour, and the update function was a big unreadable and slow mess.
Like 80% of the function didn't do anything useful as most bullets never used all the super specific behaviour all at once.
inheritance or composition, that is the question
Ideally yes, but again no inheritance in the OOP sense is available. Only primitives like structs
wdym by that ?
I can't make classes and have others inherit them.
uhh is this some type of mod or something ?
No, as the amount of bullets is quite large, so I'm making everything work in unity jobs. They only allow primitives
ohhhh okay you're doing DOTS?
I guess you could say that
hmm Ig you could use interfaces and implement specific behaviors on each?
interfaces aren't *supported in job structs either
ah ok I only used small amounts of ECS haven't touched too much n Jobs , maybe someone else knows here 😅
Yeah it's alright, thanks for taking time to try to help me anyway!
goodluck! 
@zealous lagoon you would be better served in #1064581837055348857 / #1062393052863414313
Well I read online you can't use interfaces, I guess I should actually check that before I claim so.
I'm not actually using DOTS, I just use data oriented programming for the bullets, each one is a struct which I update with jobs.
If it’s the C# job system, that falls within the dots purview
oh alright, I guess I'll repost there soon.
Also seems like interfaces work just fine, whatever forum I read seems to have been wrong
yeah could've sworn I used them in the past inside a job struct buts its been a while since I touched anything dots
okay yeah you can store structs that implement interfaces, but you can't store an interface type.
I still have no ideas how to do this well
interfaces are reference types which are managed, can't used managed objects in jobs
yeah okay
I think I might have to give up on the multithreading I got working, I just cant figure out any good way to handle this problem. I need my classes 
Sorry for spamming the channels so much, this is my last message. Turns out the performance gained by multithreading.. is negligible? I get a 2 fps difference running 1 vs 8 threads... Im out.
Does Unity provide any tooling for running C# as a script? I just want to test out some of my utility functions
vs debugger
unity has the test framework package to perform unit tests
is it normal that navmesh stops rotating after reaching its destination? Resulting in some real silly rotations.
navmeshes don't rotate
navmesh Agents , rotate on moving yes
Sorry for spamming the channels so much
If I have 10 functions that I want to call in a sort of pipeline, is it better practice to nest the calls inside of each function in the order that they will be called, or to have all the functions called from the same function and just pass the variables onto each other from there?
so like func1 calls func2 calls func3 vs basePipeLineFunc contains func1, func2, and func3 calls
In the first way, func1 is now hard coupled with func2. Eg if you have 2 places where you use Fn (which calls NestedFn1), but now you have a new place where you need to use Fn but want it to call NestedFn2 instead of NestedFn1, you have to make a NewFn that has the exact same code as the old Fn except calling NestedFn2 instead of NestedFn1.
This hard coupling doesn't necessarily mean it's bad though, sometimes you do want them to be hard coupled/hidden from public API. So it's situational which one you should go for.
Yeah I was also thinking second way is better because you can see the whole control flow from one function instead of having to run across 10 files
It's situational, not necessarily better.
what's your preferred way of defining items/abilities/monsters/etc in a JRPG-type game? dictionaries of entities you define at load time with its variables and delegates? different classes that share interfaces that get instantiated when needed? something else?
maybe scriptable objects but which reference hard-coded methods that take in parameters stored in said SO? 🤔
If I have 10 functions that I want to
Probably a combination of all the things you mentioned. The data itself could be stored conveniently in SOs.
Suppose I have a list of functions List<Func<S, bool>>, and I want to combine them into a single function Func<S, bool> with OR, AND, etc., i.e. is_hungry_and_thirsty = and([is_hungry, is_thirsty])
Is there a C#-native way to combine them, or will I have to make my own wrappers for this? I'm forgetting all of the specific Functional programming lingo
obligatory
. items abilities and monsters are all different in how you can define them. for example a monster could just be a prefab, that prefab can contain monobehaviours defining what the abilities do. Monster stats can be populated via SO. Items would probably just be best as an SO
my main worry with SOs is that I'm not sure how to make a neat structure for the delegate methods
tried something before using enums as identifiers that would appear in dropdowns on the SOs, but seemed odd
specifically right now I'm thinking about implementing abilities, which are shared by allies and opponents, so it wouldn't make sense for the behavior methods to be part of the prefab
could you not just do is_hungry(whatever S is) && is_thirsty(S)
without seeing how youve defined it, its hard to really say anything. are you talking about the abilities here? what part here are you trying to use delegates for?
also what do you mean by shared abilities? if the ally and enemy can both have the same ability, both ally and enemy can have their own instance of that ability.
the alternative is defining this in code, which really sucks imo,
or trying to serialize a type (or something that you associate to the type like your enum)
by shared I meant that technically every character could learn any ability, so procedurally generated enemies and serialized party members both use lists of references to these abilities
the ability class itself will likely need methods to determine if an ability can be used given the character's state, where the ability can be used on the battle grid, special behavior when the ability is used and/or special behavior when the ability hits each target, etc
so essentially... lots of stuff hard-coded called at different moments 😅 not sure if I can parametrize each method or if I should keep it easily editable
then yea i could see it being reasonable to not have your abilities be monobehaviours. and yea everything youve described (if an ability can be used, etc) can just be defined on the ability itself, which you likely should be using inheritance for.
im still not really sure which part you're referring to for the "neat structure for the delegate methods". there isnt really much of a structure, when you're given an ability you can just subscribe to everything that the base ability class provides. if you ever lose abilities, unsubscribe. alternatively ditch the delegates entirely, let the ability itself call methods on the characters/vice versa
well, with a SO approach, with just a single Ability class inheriting ScriptableObject for the commonly editable fields (e.g. display name, targetable units, damage, range, etc) how do you associate that object to a method for unique per-ability behavior?
in a different project, I had an enum of item IDs, each SO would be assigned the correct unique ID and then a dictionary of behaviors would pair the unique ID with delegates... but it was pretty annoying to manage
Nothings stopping you from making more derived classes from Ability, though still the SO here should purely be for assigning data in editor. You then could either create instances of SO at runtime to use, or just create a plain c# class and then now have a unique instance.
Directly referencing the SO here would be very limiting, your abilities wouldnt store state.
Maybe share an example of what you mean, because to me it just seems very simple in just calling methods when needed here.
could you not just do `is_hungry(
Ability + AbilitySO combo
for example, a teleport ability- if each ability is its own class inheriting an interface, then once the target cell is selected, I could call the Trigger method from the interface, which would take care of moving the character's position
but instantiating an object is a bit redundant since there's no state change, so a single instance per ability would work... perhaps at load time, a new Ability object is instantiated and the Trigger is a delegate passed as argument
but then all other fields are hard-coded and I'm not sure how to implement that with SOs-
AbilitySO = read, no touchy
Ability = everything else
hmm 🤔 so initializer with delegates as above, but other than delegate arguments, it takes in that ability's SO? that could work... if I can make sure no duplicates
You can stick initializers on the SO too (to instantiate* the Ability prefab) and just pass the SO around instead of referencing some prefab manager
how do you do that? only way I can think is by using sub-classes inheriting the Ability SO... which isn't so bad if those sub-classes are re-used across multiple abilities otherwise feels a bit tedious
also not sure how it'd work out with polymorphism? characters would have a list with Ability SO type so would it work with the sub-class' initializer?
public class AbilitySO: ScriptableObject
{
[SerializeField] private Ability abilityPrefab;
[field: SerializeField] public float Damage {get; private set} = 10;
//Maybe add some Entity parameter for positioning/assignment
public Ability Init()
{
Ability newAbility = Instantiate(abilityPrefab);
newAbility.Init(this)
return newAbility;
}
}```
Hey hey everyone, so I'm currently dealing with what I believe to be some form of Unity bug (correct me if I'm wrong) where if you disable a parent object with a toggle group and then enable it again, none of the toggles will be on or the default one will be on, but never the last enabled one.
I'd say that it isn't precisely a bug but more a consequence of how it is designed.
Note that the Toggle Group will not enforce its constraint right away if multiple toggles in the group are switched on when the scene is loaded or when the group is instantiated. Only when a new toggle is swicthed on are the others switched off. This means it’s up to you to ensure that only one toggle is switched on from the beginning.
The typos in the manual are absolutely bugs though =p
Sure but its already instantiated
Unless the group is uninstantiated when its parent object is disabled
But yeah my problem seems to have nothing to do with that
There is also the issue that when anything is selected thats not a toggle, they all disable
Hello everyone, I don't understand English well, so I apologize in advance
How can I make sure that when I hold down the right mouse button, I can rotate around the character?
Guys do anyone know how can I use github with unity?
Don't crosspost
Sorry for that
Keep track of previous mouse position. Rotate based on difference with next frame
Also known as "delta"
You can also use axis like you have now. If something is wrong then I suggest you explain that
I asked the same question, and I'm trying to find the comment that answered my question, but it seems like the memory of discord is fickle...
so basically getting git to work boils down to a .gitignore and git lfs for specific file types
git lfs should track .png and .fbx
and the .gitignore can be found here:
hopefully that helps
I'm fairly new to unity too, so I hope this is useful, and I didn't forget to mention something
this is also interessting:
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
What are common patterns you've all used for coding time related things
you've got your update function that updates with delta time
but you can also use async and await
Hello, I'm trying to make a ConditionalHide attribute, which I create like this:
[ConditionalHide(nameof(SpawnType), SpawnMde.SIMPLE)]
It works by checking values of enums of certain variables. My problem is accessing the field that I specify, it results in null exceptions in certain nesting situations, like accessing a variable in it's parent.
OnGUI()
ConditionalHideAttribute hideAttribute = (ConditionalHideAttribute)attribute;
// Build the full path to the list property based on the nesting
string fullPath = property.propertyPath.Replace(property.name, hideAttribute.ListFieldName);
// Find the list property using the full path
SerializedProperty variableProperty = property.serializedObject.FindProperty(fullPath); // This is null
I see no logic here that would allow you to access a variable "in it's parent", just a dangerous Replace
If you want to do something more complex (and robust) you'll have to write a more complex function to maniplate the property path
Sure, I'd do that
I just have no idea how
Is there some cool place to read on how these paths work
No, just use the debugger or log out the path and take a look
Alr
Ok so when you pass using nameof it only has the name of the variable, which I guess makes sense
but I can't find any good way to locate where the field is
like is it in the current object, a child, a parent etc.
my current method just relied on it being in the current object, but thats not neccessarily always true, which is when I get null
ok I dont see any good way to do this, so I guess I just wont use the attribute unless it's in the same object (which sucks but idk how to fix)
is jetbens the best ide for coding
its up to you if you want to use Rider or not, I have no opinion since I have never used it, picking your IDE is personal preference really
🙂
I have already downloaded them and Ig everything is setup but my question is how could my frined see the changes I did to the project or how can I see the changes that my friend did to the project
Git add filename adds a file to tracking
Git commit -am “a message saying what you did”
That line creates a save point for all added files that have changes
Git push -u origin yourbranch
This pushes your branch to the remote repo
Git checkout yourbranch
Picks the branch you will work on
Git pull
Gets all changes on the branch
That is git in a nutshell
keep in mind this is SLI pushing and pulling, github desktop has an easy GUI for beginners as well
@sharp lodge One of the hardest things about git is learning how much you can trust it
it is very hard to permanently delete stuff if you avoid the -f option
and you will at times mess up your repository, and be cursing how to get the thing in order again
but it is rare then you'd think, and you'l figure out how te get things in order again with some posts from stack overflow
Look my friend who made the file and he made repository to the game file
And now I should make like him and link the game file in my computer
My question is how to do that?? @shrewd tendon
to get files to your computer you use git pull
I have to run now though
wife will murder me if I don't
and that means I won't be able to finish my game or help you anyway
bye
I will go to your Dm 🙂🙂
Or I will just search to git pull
Hi, i keep having the issue that if i don't use the lookAt function, the camera always looks 90 degrees to the left of whatever i copy the rotation from. Why is this and how to I fix this elegantly without just adding a +90 degree manual offset
You're confused about what direction the object you're copying the rotation from is actually facing
Not really, even if I use cam.forward = player.forward the rotation still is 90 degrees off
Then player.forward is 90 degrees off
Proper way is to track stuff using timestamps because this is also multiplayer friendly
But even if you don't care about that it's much easier to use since you have a general idea of when something passes time wise
And if you don't then turn it into a DateTime
Or just use Github desktop like dec_ves already pointed out
Especially when you're a beginner there's little reason to learn all these commands when github desktop is a very easy to use GUI application that does it all for you
Wth is dec_ves??
what
I guess you haven't seen their message then
Regardless, don't bother learning the commands yet
Git has a lot of features, but you don't need any of them apart from the ones that are much easier to use by using Github Desktop
yes use github desktop as it has a built in GUI and SLI is not for beginners #archived-code-general message
but the player rotation is 0, just like any other object
Guido Sales Calvano also gave you bad advice with various steps so that just proves how difficult it can be
you could use some other git hosting software/website but I do not really use anything else but github desktop, it just works™
Player rotation has nothing to do with it. Your player model is facing the wrong way. Select the player object and show a screenshot of the scene view
my player is a bean right now xD I got so frustrated testing that I made a new testing scence
K tysm
🤍
right, the blue arrow is player.forward
Hello! Does anyone know of a less expensive or open-source WebGL AR library for Unity?
I'm looking to create a WebGL build with AR functionality, but all the available solutions seem quite expensive. Here are some examples:
Imagine WebAR World Tracker - https://assetstore.unity.com/packages/tools/camera/imagine-webar-world-tracker-248561
ZapWorks Universal AR for Unity - https://zap.works/universal-ar/unity/
ZapWorks works well, but removing their branding costs over $3000. Even with their branding, there’s a subscription fee of $13/month.
I'm also curious about how these plugins are made and would love to learn more about the process.
I am open to suggestions even if there is any other tool through which I can create a physics-based web AR experience, with plane detection
ohhhh, well that explaines things... thank you xD
Is Unity 6 stable enough for production to be the better choice for a 2D physics game? Removing the splash screen is the main advantage
codemonkey reported that outside of some obvious screw ups on his side that crashed everything, the 6th version is more stable, albeit this was said about pre-lts version so it could've changed
i would say to give it a go, while in developement it will just be battle-tested and if deemed unstable switch(with all game logic and asstets ready should not be such huge undertaking)
More stable than the 2022 LTS is impressive! I'd love to hear from anyone who's using v6 LTS
honestly no idea, i have stopped working with unity before 2020 and returned only now with upgraded setup. though, for simple prototypes v6 lts holds up nicely as i play around right now
have not tested further yet so, sorry no intel
no worries!
Anyone using v6 LTS who would give 👍 👎 compared to 2022?
how 2 make input field interactable? i mean, i have 3d tmp with component input field but when i click on it - nothing happens
where did you find a 3D Inputfield?
hy i tried to learn using a Video Player and i want to play a video thats on youtube using URL but i got an error
WindowsVideoMedia error 0xc00d36c4 while reading
after searching its says that its unity editor bug?? is there a way around to fix this error?
https://discussions.unity.com/t/getting-windowsvideomedia-error-0xc00d36b4-on-some-devices/826148/47
unity version : 2022.3.8.f1
public void SetVideo(string url, VideoPlayer vp)
{
videoPlayer = vp;
videoPlayer.url = "https://www.youtube.com/watch?app=desktop&v=nADTdV8wsXQ";
videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
videoPlayer.EnableAudioTrack(0, true);
videoPlayer.Prepare();
}
The post stated that the Former Unity Staff member wasn't able to reproduce the error and the error he assumed the OP had was a missing codecs error (Googled the error code). He suggested filing a bug report but never continued responding because likely this may have been an issue on the users end (missing codecs on the users local machine to play the file format)
Are you able to play the video file locally outside of the web browser?
locally you mean that i should download the video first then play it? right? if so yes.
What's the file extension of the video?
mp4
I'm not sure but this could be related if you're using Nvidia
https://www.reddit.com/r/WindowsHelp/comments/17gdqae/video_playback_in_some_unity_games_not_working/
Other than that, you can try asking the forums for official support - you may need to provide some system details like hardware spec, operating system, that you're able to play mp4 locally but simply not with the Unity Editor etc
I'm assuming there isn't anything wrong with the code/editor/editor-version and that it's Windows just being annoying
Thanks for the input i'll try to read it on reddit first...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour
{
InputManager inputManager;
CameraManager cameraManager;
PlayerLocomotion playerLocomotion;
private void Awake()
{
inputManager = GetComponent<InputManager>();
cameraManager = FindObjectOfType<CameraManager>();
playerLocomotion = GetComponent<PlayerLocomotion>();
}
public void HandleAllInputs()
{
inputManager.HandleAllInputs();
}
private void FixedUpdate()
{
playerLocomotion.HandleAllMovement();
}
private void LateUpdate()
{
cameraManager.HandleAllCameraMovement();
}
}
Assets\Scripts\PlayerManager.cs(28,26): error CS1061: 'PlayerLocomotion' does not contain a definition for 'HandleAllMovement' and no accessible extension method 'HandleAllMovement' accepting a first argument of type 'PlayerLocomotion' could be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\PlayerManager.cs(23,22): error CS1061: 'InputManager' does not contain a definition for 'HandleAllInputs' and no accessible extension method 'HandleAllInputs' accepting a first argument of type 'InputManager' could be found (are you missing a using directive or an assembly reference?)
can someone help
everytime i try to fix it i get more errors when i fix those i get these back
like im in a loop
well do those classes contain those methods?
Is player locomotion (the component) something you made, an asset or a built in type of unity?
I have the following switch statement:
(float[] weights, CharacterStrategy[] states) = (perspective.Character.State.Type, perspective.Enemy.State.Type) switch {
(CharacterStateType.ACTION, CharacterStateType.ACTION) => (new float[]{.8f, .2f}, new CharacterStrategy[]{_strategyDict["Rush"], _strategyDict["Wait"]}),
_ => throw new System.Exception($"Don't know how to account for {currentStrategy}, {perspective.Character.State.Type}, {perspective.Enemy.State.Type}")
};
Will the compiled code repeatedly reallocate the RHS values? I'd like to use a switch statement here instead of a dictionary because I want to make use of pattern matching, but I'm concerned that this will perform a lot worse because I don't know how else to specify the RHS of the switch cases.
i have a player locomotion script
using System.Collections.Generic;
using UnityEngine;
public class PlayerLocomotion : MonoBehaviour
{
public Transform cameraTransform;
public float movementSpeed = 5f;
public float rotationSpeed = 10f;
private Rigidbody rb;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
public void HandleMovement(Vector2 input)
{
Vector3 moveDirection = (cameraTransform.forward * input.y + cameraTransform.right * input.x).normalized;
moveDirection.y = 0; // Keep the movement on the XZ plane
rb.linearVelocity = moveDirection * movementSpeed;
}
public void HandleRotation(Vector2 input)
{
Vector3 targetDirection = (cameraTransform.forward * input.y + cameraTransform.right * input.x).normalized;
targetDirection.y = 0;
if (targetDirection.sqrMagnitude > 0.1f)
{
Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
}
}
}
Right, so it doesn't have a method called HandleAllMovement
yes. You can eliminate the first array alloc with a static array and hope nobody modifies its values. The second one you'll have to set up a cache of some kind so you return the same array instance each time
https://hastebin.skyra.pw/kixedinaro.pgsql
Problem with movement code: When climbing a slope, the player's speed decreases as it should, but it never reaches zero and goes down the slope, because the code that handles movement based on input is still active and adding to the speed, causing the player's speed to not be zero and making it crawl up the slope
I personally shoot a raycast down and check if the normal's of the slope are more than a certain threshold which Is a Boolean called steepslope then using that I turn off input for movement and add a force down (you could easily just make the collider for the player frictionless).
I'm not using forces or friction since I'm coding it all myself
I also have just 3 sizes for slopes, and I want the player to be able to climb them all if they have enough speed
Which is the problem I'm facing
When climbing up a slope, the speed is never a non zero number because of the code that handles movement based on inputs is still active
you would just decrease the speed moving up it when on a slope of an angle of your choice until it reaches a certain threshold then turn off inputs and move your character down it
this way you get the enough speed and if you do not have it, you will slide down it
I would also just make a hard cap for the slope angle as well so a player cannot break your map with movement, unless you want that
I tried disabling the movement code when the player is below a certain speed when climbing up a slope, but it didn't feel natural and also made the player stuck if they tried to climb a slope without any starting speed
you could make it so only above a certain speed can you slow down on a slope as well, you could instead of overriding the inputs, override the velocity make it go in the direction of the slope and make the movement speed lower so inputs do not overpower the slope "force"
float slopeFactor1 = groundSpeed * Mathf.Sin(angleRad) > 0 ? slopeDown : slopeUp;
groundSpeed += delta * physicsMultiplier * Mathf.Sin(angleRad) * slopeFactor ```
Currently this is the code that handles the slope adjustments, and it runs before running the input code
private void accelDecel(ref float speed, float accel, float decel)
{
if (Mathf.Abs(speed) < topSpeed || speed * directionHorz < 0)
{
speed += directionHorz * (speed * directionHorz >= 0 ? accel : decel);
if (Mathf.Abs(speed) >= topSpeed)
{
speed = Mathf.Sign(speed) * topSpeed;
}
}
}```
That is the movement input code
hi, I managed to create a grid mesh in a compute shader, however I get these weird black triangles every dispatch seemingly at random. (Black = no normal calculations done, so not processed by the compute shader). Is this just noise from allocating buffers?
Does C# IEnumerable have any implementation of ArgMax?
yes it was
can I not use tex2D in my URP vertex shader? I swear i have before
ah it was tex2Dlod
ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
This happens when I start the game while having SO selected in the inspector which contains null properties(in some cases)
Is there a way to avoid that, I can't really set all values to a value so they have to be null sometimes.
Actually it seems to happen regardless if anything is assigned in the inspector so that's even more annoying ;_;
What's the full stack trace
hello people
I ... would like to request to save a file on the players computer from webgl
ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
UnityEditor.SerializedObject.FindProperty (System.String propertyPath) (at <fe7039efe678478d9c83e73bc6a6566d>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindPropertyRelative (UnityEngine.UIElements.IBindable field, UnityEditor.SerializedProperty parentProperty) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.BindTree (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEditor.UIElements.Bindings.SerializedObjectBindingContext.ContinueBinding (UnityEngine.UIElements.VisualElement element, UnityEditor.SerializedProperty parentProperty) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEditor.UIElements.Bindings.DefaultSerializedObjectBindingImplementation+BindingRequest.Bind (UnityEngine.UIElements.VisualElement element) (at <c91a25f185b743118a39aafa100dff09>:0)
UnityEngine.UIElements.VisualTreeBindingsUpdater.Update () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.VisualTreeUpdater.UpdateVisualTreePhase (UnityEngine.UIElements.VisualTreeUpdatePhase phase) (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.Panel.UpdateBindings () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <79c7b132c51745cbae03eebea8111c0e>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <c91a25f185b743118a39aafa100dff09>:0)
type thing, but on webgl
where the player can choose the file directory and save it
#🌐┃web but use a JS plugin like https://github.com/Nateonus/WebGLFileSaverForUnity or write your own
hey guys, can one access the PlayerPrefs from one project to another?
my rigidbody isnt reacting to linearVelocity
nor linearVelocityX and linearVelocityY
'''
gameObject.GetComponent<Rigidbody2D>().linearVelocity = new Vector2(Joystick.GetComponent<UltimateJoystick>().GetHorizontalAxis()
* Time.deltaTime * 3f, Joystick.GetComponent<UltimateJoystick>().GetVerticalAxis() * Time.deltaTime * 1.5f);
```
3 backticks, also you should probably not be using deltaTime on a rigidbody
oh ok
did you put this in update? cause rigidbodies should be also moved in FixedUpdate, n always cache your components as well, you should not be calling GetComponent every frame / physics update
THANK YOU
it works now
omg ive been working on this for so long
gives cookie
/givecookie
I introduced a circular dependency into a factory pattern, and I'm really struggling to resolve it:
public class CharacterStrategyFactory {
Dictionary<string, CharacterStrategy> _strategyDict;
public CharacterStrategyFactory() {
_strategyDict = new() {
{"Rush", new CharacterStrategyRush(this)}, // ...
};
}
public CharacterStrategy Rush { get {return _strategyDict["Rush"];}}
// ...
}
public class CharacterStrategyRush: CharacterStrategy {
public CharacterStrategyRush(CharacterStrategyFactory factory): base(factory) {
_strategyTransitions = new() {
{CharacterStateType.ACTION, (new float[]{.994f, .005f, .001f}, new CharacterStrategy[]{null, _factory.Wait, _factory.Flee})}, // ...
};
}
// ...
}
The factory points to potential states to return, but the states also point to the factory which is trying to return said states, so the code breaks when it tries to access a value in the factory's dictionary which hasn't finished instantiating. Would it make sense for me to try to lazily evaluate the factory's return states, or should I go about this some other way? I like the idea of asking the state which other states it might transition to (and I do need the potential transitions to be tied to the current state)
Instead of instantiating everything in the constructor, you can instantiate things as they're called:
public CharacterStrategy Rush {
get {
if (!_strategyDict.ContainsKey("Rush"))
_strategyDict.Add("Rush", new CharacterStrategyRush(this));
return _strategyDict["Rush"];
}
}
I do this all the time for caching components when I don't feel like figuring out exact script execution order.
I'm using a mesh generator to create infinite seamless terrain that loads in chunks, the mesh itself lines up perfectly at the seams but the lighting is off. I tried recalculating both normals and tangents.
Are you baking the lighting or something? If not, then the only way the lighting wouldn't align is if the mesh isn't aligned.
Can you zoom on on the seam and see if there are any gaps/high differences between the chunks?
there arent any gaps, but also the mesh doesnt exist outside of runtime
are there any open source games being developed in unity
like i have a question how dose skill trees work and how can i make one like how how dose a skill get activated once some one clicks on it i need to know
just like dm me any resources u guys think might be helpful
you asking in terms of UI or the system behind that creates the functionality?
how do i get to make the transform cords to be in the center of the planet?.
This is the code i use to get the transform of the planet, the planet itself is an empty gameobject with 6 meshes as children and I'm getting the transform of the empty gameobject and get this result of transform center dislocated (I'm trying to explain as best as i can lol)
{
gameObject.GetComponent<Rigidbody>().mass = surfaceGravity * radius * radius / gravitationalConstant;
gameObject.GetComponent<Transform>();
gameObject.GetComponent<Transform>().localScale = Vector3.one * radius;
}
Move the children so that the center is where you want it
nah, i just needed to click on the toggle tool handle position and click center to get it centered 😭 , thank you anyway
That doesn't change where the actual center is
you mean that for example, if i scale the object, it scales based on the pivot instead of the "center" right
i mean, that is what im getting
you are correct
All it changes is where the gizmo is shown in the editor
Function terms
This is because the outer vertices dont have the same neighbors in every cell, so the normal calculation doesn't give the same result
How I would solve it is to have an extra row of quads on each side. Now recalculate the normals.
After calculating the normals, remove the triangles for the extra quads. They aren't supposed to be visible, they are just for calculating normals
If it doesn't make sense I can try explaining better
GUYYYYYS HELP..
- can i delete terrain grass (from terrain) via code at some position and then later add it again?
- can i (in runtime) get color or texture of terrain at some particular position?
- You can get the alpha maps with GetAlphaMaps:
https://docs.unity3d.com/ScriptReference/TerrainData.GetAlphamaps.html
Alpha maps store the weight for each terrain layer at each pixel
To sample it at a world position, you need to first convert the world pos into alpha map coordinates
There's guides on this online, especially if you look for "terrain footstep sound" tutorials and such.
so, I fixed my slope problem by making the slopeDown force weaker when you try to brake on it when going down, but now I got a different problem: When the player tries to climb a slope without any starting speed, he gets stuck. It looks awkward and unnatural, so I'm open for suggestions on how to remedy this
Oooh smart
I'll try that today if I can
So I am creating a game in which the player can change gravity, so sometimes the player will find that the wall in front of them now becomes the floor. However, I am making the game with an isometric view, the camera has right now the rotation (30, -45, 0) and looks like this
However, I am trying to make that when they change gravity to the front wall (for example), they have the exact same view that they have now but in a wall that is rotated -90 degrees in the X axis. I am trying to rotate every way possible the camera but I do not get any result that is similar to the image above when the player is in this wall. Basically, I want to have the same isometric perspective even if they are in the wall but with that wall being now the new floor. Anyone know how I could make something like this?
the trick I've seen for this is to rotate the level, not the player and camera. that gets tricky if you have physics objects tho.
damn, what number is this even?
Zero, the result of dividing zero by zero in float math, and a huge number
something went spectacularly wrong in some calculation
Well I have some features that would really get tricky if I turn the whole level, isnt there a possibility to rotate the camera itself and have the same isometric view?
nan stands for not-a-number, it's a value used to represent an invalid value, like 0/0, -0/0, sqrt(-1), log(-1)
weird, it should just be the x thread id, im prob not setting it right
next best thing I can think of is to make the camera a child of the player, rotate just the player, and see how that looks.
That actually works I just need to change the offset, it was so simple solution hahah thank you!
I got a weird problem
Basically,it doesnt work in the editor, but it does in renderdoc
is it right that mesh.vertices is used when setting MeshCollider.sharedMesh?
I'm trying to get started with NavMeshes in Unity, and I'm following this documentation, starting with this page, but I'm not able to follow it. It says to "select the scene geometry where you want to add the Navmesh" - what is that referring to? Google isn't turning up anything. I'm assuming this is tied to the "Scene" construct, but clicking on the Scene itself doesn't display anything in the inspector. I then thought that it might be that a given gameobject would contain the specified "Navmesh Surface" component (and maybe its children would contain the obstacles and such), but I don't see "Navmesh Surface" as an option for components. I'm using Unity 6, btw.
Suppose I have a Prefab that may or may not have a particular component at runtime. In my case, I have Character prefabs that may or may not contain NavMesh Agents. Is there any philosophy around the prefab having the NavMesh Agent component by default, and only enabling it if relevant, vs only creating the component if it's applicable to the agent?
I feel like you should just use prefab variants. The base prefab would not have the component and subsequently characters that need it, it is added on the variant
If there are 2 scripts, and both have an on collision method, but one script's on collision method disables the object, and the other scipt/s on collision deals damage, will the damage be able to be done before it is disabled
The scripts are on the same object?
Hey everyone! Looking for some advice. Currently working on a school project. Game is bartending but plays like a diner dash sort of thing. Currently trying to figure out best way to store recipes for the drinks. Was thinking of a scriptable object that stores what ingredients the recipe calls for as well as the amount of each ingredient. (Not designing the drink making to be done in an order, just checking to see if all ingredients and correct amounts are in). Currently looking at scriptable objects for ingredients and recipes just for data storage/checking to make sure user created the drink successfully. I'm trying to find the best way to have an ingredient listed as well as the required amount next to it visible and modifyable in the inspector. Any tips? Screenshot attached is what I have. Was going to turn what I have in the screenshot into a dictionary, but was hoping I could get some tips on best way to proceed. Obviously Dictionarys aren't serializable otherwise I would just do that (ScriptableObject, float). Really want recipes to be fully done in Inspector for ease of use for other members of the team (I'm the only programmer). Thanks!
yeah
It may just work, I don't know how reliable it is if it does though. You could delay disabling the object until the end of the frame to be safe
You'll need to write a custom editor script or if you are just looking for serializable dictionary, there are plenty of examples online. There's also one in the Core RP
Not in need of serializing dictionary, really just looking for the best way to store the ingredient and the amount next to it. Is that my best option?
You can serialize structs
Yeah just make custom data type that contains a field for ingredient and amount, then you can have a list of those
You can make a custom property drawer to make it look how you want in editor as well
public class Drink: ScriptableObject
{
[Serializable]
public struct DrinkContent
{
public Ingredient Ingredient;
public int Amount;
}
public string Name;
public List<DrinkContent> DrinkContents;
}
public class Ingredient: ScriptableObject
{
public string Name;
//Any other info
}```
something like that. Can also just make this an SO as well chopped it into SOs
I would say a class makes more sense for the recipe than a struct
Probably an SO if you want to move the instance on the editor besides one place.
Definitely prefer to do SO. How would that approach work?
updated. This chops everything into instances if you just want it all to be done on the editor
Thanks! Gonna take a look
Oh that's wonderful! Thank you so much, exactly what I was looking for
If there are 2 scripts, and both have an
hi
hello
Hi
hi
I’ve developed a game for a specific camera aspect ratio, but when I play it on a different phone, it completely messes up the gameplay. What are some possible ways to fix or adjust this? Any advice would be greatly appreciated!
sry for using ai to ask me quetion english be shit
This is a code channel. Also https://docs.unity3d.com/Packages/com.unity.ugui@2.0/manual/HOWTO-UIMultiResolution.html
is there a way to make code where the sprite renderer does a Look at Function and not the whole game object
sorry i wasnt clear
i ment the game changes up not the ui
ill show you an example
i want it in the secound pic to be with like black bars to make sure its the same size
the game is not playable on my game
i tried using this code
{
Camera.main.aspect = 16f / 9f;```
but its just squish it instead
This is calculated automatically, if you force it to different aspect it will not correspond to current resolution.
Find a tutorial that explains how to support different resolutions on mobile devices (for fixed 2d view), it's an involved process, you need to design for it.
@sleek bough this before putting the code in
oki
{json} is correct and has all the right values.
Yet the bottom print statement only shows ID is correct, everything else is default. ??
LevelCompletionInfo has a [JsonConstructor] which takes all the values and assigns them. How does this make any sense?
public LevelCompletionInfo(int id, bool heart, bool diamond, bool club, bool spade,
int wins, int streakWins, int highScore)
{
Debug.Log($"creating levelocmpletioninfo. id: {id}, heart?: {heart}, highscore: {highScore}");
levelID = id;
heartAchieved = heart;
diamondAchieved = diamond;
spadeAchieved = spade;
clubAchieved = club;
totalWins = wins;
winStreak = streakWins;
highestAmountLeftover = highScore;
}```
once again, only id is correct
AH my bad, it's because levelID is a field and the rest are properties. I guess it only can deserialize into fields.
Hello.
Is it possible to debug a standalone build in the editor?
I am trying to make a mod for a game, of course I don't have the project for it
But I can't seem to figure out how to add (old) UI elements to it, so I'd like to debug the game objects in the editor
Is it possible at all?
No. You can't open a standalone build in the editor. You can attach various tools, like the console and profiler to a development build but that's about it.
The way you debug a build is usually by attaching a debugger of your ide.
Yeah, I could get that working
But trying to decypher why the ScrollRect refuses to draw it's contents is beyond imesurable pain, if possible at all
The problem could be anything at all, as far as I know
It might be difficult to figure that out just by debugging the build. You should be looking at the active/enabled states of the objects and components that you expect to be drawn as well as their transform/text transform properties to make sure that they are where you expect them and scaled/rotated the way you expect them to be.
Is it possible to get the a development standalone build to draw gizmos or Debug.DrawLine?
That way at least I could figure out if something is drawing under the UI/mask at 0width, etc
I didn't realize that ScriptableSingleton lives in UnityEditor, and I need some sort of globally accessible Singleton for processing things in my gamestate. How should I go about that instead? I can't use ScriptableSingleton in a build of the game
No. The beat you could do is maybe use some line renderer(though you'll need to convert between screen and world space positions).
can someone help me I im new at code so I don't know what is the issue with my code please help me.
Make your own singleton..? Also, a singleton SO doesn't sound like a great idea anyway? Does it have to be an SO?
Ah, it's not an SO?
If you're new, then ask in #💻┃code-beginner
ok thank
I guess I will do the least bad thing, if anyone got a better idea please tell me
hmmm
ScrollRect-> Viewport->Content has a VerticalLayoutGroup yet it's children are not being laid out. I've even ran VerticalLayoutGroup.CalculateLayoutInputVertical(); after they got added to ensure they would get laid out on the frame I queue the print
Do they have a rect transform and a graphic component?
yes, although this code is slight modified to enable manual layout
After a lot of time, I've managed to get something to draw on screen.
But why does text refuse to draw?
That's how I instantiate a list item. While it works just fine for the Image, the text does not draw at all
is the text perhaps white
yes? It should draw white
modifying UGUI in code is a pain
Maybe try text mesh pro text component, instead of legacy(assuming that's what you're using).
is there a reason this isn't all prefab'd
I don't have the project, I am making a mod through Harmony
Gotta make your own non-editor Singleton template
Changing from Text to UIText did it. I can finally get somewhere now
white text on a white background isn't going to show up lol
My mistake, I didn't post it before. The leather bag background would draw with nothing on it before I added an Image to check if it was even in the right place
I can't add Image and UIText at the same time on the same gameobject it seems
anyone know if theres a way to change how enums are displayed in editor? these are supposed to say "AmPower" not "Am Power"
oop found it! it's the InspectorName attribute
is there a way to instantiate a gameobject into a scene on the root of the scene instead of the child of what spawned it
It should go to root, if you do not pass any transform, doesnt it?
lemme double check
ok so it doesnt have it as a child but now i need it to spawn where the spawner is
Then read the docs.... its all there
this is a chat to ask questions but thanks
For sure it is, if you tried things yourself upfront. Reading the docs is the number one thing you should be doing when using a method in unity. Just my advice, to get the best help here if you really need it and how to handle things upfront to solve it yourself. Docs is always the way to go for any development purpose 🙂
definitely, ive been using the docs throught this recent project. This is the first time im coming to the discord for help because these two parts have been giving me trouble and i was running into dead ends. thanks for your small help but not a great way to make a new user feel welcomed.
you will find out while being here for a longer time, but sorry, if it felt too harsh for you
dude its a discord for a game engine, you're acting way to serious.
people are spending their time here helping others for free, at least some effort is expected from the other side
Use GetSiblingIndex and SetSiblingIndex if you want to control the index of a gameobject in the hierarchy
I think, the person meant the actual position in space, not the hierarchy position 🙂
Oh, I assumed this was in the literal hierarchy, close to the spawner there and not in the world.
Hey all, I want to ask a question about Collider2D OnTriggerEnter2D events.
Let's say I have a script inside of a GameObject that contains the Trigger Collider I am hoping to get an event from. How do I know that when I receive the OnTriggerEnter2D event, it belongs to this specific Trigger Collider I setup in the same GameObject, and not a random one from the scene?
I am still new to Unity so I'm not sure how we link or know which TriggerCollider we are listening to in any script.
Your OnTriggerEnter2D contains a parameter Collider2D as you specified. If you want to ensure it belongs to a specific gameobject you can use tag checks, for example
Alternatively check for a component ont he gameobject that it must implement, or have some sort of metadata on it to check for
Kind of depends what you look for specifically
Does this mean that I have to call OnTriggerEnter2D from some update function?
No. What exactly are you trying to do? Because you have all the info you need in the parameter mentioned
I have Collider2Ds setup for every swing of an attack by my character, each attack object contains a small script and a collider.
I want the script to check for collisions when triggered to decrement enemy hp. The colliders and enabled and disabled by another script managing animation events and attack swings
From the docs: Sent when another object enters a trigger collider attached to this object (2D physics only).
It gets fired on that specific object, not globally on all and neither does it have to be checked, thats what the physics update loop does for you already. Check this graph for understanding, when what happens: https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
I see so I will only receive this event when the OnTriggerEnter2D is within the same object as the collider?
the ontriggerenter subscribes to your collider set as trigger. When another object enters this collider, it will call this method in your script. The script and the trigger collider of course have to be on the same object, otherwise they wont get the call
Okay thanks a bunch!
quick question, I want to sort my script in folders with assembly defenitions to make the compiling time faster but when I am trying play I get warnings and my game doesnt work, and then I see that I can search for script in add component and the already added script does not have showing(public) values. Someone know a solution?
The documentation for assembly definitions details all the requirements for using them. It’s mainly about them referring to each other correctly. The primary caveat is that they cannot refer to each other in a cyclic fashion.
Hi, I am having trouble with getting my OnTriggerStay2D to return any response. This is how I have things setup, could anyone tell me what I am doing wrong please
public class AttackMelee : MonoBehaviour
{
public AttackData m_attackData;
public List<string> m_targetTags;
private void OnTriggerStay2D(Collider2D collision)
{
Debug.Log("Triggered Collision of Attack Collider");
if (m_targetTags.Find(tag => collision.gameObject.tag == tag) != null)
{
collision.GetComponent<Mob>().OnHit(m_attackData.GetDamage());
Debug.Log("Attack Detected");
}
}
}
The box collider for Attack1 is enabled and disabled with AnimationEvents elsewhere, I have verified its working correctly
is the collider active?
it is when the attack is
r u sure? n does the attack gameobject stay active?
the gameobject is never disabled. I also checked the activeness of the collider when using the attack, it toggles on and off perfectly when the attack frames come out
is ur enemy thing in the Mob layer?
yea
I dont really use those dropdowns before, i usually use the old school Physics layer based collision, but your Enemy does seem to have included layers set to "Nothing" maybe it needs the actual Player layer there to enable collision/trigger msgs between the two
doesnt seem to make a difference unfortunately 😦
have you tried running this on a staic / non moving enemy ? like not moving by code or anything
just tested it, doesnt work either, how do you do it if you dont mind explaining it? I have never done this before so I don't know where to get started haha
do what exactly ? put like a plain 2D box thats big enough with collider2d and a rigidbody, no scripts or anything. Try attacking it and see what happens. Dont change any layers option on the collider
melee combat in 2d? how'd you handle registering them i mean. ill try the debugging step too ofc
honestly I dont use those physics messages. I usually do physics queries in code so I dont have to rely on Rigidbodies
functions like Overlaps, Casts
far more reliable
i see, i was planning on doing that initially but thought it would be hard to visualize the size of attacks, do you use custom gizmos to visualise them?
thanks for the help! the debugging steps made it work, seems the issues were with the layers. and rigidbodies were not needed for it to function (unlike what forum posts said)
well yes at least 1 rigidbodies IS needed between the 2 colliders
and yes you just draw gizmos, although the 3D one they have nice Visualizations built in the physics analysis now so drawing gizmos is no longer needed
would that mean the rigidbody of a parent count towards the required collision?
thats pretty nice
yes a parent rigidbody makes the child colliders belong to the parent rigidbody
Hello! I'm trying to work with a custom track/timeline and most documentation links I find point to nowhere land. I see this discord does not have a channel for timeline/playable/director (there's one for animation, but i'm not doing animation at the moment) so I figure maybe that feature is getting deprecated 😄
none of those are getting deprecated any time soon
playables are quite useful , and sadly the documentation for them is very scarse
I'm looking to do a couple of simple things and cannot figure out how. If you would be so kind to point me in the right direction, I'm trying to:
- Change the name that appears on a custom playable on the timeline track (Not just when the timeline clip is created, change the TimelineClip.displayName everytime the data inside the playable changes!)
- Change the color of the clip depending on which PlayableAsset it is
- Make the duration of a certain type of PlayableAsset fixed (i override duration, but it changes nothing, just the size it has when you create it). As in locking the duration of some PlayableAsset clips on the timeline (making them impossible to resize)
Well the documentation got pulled before the feature! If the feature is not going anywhere soon, I suggest a good first step would be to put the documentation back. On Unity docs a lot of it is tagged as deprecated and is simply not available for current version of Unity, despite existing in the engine
It seems like this feature stood on a lot of "user wisdom" that got lost when various Unity forums and blogs got deprecated too (Now most of the user knowledge I find redirects me straight to a 404 or to Unity Blog homepage). It is unfortunate all that knowledge got binned before anything came to replace it.
yes sadly thats a side effect to when they merged the docs for 6 everything got borked, a lot of links got broken
Unfortunately with its multiple layers of abstraction and great complexity, without documentation and prior knowledge this feature as a whole is barely usable. I come to discord for answers, knowing whatever help you give me will disappear under new messages and somebody will ask the same questions in a month
I have a thread mentioning the 404 issues, the ones i mentioned were somewhat fixed but seems not all, I would bring it up to the Unity Community Staff n they might relay it to the team. https://discord.com/channels/489222168727519232/1297593457614786650
Right now I'd just like to tackle these simple things but then i'd be happy to report broken forum and/or blog pages to Unity
Surely changing the color of a clip based on its PlayableAsset type cannot be this difficult, and I'm just struggling to find the right function to call 🙂
this channel was the best resouce I could find on this system
https://www.youtube.com/@git-amend
ah I mean before watching a whole channel I'm sure since this is the Unity discord somebody must have the answer right?
yeah but unless you make a thread and hopefully someone stumbles it, it will probably get buried in other help questions
Sorry I thought this was the help channel - where should I create this thread?
(Note that my problem is not related to animation, and only related to the scripting API)
you can create them in discord
also, I would probably just use the Unity Discussions page, you are more likely to stumble on Unity employees answering
So I should create a thread in that channel to get an answer ? Under this message for instance
or just bump your question, within reasonable time inbetween if none answer your question here
I thought thread had to be attached to a message, my bad
Simple clip customization on custom track / custom playable
it does; it just doesn't have to be an existing one
It’s beautiful seeing these two people interact.
Purple pfp, green name
Green pfp, purple name
Hi, i have a question regarding the MeshCollider.sharedMesh property. I procedurally generate my mesh on the GPU via a compute shader, passing it's index and vertex buffers. This works great, however when I try to set a mesh collider for it it detects some nan-values and other goofy values and is thus not able to cook the mesh.
The index 17 matches mesh.vertices[17], but not the GraphicsBuffer data from renderdoc
You need to have the mesh data on the CPU side if you want to use it in a mesh collider
so i'd need to use something like vertexBuffer.GetData(mesh.vertices)?
Not sure what API that is, but if you generate the mesh in a compute shader, you could just get the data from the compute buffers back on the CPU side and use it to create a Mesh object.
alright, ill try that, thank you
hello, i am trying to implement an a* pathfinding algorithm into my 2d platformer game and i just was wondering how i would go about implementing jumping into this algorithm. been searching the internet and couldn't find any meaningful help so came here as a last resort
jumping wouldn't really have anything to do with it unless you mean having the pathfinding allow for jumping.
In that case you'd just structure your graph to include edges between two nodes that can be jumped between
the algorithm itself doesn't change
just the structure of your graph
Define jumping in the context of your game first. Is it just an animation? Does it have a functional meaning as well?
it has a funcional meaning. i would like to find the optimal points for the player to jump from (change the y coordinate of a custom grid) to get to a specific coordinate faster
just a matter of structuring the graph to include jumpable neighbors as neighbors
instead of just walkable neighbors
That might be a bit beyond what an a* can do. Sounds more like a physics calculation. Though I guess you could incorporate it into the algorithm heuristics. It would just be super slow.
And properly weighting those edges
okay thanks guys i’ll do some more research on other methods and try to find a solution using a* if not by restructuring my graph
How can I convert an x rotation into a y position change?
w/o using a parent object
im thinking of using the euler thingy and just going from there but is there a built in function for this
That's really vague. You will almost certainly need to write some code
There are dozens of ways I could imagine that working
I have a bunch of textures that i need to slice. Each has a different Cell Size, which i can access during a foreach loop. How do i programmatically slice a Texture? (It's already set to Sprite 2D And Sprite Mode: Multiple).
Create sprites in code with https://docs.unity3d.com/ScriptReference/Sprite.Create.html
Are these saved into the assets or are they runtime objects?
Runtime objects, you can save them as assets if you want with further editor scripting
Aa! And how would i do that?
With the AssetDatabase class
Gotcha!
These wouldn't be saved as sub-files of the texture tho, right? Like with manually slicing?
This thread might also be useful to you if you wish to hook into the existing importer
https://discussions.unity.com/t/sprite-editor-automatic-slicing-by-script/577630/4
You can save them however you wish with editor code
Great! Thanks alot!
How would I do this? I tried setting thm like this, but I think that just using the GetData() also includes uvs, normals, etc c# Vector3[] tempVertices = new Vector3[mesh.vertices.Length]; vertexBuffer.GetData(tempVertices, 0, 0, chunkSize * chunkSize); mesh.vertices = tempVertices;
you should be able to use GetVertexBufferStride and GetVertexAttributeOffset to get the info you need to read the raw data, you need to be careful with alignment though
using UnityEngine;
public class MainMenu : MonoBehaviour
{
public Animator mainMenuBookHolder; // Animator for the book UI
public GameObject canvasInventory; // Reference to the Canvas that holds the menu
private bool isMenuOpen = false; // Track if the menu is open
void Start()
{
canvasInventory.SetActive(false); // Ensure the canvas is hidden initially
}
void Update()
{
// Listen for Escape key press to toggle menu
if (Input.GetKeyDown(KeyCode.V))
{
if (isMenuOpen)
{
CloseMenu(); // Close menu if it's open
}
else
{
OpenMenu(); // Open menu if it's closed
}
}
}
// Open menu with animation
public void OpenMenu()
{
canvasInventory.SetActive(true); // Show the canvas
mainMenuBookHolder.SetTrigger("OpenMenu"); // Trigger the "OpenBook" animation
isMenuOpen = true;
}
// Close menu with animation
public void CloseMenu()
{
mainMenuBookHolder.SetTrigger("CloseMenu"); // Trigger the "CloseBook" animation
isMenuOpen = false;
StartCoroutine(DisableCanvasAfterAnimation());
}
// Disable the canvas after the "CloseBook" animation finishes
private IEnumerator DisableCanvasAfterAnimation()
{
yield return new WaitForSeconds(1f);
canvasInventory.SetActive(false); // Hide the canvas
}
}```
can someone tell me whats wrong? i have no output errors
it s supposedto play an animation when it opened a idle one and another one for closing
sanity check it? can you make the sound play without ANY conditions? like in Start?
I tried it, now i no longer get geometry errors which is definitely an improvement, but I still get this error, and I don't really know what is happening:
I this because there is no density in the mesh? it's just a grid with a heightmap, but i thought that only mattered for convex colliders, i only need a raycast
How do I initialize an array of multidimensional arrays? cs bool[,][] arrayOf2DArrays;
I tried cs arrayOf2DArrays = new bool[5] as I need 5 2D arrays, but it didn't work. I need the 2D arrays to be of different dimensions
It would be a lot simpler to understand if you split this up. Like put the 2d array in it's own class, then make an array of that class.
I guess you're right 😅 Now I'm just curious if it's possible
Yes it is, I think this is what you're trying to do
https://stackoverflow.com/questions/7775458/how-to-initialize-an-array-of-2d-arrays
But it gets very confusing accessing elements when it's like this, so I really dont recommend
Your inner 2d array should be representing something specific, so making a class containing it will be useful. Then you can also make your own helper functions if needed
Right! Thank you 😊
How would I go about writing an algorithm to remove unnecessary vertices and triangles from a mesh to try and improve performance? For instance, how would I go about making a general purpose algorithm that takes this mesh from having 8 vertices and 12 triangle points to only having the 4 vertices and 6 triangle points it actually needs?
I don't see you assigning triangles. At the very minimum, a mesh requires vertices and triangles data to function.
Might want to google mesh optimization algorithms.
I tried, but I'm getting mixed results
Mixed in what sense?
Some of them seem to be more about turning the mesh low poly rather than preserving the same mesh but just getting rid of unnecessary vertices and triangle points
And others look, well, really dry. And dense
Dry and dense?
I'm not even entirely sure this is what I'm looking for anyway
Hello, does anyone know a good tutorial to make a generic FSM? Been browsing for a while and most of tutorials are either old, not generic at all, or have pretty different approachs.
Maybe look at "edge collapse" algorithm
Well, it's a lead at least
I'm getting a bunch of video results for "wave collapse". Please tell me that's the same thing
The hard part is retriangulation imho.
It's not. Search in the context of a mesh or 3d model
It's giving me the same search results
What's the problem with an old tutorial. Design patterns, like state machine don't change over time.
c# has evolved in the last 14 years, some stuff that was done before is now performed more efficiently
I've no clue what you're googling. I'm getting plenty of results
I was looking for Youtube videos since I figure that's where I'm going to be finding an explanation I understand. It's where I found an explanation I understand as to how marching squares work (which is now giving me the problem of thousands of unnecessary mesh vertices)
C# changes are almost always backwards compatible, so you shouldn't worry about that. And most stuff that was added is syntactic sugar any way, so the old way is always the best.
Besides, unity doesn't support the latest C# version anyway.
You're not gonna get many YouTube videos on such a complex topic.
It's like trying to build a jet plane by watching a YouTube video.
You'll need to look up research papers and sample code
The latter one is probably the best approach.
Btw, from the sound of it, it might be better to modify your marching squares algorithm or adjust it's settings to get less redundant vertices.
I've done it so that it gets rid of straight up duplicate vertices and I think I know how to get rid of unnecessary vertices, but I have absolutely no idea how I'm supposed to correctly triangulate after that
Actually, I'm not entirely sure I have a way to get rid of all redundant vertices
Well, that's part of the edge collapse algorithm. You'll need to look it up.
You'll need to use data from the removed vertices to create the new triangles
If this is what edge collapsing is supposed to be then I really don't understand it
https://graphics.stanford.edu/courses/cs468-10-fall/LectureSlides/08_Simplification.pdf
Which is to say I replace instances of the redundant vertices in the triangle list to the vertex they've collapsed into I'm assuming?
I think this paper covers many different techniques.
It doesn't really explain any in detail though.
Either way the first order of business is finding a way to identify the vertices that need to be collapsed, right?
Yes. That part would determine how much it would affect the mesh shape.
This paper is the first google result. You should look at the others too. The second one on medium seems to be quite a bit more descriptive.
Actually I think I have an idea I might be able to try. I'll read the paper if it doesn't work if you say it's what I'm looking for, though
The idea is simple:
- find the vertices to remove and remove them
- retriangulate the mesh
The hard part is how to implement these steps.
anyone know where the old "body" section is in the new Cinemachine camera. it used to be called Cinemachinevirtualcmaera
it was renamed to CinemachineCamera
If you need to optimize the output of marching squares, you probably want to look at "greedy meshing" algorithm
Does anybody know how to make Physics bone?
Like "VRchat","Genshin Impact"
A bone that is affected by physics you mean?
Some same
I need tail,hair Physic bone
Bones in unity are just empty gameObjects. You can add rb +collider to make physics affect them, or control their position via script.
If you have any animations that affect it, the animator would override the position/rotation, so you would need to modify it after the animator updated the bone
then pls give me some more examples in script?
Not code just how
You don't know how to move objects via script?
noep but I just wanna know
Principle
Wait i can make that system just use Collider and rb?
Depends on what you're trying to do.
If you don't know how to modify an object position, you should go over the basics of working with unity. !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Just hair
But have so many bone
And need they move like chain!
Anyway I try it XD
Thx for help
Look up chain tutorials for unity. You can achieve that with multiple rb, collider and joints.
Though, to be honest I don't think that's a suitable approach for hair. Hair is usually simulated in the shader.
Shader?? Ok i need learn shader graph thx
Basically, this is a complex topic with many different approaches. Look up "hair motion in games" for more info.
Kk
Hi all, may I get some help with events please? I don't know why it isnt invoked despite being subscribed to.
I have a LaserDrone type (derived from Mob type) which contains the m_health member, this member is of type PropertySet
public class PropertySet
{
public PropertySet(float min, float max, float cur)
{
this.min = min; this.max = max; this.cur = cur;
}
public float min { get; private set; }
public float max { get; private set; }
public float cur { get; private set; }
public delegate void PassedUpperThresholdHandler(float val);
public event PassedUpperThresholdHandler OnPassedUpperThreshold;
public delegate void PassedLowerThresholdHandler(float val);
public event PassedLowerThresholdHandler OnPassedLowerThreshold;
public void RaiseEventPassedUpperThreshold(float n)
{
OnPassedUpperThreshold?.Invoke(n);
}
public void RaiseEventPassedLowerThreshold(float n)
{
OnPassedLowerThreshold?.Invoke(n);
}
public void Increment(float val)
{
var overflow = val + cur - max;
cur = Mathf.Clamp(val, min, max);
if (overflow > 0)
RaiseEventPassedUpperThreshold(overflow);
}
public void Decrement(float val)
{
cur -= val;
if (cur < min)
{
Debug.Log("Passed Lower Threshold");
RaiseEventPassedLowerThreshold(min - cur);
}
}
}
Inside of my Mob definition:
private void OnEnable()
{
m_health.OnPassedLowerThreshold += HandleDeath;
}
private void OnDisable()
{
m_health.OnPassedLowerThreshold -= HandleDeath;
}
and
private void HandleDeath(float diff)
{
//if (!m_alive) return;
m_alive = false;
Debug.Log("Mob " + GetInstanceID() + " died");
}
Am I doing something wrong here? Why does my event not get invoked?
Add more logs, at least to OnEnable and the RaiseEventPassed methods
I have previously added logs there to confirm if they work, they do. It is the Invoke method that doesnt do anything
My guess would be it's subscribing to the wrong instance of PropertySet if you've confirmed all the code is getting called
Each Mob only has one instance of m_health and so far, its the only PropertySet to exist in the type and its derivatives. How do I know if I am subscribing incorrectly? It seems right since I am attaching the death handler to only the m_health event
Thanks your guess was right. I was assigning the handler inside OnEnable but a new instance is created in a custom Init function. Changed the order of initialization and it works now. Thanks
Is there a way to move the create scriptable object menu to the top of a right click?
Move awesome game to the top
does anyone know if i can control a sprite resolver label with its array number? the documentation only speaks of strings..... which is totally useless
are you using CreateAssetMenu? it has an order parameter
That's how you make it appear there on the menu
I want to move it above the folder option
you can also use MenuItem, it's just not as convenient
anyway, have you tried the order parameter?
That doesn't change the order
Hello, could anyone advise on how should I make sure the task stops getting executed if the object is destroyed? Currently the task continues to be executed well after the program is stopped
I'm guessing something involving a cancellation token?
Look into cancellation tokens
The async-Task pattern goes hand in hand with cancellation tokens for everything, and in this case you'd pass the token into your method and check for IsCancellationRequested. Then when your program stops you want to call Cancel() on the cancellation token source, which in turn delegates this into all of the tokens it created.
it's all relative so you just need to have a lower value than whatever Folder is, i don't know if Unity will tell you exactly but i can say order -9999 definitely puts it at the top haha
So if I were you I'd make a global cancellation token source that is cancelled on program end, and you pass this into everything.
Note that native .NET methods like Task.Delay and everything else asynchronous also accept this token
in recent (2022 i think?) versions of unity, all MonoBehaviours have a destroyCancellationToken
there's also Application.exitCancellationToken
oh you're right, that's handy
Nice, didn't know about this
Basically my tip but already implemented, use that instead
Hell yeah, thank you both
yeah, basically everything you start in unity should at least check the exit cancellation token so things work properly in editor haha
switching out of play mode counts as exiting for that token
I should have known this was a thing now that there's a proper pattern in Unity with the newest version
Thanks -10 did it
Hi, is there a Frenchman who knows a lot about unity?
whats a shortcut for a zero vector
Vector2.zero/Vector3.zero
ty
Please read this https://dontasktoask.com/
even shorter, default or new() 😄
Sure, but considering these exist you might as well use them for readability. Also because There are quite a few more
If it were a class it would save on allocation even, but that doesn't apply here since it's a struct
why arent my rigidbodies colliding
my main guy is dynamic and the object is static
i have capsule colliders on both
are they on layers that can interact?
most of them yea
Just go through the link you've been given
why cant unity just fucking work
im sick of this shit
been working on the same fucking game for 10 years
i dont need collision messages
i just need them to collide
Game dev is complicated
Collisions not working is because the dev set it up wrong
Collision messages happen because of collisions.
i dont have the onenter onexit methods in my script
so use this link
I DONT have those methods
JUST FUCKING go through it all, skip that page 😄
no wonder you've been working on this for 10 years 😄
Hello guys, anyone know any way to increasing the number of layers in unity instead of 32 layer
no
Why would you need that many layers?
if you need more than 32 something is def wrong in your design
The layers are implemented as a 32 bit bitmask. Therefore there are always 32 layers, no more or less.
Hello guys ! I'm working on a game with different zones and areas where the lighting of the area will change after "unlocking" it, what's a good way to approach this? Since realtime lights are expensive. Is it possible to use and changes lightmaps for specific areas?
How are you moving the rigidbodies?
you should be moving them via built in rigidbody methods such as LinearVelocity, Addforce, MovePosition (If kinematic), NOT translation as that causes unreliable collisions
linearVelocity
is this 2D or 3D
2d
if its 2D check if they are on the same Z axis
should be 0 for both the rigidbody and ground (or walls)
show the inspectors of the two objects you expect to collide
iirc in 2d colliders are always stuck on the same z
(the physics2d are not related to unity 3d hence no Z / quaternion for rotating rb)
Are they?
so there are many ways on how to use the new inoput sytsem, what is the easiest and most common way to get the Horizontal or Vertical Axis, we used to use GetAxis("Horizontal"). Thanks in advance.
OnMove(InputValue value){ movement = value.Get<Vector2>()
ty
if you create the PlayerInput Input Action asset from the Inpsector component it automatically makes a 2d composite for movement
yeah i also need to create that actions right, by default there are Move, Fire and Look
correct
SendMessages is the simplest, and then you can later change it if you want to pure events
ty, i think the new input system is really weird and confusing. takes a lot of effort to find out how it works since there are so many ways
thats exactly what makes it a bit confusing , you have many options at your disposal
but then it turns out its even easier than Input. class , I dont even use it anymore
the tricky part is playing around with the button modes
eg if you want tap and held
Thanks !
I have never used dictionaries before, is there any reason to use them over lists or arrays?
plenty of reasons but it depends on usecase like everything else
what are the main uses of them?
they're mappings
they are generally pretty fast as lookup methods
they're more akin to a list of tuples than just lists in general
but they're built for key lookup, in terms of api and internal structure
unlike array is not a fixed size, but unlike list its not an ordered list
Say you want to find an object with a name, from a list. Instead of iterating each object in a list, you can use a dictionary that has the name as the Key and the object as the Value
I was going to use the phone book analogy, but realized maybe people nowadays don't know what a phone book is.
contact list analogy
I understand that analogy, works well too
so you probably don't want to use dictionaries if you require it to be in a certain order?
probably not, as dictionaries dont have order
You can always use both though. A list accompanied by a dictionary for fast lookups
sweet
The dicionary could be generated from the list when needed
Or just a SortedList
SortedDictionary is also a thing.
collections have a few properties that matter outwardly
- indexed vs keyed vs no random access
- ordered vs sorted vs unordered
- exclusive vs nonexclusive
and a few for performance, like being contiguous, that don't really change the bulk of the api
unique combinations have unique usecases
for example, lists are indexed and ordered, queues/stacks are ordered, priority queues are sorted, a hashset is exclusive, a dictionary is keyed and exclusive
Oh cool, i never bothered to look into sortedlist
Didnt realize it has key/value pairs
no a sorted list is just a list but sorted
It implements IDictionary
I don't have a clue what a queue, stacks, priority queues, or a hashset's are I never used them but I get what you mean
ah, bad assumption from other language, sorry.
A list can do everything that queue, hashset or stack can, just with worse performance 😄
not quite for queues or stacks. that depends on their implementation. some libraries use lists or deques as underlying containers for queues and stacks (like c++ stl)
sweet, thanks bud
Looking at Stack and Queue source code, they use arrays not lists
https://github.com/dotnet/runtime/blob/5535e31a712343a63f5d7d796cd874e563e5ac14/src/libraries/System.Collections/src/System/Collections/Generic/Stack.cs
https://github.com/dotnet/runtime/blob/5535e31a712343a63f5d7d796cd874e563e5ac14/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Queue.cs
Idk what you mean with some libraries. We are talking about standard C# (Collections.Generic)
depends on their implementation
im talking about structures in general
Alright but why would you use a worse implementation than what is built into C#?
Alright, well I was :P
I was intrigued because queues are usually implemented with ring buffers rather than arrays, so I looked and well it's basically embedding the ring buffer implementation inside of queue.
are ring buffers used for stuff other than queues?
not seeing it
isn't a buffer generally for dynamic data?
"buffer" is a very broad/generic term just meaning more or less a contiguous array of data.
Anyway who says a carousel can't be dynamic?
frankly a dynamic carousel sounds like a ux nightmare
regardless, a ring buffer would be a good way to represent it in memory.
is there any way to call this reset button in code? I want to set a sprite from a scriptable object then call this reset button to get the collider to match the sprite
Are you writing an editor script?
Or are you expecting this to happen at runtime
just destroy and AddComponent 😛
well you could do:
GameObject go = myPolygonCollider.gameObject;
DestroyImmediate(myPolygonCollider);
myPolygonCollider = go.AddComponent<PolygonCollider2D>();```
Thank you I didn't realize that was probably just what the button did anyway 👍
It's probably not what the button does
the button calls native C++ code
in fact doing this will break any other references you have to the collider
so it's a bit janky
yeah it should work for my usage thank you
addcomponent? does it even calculate the collider for polygoncollider when it gets added?
https://github.com/Unity-Technologies/UnityCsReference/blob/ac359b9f2cf4048acb91530f81ca5d78966aeec7/Editor/Mono/Unsupported.bindings.cs#L210
Interesting function name lol
public static extern void SmartReset([NotNull] UnityEngine.Object obj);
For A³ game 😂
Just wandering if I can
Dudes now I want to make an up and down animation for an object and I don't know how to edit the position (update and not to set)
Because when I set the position of the 'y' and trying to apply the animation for several objects and putting them in different positions when I apply the animation on them they are go back into the position of my animation!
how come can I click a UnityEngine.UI.Button that's behind an Image/RawImage and how can I fix this?
the image is likely not a raycast target so it doesn't block raycasts
the raycast target box is checked though
well then ask in the proper channel and provide some actual information instead of making people guess
i'm not quite sure what information I can give, I haven't assigned an image, I'm just setting a color so it covers the entire screen, the color is transparent
but sure I can try my luck in a different channel
i haven't assigned an image
well that's probably why then
same behaviour with a source image
then i will say this again: ask in the proper channel and provide actual details
if you aren't sure what details might be important, then see #854851968446365696 for what to include when asking for help
How do I reference my Text Animator TMP?
textAnimator = headerText.GetComponent<TextAnimator>(); does not work
you need to use its actual type
What do you mean?
i mean you need to use the actual type of the component instead of just guessing what it is, consult the documentation for whatever asset you got it from since it's clearly not your own component
if the correct suggestion isn't being displayed when you type that.. then I'd suggest check your IDE is correctly configured
I can't find anything on it
The correct suggestion isn't showing up no nothing similar to it at least
what is the asset it came from
also you can probably look in your screenshot for a hint as to what you should google
The package you mean? The asset isn't mine it's my partner's
the asset as in the asset store asset that this component came from. also simply googling the name of the component was enough to find it. put in some effort.
You really love to help don't you
you wouldn't have even had to ask in here if you would have just googled the name of the component. it's the first result
here's another fun fact: the type name is also in your screenshot
Yeah
Thanks btw though I'll tell you most people wouldn't like that you'd assume they're trying to get spoonfed
and yet you were so 🤷♂️
lol
is your IDE configured?
Yeah I have it set up, I don't know why it didn't show the suggestion but it worked after I ctrl+Sd my VSC
That's... kind of what he was trying to show you
how easy it is to check documentation to find it
okay done
void Update()
{
Debug.Log(fallTime);
// If the velocity is negative
if (GetComponent<Rigidbody>().velocity.y < -2)
{
// Count the time as "fall time"
fallTime += Time.deltaTime;
// The player "has fallen" I guess
hasFallen = true;
}
// As soon as the velocity is not negative, if the player fell, even a bit
else if (hasFallen)
{
if (fallTime > 5.0 || playerStats.currentHealth <= 0) { // <<< specifically this if
// put player x y z to respawn pos
// loadScene(DeathScreen)
SceneManager.LoadScene("Death");
}
// If the player has fallen a considerable amount of time
if (fallTime > 1)
{
// Hurt the player based on how long they fell
playerStats.currentHealth -= fallTime * 25;
}
// Reset fall measurements
hasFallen = false;
fallTime = 0;
}
}
does anyone know why when falltime > 5, the if condition doesn't work?
which if condition
if (fallTime > 5.0 || playerStats.currentHealth <= 0) { // <<< specifically this if
There are twoi other conditions required there
hasFallen has to be true, and ccurrentHealth has to be less than 0
and.. if they're not both also true
oh
yes sorry
you do need hasFallen to be true though
hasfallen should theoretically be true since I am getting a debug log from the first line
the first line logs no matter what
and fallTime += Time.deltaTime; is adding
it's the first line in Update
It looks to me like you're setting hasFallen = true immediately when the object first starts falling.
That means next frame you will run the else if which does fallTime = 0 at the end
so fallTime will only ever be Time.deltaTime at most
one frame worth
I don't see how fallTime could ever be more than 5
unelss you had a single frame that lasted more than 5 seconds
// Reset fall measurements
hasFallen = false;
fallTime = 0;```
^ This is screwing you up
it doesn't make sense
I see your point, but when I remove fallTime> 5.0 that condition and just take damage instead of falling indefinitely, the scene loads
meaning hasFallen is true constantly when falling
instead of sluething around like sherlock holmes why not attach a debugger or add more logging so you can know for sure
Here's what is definitely true:
- If statements work properly, 100% of the time
Currently working on making editor tools, and trying to display a UnityEvent property in a custom inspector, so that way a designer can assign unity events to a "story beat system"
I know that you can use PropertyFields to read SerializedProperties, but since the UnityEvent is being retrieved from a list of custom classes that don't derive from UnityEngine.Object, they can't be read
Is there another way to do this, or is that not possible within the constraints of the editor?
Start from the top and work through the logic.
The first condition is if Y velocity is less than -2.
If it's not, then you check if hasFallen is true.
Then you check fallTime is greater than 5 or health is 0
After that, you check if fallTime is greater than 1.
UnityEvent is being retrieved from a list of custom classes that don't derive from UnityEngine.Object, they can't be read
Wdym by this?
You mean you just have a List<object> or something>
You can always do:
if (theProperty is UnityEngine.Object uobj) {
EditorGui.DrawPropertyField(... uobj );
}```
er, that's a bit off
since you need a SerializedProperty
but yeah
Essentially, there's a custom class "StoryBeat" containing a list of "StoryBeatEvent"s, each with their own UnityEvent Event
Is StoryBeatEvent serializable?
yes
So... it should work out of the box unless I'm missing something
What type is the custom inspector for?
when making a SerializedProperty, you start with a SerializedObject to pull the property from, right?
wdym
A custom editor can only be made for a type that derives from UnityEngine.Object
i.e. a MonoBehaviour
or a ScriptableObject
you said youre writing a custom inspector
unless I misread somewhere
yes, but within that MonoBehaviour, I have a list of non-MonoBehaviours that actually contain the UnityEvents I'm trying to serialize
and those can't be read by SerializedObject, since they don't derive from Object
sure - so the SerializedObject is the MonoBehaviour
the field of type StoryBeatEvent would be the SerializedProperty
and within that SerializedProperty the event would be another SerializedProperty
I kind of understand? from what I've seen online, this is how you do SerializedProperties, correct?
SerializedObject eventObject = new(storyBeatEvents[index]);
SerializedProperty eventProperty = eventObject.FindProperty("UnityEvent");
EditorGUILayout.PropertyField(eventProperty);
eventObject.ApplyModifiedProperties();
e.g.
SerializedObject sobj = new SerializedObject(myMonoBehaviour);
SerializedProperty eventProperty = sobj.FindProperty("someEvent");
SerializedProperty unityEventProperty = eventProperty.FindPropertyRelative("theUnityEventField");```
It would help to see the structure of the classes you are trying to render a GUI for here
It seems unlikely "UnityEvent" is the name of the field
yeah, I can draw something up
that was a placeholder variable name, ideally it'd be better than that
StoryManager : MonoBehaviour
{
List<StoryBeat> StoryBeats
}
StoryBeat
{
List<StoryBeatEvent> StoryBeatEvents
}
StoryBeatEvent
{
UnityEvent EventToRun
}
here's the general structure, simplified to make it easier to see
Are both StoryBeat and StoryBeatEvent marked with [Serializable]?
and are those fields public, or marked with [SerializeField]
yes, the classes are serializable, with the fields public
Hey! I hace a question about optimization, should I post it here, or on #archived-code-advanced ?
you should be able to do e.g.:
SerializedObject serializedStoryManager = new SerializedObject(myStoryManager);
SerializedProperty storyBeatsProp = serializedStoryManager .FindProperty("StoryBeats");
for (int i = 0; i < storyBeatsProp.arraySize; i++) {
SerializedProperty beatProp = storyBeatsProp.GetArrayElementAtIndex(i);
SerializedProperty beatEventsProp = beatProp.FindPropertyRelative("StoryBeatEvents");
for (int j = 0; j < beatEventsProp.arraySize; j++) {
SerializedProperty sbeProp = beatEventsProp.GetArrayElementAtIndex(j);
SerializedProperty eventToRunProp = sbeProp.FindPropertyRelative("EventToRun");
EditorGUILayour.PropertyField(eventToRunProp); // for example
}
}```
it's pretty laborious with the lists
oh my gosh tysm, this has been plaguing me for so long, I've been so lost in the editor madness
I'll go ahead and start adapting/implementing something like this and see if it works
does it actually need the eventObject.ApplyModifiedProperties(); line in there, like from the source I found, or was that something not as necessary?
got it working perfectly, thank you so much again
So I've almost got this save system working, just one problem.
JsonConvert.DeserializeObject<PlayerData>(File.ReadAllText($"{_playerDataDirectory}{_slash}{PlayerDataFileName}.json"));```
This gives an error because one of the data is List<Condition> where Condition is an abstract class. The error: ```JsonSerializationException: Could not create an instance of type Condition. Type is an interface or abstract class and cannot be instantiated.```
I don't even know why it's trying to instatiate, PlayerData is a regular C# class
!ban 980901204597030912 spam/racism
friedreports was banned.
Actually in this case I guess it's simple to make Condition a non abstract class. But still, don't know why it does this
Instantiate in this context doesn't mean UnityEngine.Instantiate, it means creating a new instance of a C# class with new
The problem with abstract classes is that when you serialize the data into JSON it doesn't contain information about what the actual class is. So when deserializing it, it's not possible for it to know what class to use
It doesn't even need to be abstract, if you have List<A> then it will deserialize all the data into instances of A regardless of what type the original data is
just FYI, Instantiate is also the term used to create an instance of an object outside of unity. it doesn't just mean to clone a prefab/gameobject
oh i was scrolled and someone else already said that my bad
I dont get why it says it couldnt be found
C# is case sensitive
get your !IDE configured then check your spelling
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Ah, so you can't type using base classes?
I guess you need to do some kind of ID lookup instead, where you just serialize IDs?
In this case, Condition is also a scriptableobject, so I can maybe just serialize the GUID?
omg i forgot to modify my vs
Something like that, although I'm not 100% sure if GUIDs are stable
What's a Rigi body
to make the character collide with things
I thought they were at least stable within a game instance (a player's copy of the game). But I guess even then it would caue problems if someone uninstalled the game and reinstalled it later
No, that's a Rigid body.
What's a Rigi body
huh
Well, your code is looking for something called a Rigi body. What is that
So how the heck are you supposed to save this data...?
Oh
Is it a script you've made? Maybe show the code for Rigibody2D
configure your ide
give a sec its updating
@naive swallow
Well, yeah. You can't add a vector to a Rigidbody, that wouldn't make any sense
But that is what the tutorial showed me to do
Show the tutorial
Let me rewatcg just in case
okeeey
Getting a character to move in your Unity game engine takes some understandment. In this tutorial you will learn how the New Input System works and how you use it to move a 2D character. By combining a Sprite Renderer and a Rigidbody2D we will make moving as simple as possible. This tutorial is focused to be beginner-friendly and explains all th...
Minute 11:28
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 181
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-11-12
oh truee
im sorry for wasting all of u guys time
who said Number of times the code literally did not exist: 1 🤔
I'm wondering who would do that
It was a Code Monkey tutorial and he just straight up forgot to include the script in the video or the repository
hmm i have a strange unity IAP issue, that someone else complained about in july but didn't ever post a resolution to. in editor, i can connect to the IAP initialization in editor fine, but when i build to android and try to load the game there, i get a failure response to UnityPurchasing.Initialize OnInitializeFailed InitializationFailureReason:No product returned from the store. error
Chat GPT is telling me to bind the rightclick under hold... I feel like thats wrong but i dont see anywhere to bind what button im actually pressing. Help?
chatgpt was your mistake
learn how to properly use the Input System
mouse delta isn't for button, it gets the value between the 2 moved points
I just want help. I dont understand how to set it and i went to chatgpt becasue i couldnt find a straight answer. Are you able to help?
This is what it said:
i posted this in art but bc it has code i figured someone could help
Hey can someone help me as to why the animation of the slashing isnt flipping as intended on the left side when the player faces left.
private void Attack() {
myAnimator.SetTrigger("Attack");
weaponCollider.gameObject.SetActive(true);
slashAnim = Instantiate(slashAnimPrefab, slashAnimSpawnPoint.position, Quaternion.identity);
slashAnim.transform.parent = this.transform.parent;
}
public void SwingUpFlipAnimEvent() {
slashAnim.gameObject.transform.rotation = Quaternion.Euler(-180, 0, 0);
if (playerController.FacingLeft) {
slashAnim.GetComponent<SpriteRenderer>().flipX = true;
}
}
public void SwingDownFlipAnimEvent() {
slashAnim.gameObject.transform.rotation = Quaternion.Euler(0, 0, 0);
if (playerController.FacingLeft)
{
slashAnim.GetComponent<SpriteRenderer>().flipX = true;
}
}
is there something wrong with my code? I cant seem to see a reason as to why it isnt working
does anyone get this file auto generated by unity? must i gitignore it or is there a way to stop it from genning
Wouldn't you want to flipY instead of flipX?
i fixed it now i forgot to set my facingleft to = true so it never triggered. But i wanted X as i want to spawn it 180degrees from the right if that makes sence
Anyone here experienced with mesh generation? I need help setting UV's for a procedurally generated mesh.
I need to make sure every yellow point within the blue octagon is on a single UV texture 0,0 to 1,1
Part 1
int pointOffset = verts.Count;
List<JunctionEdge> edges = intersection.GetEdges().ToList();
List<Vector3> intersectPoints = new List<Vector3>();
List<Vector3> curvePoints = new List<Vector3>();
for (int j = 0; j < edges.Count; j++)
{
int next = j == edges.Count - 1 ? 0 : j + 1;
int previous = j == 0 ? edges.Count - 1 : j - 1;
JunctionEdge currentEdge = edges[j];
JunctionEdge nextEdge = edges[next];
JunctionEdge previousEdge = edges[previous];
Vector3 leftIntersect = FiveBabbittGames.MathUtils.GetIntersectionPoint(currentEdge.left, currentEdge.direction, nextEdge.right, nextEdge.direction);
Vector3 rightIntersect = FiveBabbittGames.MathUtils.GetIntersectionPoint(currentEdge.right, currentEdge.direction, previousEdge.left, previousEdge.direction);
Vector3 currentEdgeLeft = currentEdge.left;
Vector3 nextEdgeRight = (j < edges.Count) ? nextEdge.right : edges[0].right;
BezierCurve curve = new(currentEdgeLeft, leftIntersect, nextEdgeRight);
intersectPoints.Add(leftIntersect);
curvePoints.Add(currentEdgeLeft);
// Quad Verts
verts.Add(currentEdge.left);
verts.Add(leftIntersect);
verts.Add(rightIntersect);
verts.Add(currentEdge.right);
// Curve Verts
float curveStep = 1f / (float)curveDivisions;
for (float t = curveStep; t <= 1f; t += curveStep)
{
Vector3 pos = CurveUtility.EvaluatePosition(curve, t);
curvePoints.Add(pos);
verts.Add(pos);
}
int triOffset = pointOffset + (j * (4 + curveDivisions));
```
Part 2
// Quad Tris
// Top Left Triangle
tris.Add(triOffset + 0);
tris.Add(triOffset + 1);
tris.Add(triOffset + 2);
// Bottom Right Triangle
tris.Add(triOffset + 0);
tris.Add(triOffset + 2);
tris.Add(triOffset + 3);
// Curve Tris
for (int k = 0; k < curveDivisions; k++)
{
int current = 4 + k;
if (k == 0)
tris.Add(triOffset + 0);
else
tris.Add(triOffset + (current - 1));
tris.Add(triOffset + current);
tris.Add(triOffset + 1);
}
// THIS IS PLACEHOLDER CODE FOR THE UV's
// Quad UVs
uvs.Add(new Vector2(0, 0));
uvs.Add(new Vector2(0, 1));
uvs.Add(new Vector2(1, 1));
uvs.Add(new Vector2(1, 0));
// Curve UVs
}```
stop posting chatgpt stuff and just ask your question
Second this, we don't have ChatGPT's context
its better to ask your question here than ask chatgpt because chatgpt will set you in the wrong direction and that would make it more difficult for us to help you
I have a hypothesis but now I need to know how to get the bounds from a list of vertex positions, anyone know how to do that?
Can be more specific about what you mean by "bounds"?
DO you mean a convex hull? Concave Hull? Or an AABB?
the bounds from a list of vertex positions? you can start working with each axis, loop through the list, find the minimum X, maximum X, minimum Y, maximum Y, etc
this will give you the box bounds of the vertices
a square that contains every point that I can easily translate the positions coordinates to be between 0 and 1
thank you will give this a go
If you mean an AABB you can use Unity's Bounds struct like so:
Bounds b = new(myVertices[0], Vector3.zero);
foreach (Vector3 vertex in myVertices) {
b = b.Encapsulate(vertex);
}```
ooooh
at the end b will perfectly encapsulate all the vertices in a minimal AABB
oh wait sorry Encapsulate doesn't return anything
it's just b.Encapsulate(vertex); without the b = bit
Can someone help me with a issue? ~
Im trying to code a simple toggle that when the player presses "G" it turns off the sword object (putting it away) but I seem to only be able to get it to turn off and nothing i do seems to be able to re enable the sword object
private void Update()
{
MouseFollowWithOffset();
if (Input.GetKeyDown(KeyCode.G))
{
ToggleSword();
}
}
private void ToggleSword()
{
gameObject.SetActive(!gameObject.activeSelf);
}
!code and this seems more like a beginner issue.
If the game object is disabled, Update isnt gonna run
📃 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.
Any suggestions on a way around this
disable a different object than the one that has the script on it
restructure your hierarchy as needed to make that happen
Oh i see, its not working because the code cant run if the object is off? If i put that in my controller file itll be okay?
not sure what a "controller file is"
Player Controller sorry
but yes, if you disable a different object than the one this script is on, this script can continue running
Awesome thankyou sorry for the stupid question
Hey, I am trying to load a config from a JSON file.
I managed to get the file to actually load, which can be seen in the inspector shown in the very first picture I attached.
Issue is, values for some reason don't get set to ones from the JSON file.
Is this possibly because the JSON is unable to assign values to Properties?
If yes, is there a quick and easy workaround or will I have to literally have double fields just to accommodate to the Unity's JSON loader?
Here's a class JSON is supposed to load to: https://github.com/nnra6864/Nisualizer/blob/master/Nisualizer/Assets/Scripts/Config/Config.cs
And here's the JSON loader script: https://github.com/nnra6864/Nisualizer/blob/master/Nisualizer/Assets/Scripts/Config/ConfigScript.cs
Thanks in advance!
please @ me if you are able to help
does anyone know if you can execute code to an asset when imported
ie, when importing an FBX run code to change a name on its animation clips
JsonUtility uses the same serialization rules as the inspector
You just have to follow those rules
It's not clear which things you're expecting to be serialized or not here
The only things you actually have serialized in your class seem to be those "default" fields
Hello! Fairly new to Unity here but experienced in C#! Im trying to create a game that will have a lot of item classes and sub-classes that will also havr a sub-class and in that class the values for the item. I want to make it as modular as possible, meaning I want to be able to change items names and values really easy and fast. I tried using ScriptableObject for every item but trying to add too many items, might take a while to set them up and imagine wanting to change or add a value for all of them... I also had the idea of using a XML or JSON file but havent implemented that yet. So any ideas how I should do it?
Please @ or DM me if you want to help. Thanks!
scriptable objects is a good way. for changing a value in all of them, you could always make some editor scripts to make the process easier for you. xml or json would have this issue too. in reality, it does take time to setup all your items
JSON isn't a bad idea, but the work flow using SOs is just much quicker as you're using a UI to change value fields. SOs are also supported out of the box so you're not needing to manage the deserialization or parsing of data
Not to mention how easier it is to reference with an SO compared to explicit pathing/IDing if these items are anything but trivial
Ah, so I literally have to mark it as [SerializeField], in order for it to work, makes sense.
And well, not use properties too ig.
Since this is the case, would it be an uncommon/bad approach to have an additional abstraction layer, which is literally just a Config class that only gets the JSON data loaded into it, and then the current class I have is just a place that would then store all that data into actual properties so you can have stuff like OnValueChanged etc.?
I genuinely can't think of another way to work around this, but then again, I can't say I have a lot of experience w JSON in the first place tbh.
Yes, it's p much code duplication, but I am out of ideas...
You might want to look into stuff like JObjects and JTokens
