#archived-code-general
1 messages ยท Page 380 of 1
pro tip: make the problem smaller when debugging
am i calculating the direction wrong somehow? it seems to be all messed up
this is my code:
private void OnDrawGizmos()
{
if (!Application.isPlaying) return;
Vector2 MousePos = Camera.ScreenToWorldPoint(new Vector3(InputHandler.MousePosition.x, InputHandler.MousePosition.y, -Camera.transform.position.z));
Gizmos.DrawWireSphere(MousePos, 1);
Gizmos.DrawWireSphere(transform.position, 1);
Gizmos.DrawLine(transform.position, ((Vector3)MousePos - transform.position).normalized * Distance);
}
Log the direction, mouse position and transform position
My guess is that you're wanting a point for the second argument and not a direction.
https://docs.unity3d.com/ScriptReference/Gizmos.DrawLine.html
this is a debug for a boomerang mechanic, i just stripped it down to highlight the issue
if this was purely a debug that would work but i need it to be a direction with a constant distance (to ensure the boomerang always flies a specific distance before coming back)
The function takes two points. Not a point and a direction.
Use DrawRay then
to make myself more clear im trying to debug the direction not how i draw it
Your draw line function is being used incorrectly
i replaced the line and this showcases how the red circle (the direction) strays off of the actual line if it were to go in the direction correctly
im using debug to visualize it better, in gameplay the boomerang strays aswell
Fix the debug first then attempt to fix the actual object.
Your draw line is definitely wrong as is
And the visualization is wrong, as dalphat has been explaining
The direction looks fine otherwise
ive been trying to make a grid system for a project but i just cant seem to fully understand it
im trying to make a puzzle game where the pieces move like chess pieces
what issue are you encountering exactly?
im an idiot basically
we can't really help with that
if you have a specific issue you want to actually ask about, we could help with that, but we're not going to reexplain the whole grid system when there's already plenty online
Hi! I was wondering if someone could help me. My electricity went, and now when i started my project again this error won't let me press play. I can't find anything on google eighter ๐ฌ
make sure all of your packages are up to date. after ensuring they are and if the issue persists then close the editor and open up the Library folder within your project files and delete the PackageCache folder. Then open the project again and unity will force your packages to reinstall which should resolve that
ok! thank you! Will reimporting all the packages work to update them?
it will reinstall the versions currently installed in the project which is why i said update them first
aah ok!
Thank you! It worked
Question:
I'm making a menu based game (think rpg with menus). Since my "turn phases" are defined, I chose to make the player into an FSM.
I want to handle a key input (let's say space key) differently depending on what phase I'm in.
Example:
Action picking phase -> the space key selects an action
Target Picking phase -> the space key selects a target
Would triggering an event from the player when the key is pressed and having the state listen to that and act accordingly be logical?
or is it better to just have each state handle it's own input? (as there may be states where the player cannot move)
Each state should handle the input. If you want, you could always define function to handle the same behavior. (UpdateMovement(), etc.)
Obviously, you need to factor in the player whenever you read inputs. Either by listening to its input or "pooling" them.
I don't quite follow, please clarify
I understand this part though
player.Input.OnGetKeyDown += ...
OR
if(player.Input.GetKeyDown(SpaceBar))
Can't I just
Input.GetKeyDown?
Or is there a difference when called on the player object?
Yes you can, but as I said it is better to use the player object. It give you more control.
By example, you can easily define a control mapping schema where if you do a Input.GetDown everywhere it is going to be tricky.
Also, if you were to replace the player an AI, it would be easy to simply simulate the input to make your ai.
If you have multiple device (Keyboard, Phone, Controller) it can make it eaiser
Finally, if you have more player, you will be able to handle this case as well.
So yeah, 4-5 reasons to why you should use the player instead of reading it directly.
I have a bunch of extension methods, and I just realized looking at them that they are declared static - not sure if this is for csharp reasons or unity reasons. Can someone explain to me why that is, and also can I declare a true static helper? So I can call Quaternion.SomeHelper(), rather than needing a quaternion instance?
Is this a good approach generally, or should I just decalre a static QuaternionHelpers and call that?
Extension methods are required to be static
That's C#
nothing to do with Unity
If you want to add static functions directly to Quaternion, I believe you should be able to do this:
public partial struct Quaternion {
public static void MyNewHelperFunction() {}
}```
That should let you do Quaternion.MyHelperFunction();
But if that doesn't work - your best bet is just to define your own static functions elsewhere.
you cant do that, partial classes need to be in the same assembly
Fair enough
In that case yeah - you're SOL since C# doesn't support static extension functions
it doesn't buy you too much though.
Just Quaternion.MyFunc() instead of MyClass.MyFunc()
should i keep my player script in one script or should i split it into multiple ones like InteractionController, MovementController etc??
split it if you value your sanity, and clean code
ideally your script should only take care of 1 thing and do it well.
I'd say depends on the code.
well they mentioned movement vs interactions, something you def don't want mixed
I can disable interactions or movement without affecting the other, thats a win win situation
If the movement is just setting a destination on a navmesh agent, there's not much to move to a separate script.
For example.
even so I'd keep it in its own script but thats just my preference
I rather have a Movement script where i know its just that rather than scouting a movement script to find some interaction logic
i mean it would be easier to read but one script would be easier to manage i constantly forget what script does what i use singletons a lot so it would be easier to reference player in other scripts
in the end is whatever is easier for you, if all in one script is easier for you go for it.
I started with monoliths myself ๐
okay thanks ๐
I think with time you appreciate value of non-monliths
In my current project, I have a crpg like characters, so a lot of actions are implemented as separate classes. The character script executes the actions queue state machine and has some basic methods for controlling the characters from these actions.
In this scenario it doesn't feel right to separate movement into a separate script. At least not for me.
yeah that specific example does make sense if thats your system, def agree where you should be aware of your setup and use what works best for your own system
Maybe later on I'll split it if I plan on having immovable characters, though, I can just as well disable the logic itself. We'll see.
yeah statemachines are tricky to split for me cause so much is kinda tied together
i still use enums to make my state machines , I haven't dived into the classic pattern yet tbh
Yeah, my system is a bit more involved. It would be a spaghetti mess if I were to put all the actions in one class.
jittery in what way ?
wait is the background a rigidbody ? ๐ค
for 2D ? are you sure its not just artifacts from missing pixel perfect ?
do you have interpolation turned on ?
should be yea
maybe show a vid what it looks like ?
not entirely sure I don't do 2D much, it might be the camera. If you're using cinemachine maybe try another update mode
In the new Unity input system exactly what triggers the canceled event for a 3d composite binding? I was hoping it would just be if one of the keys was released, but that appears to not be it.
Naming convention question.
Is there a standard practice for how to capitalize tags and game objects?
Such as:
EnemyLaser
enemyLaser
enemy_laser
I'm trying to establish good habits so things are easy for future possible collaboration ๐
Not as far as I know. I would not use camel though.
i tend to use PascalCase for tags, treating them like enum members, since that's essentially what they are (layers as well)
PascalCase unless otherwise specified
Especially keys and names, these always use PascalCase
But like with all things, do what you feel fits best (tm)
fun fact, discord supports :tm: -> โข๏ธ
What is the recommended way to have a parent RectTransform conform to the height of it's child, specifically layout groups?
Thanks for the tips all! It's kinda funny cuz I started with PascalCase, then wanted to try lowercase for both just cuz it looked cool. and then I started getting confuzzled on what was and wasn't capitalized ๐
I would suggest you set up constants for this because magic strings (and numbers for that matter) are a very common mistake
probably ContentSizeFitter if it controls its own layout, otherwise you can propagate preferred/min size upwards by giving it its own vertical or horizontal layout group if it doesn't have one already
Constants as in constant rules for what to capitalize? And forgive me but what is a 'magic string'?
No, a "constant" variable. This is a static variable that cannot be mutated (meaning you can't change it)
"Magic string" or "Magic number" is a term used for a string or number which has no specific restrictions to it, so when you make code that uses these and they exist on multiple places, they are very prone to mistakes
For example, missing capitalization, specifying 5 instead of 6, so you should use enums or constants
Yeah that's what I normally do but it's a little buggy, layout changes don't always work correctly
do you have a warning in the content size fitter inspector? putting it on a RectTransform that has its dimensions controlled by something else is a mistake I see a lot
yep, I have nested layout groups, so I don't know how to get around that
Interesting. I'm wondering, how would turning strings into constants help with spelling though if you also have to remember how to spell the name of the constant variables that contain the string?
The idea is that instead of typing out the string everywhere, you pass the constant
So like a variable, reusing it
It's just that you can be sure this is the string, and it will not be changed
FYI this does mean you have to set the tag of things through a script, and not from the inspector
But I'd argue relying on inspector data is a bad habit due to how easy it can change
I want my sub layout group's preferred height to define the height of the parent layout group
so the parent of this object needs to drive its layout. Remove ContentSizeFitter, add a V/H layout group if it doesn't have one already (even if only a single child - look at what Layout Properties are at bottom of inspector to see if this is needed), add LayoutElement, FlexibleWidth checked on, set it to 1
or the parent driver of your ContentSizeFitter RT can force expand horizontally if it only has this one child
I don't understand how to make a vertical layout group's height be the total size of child elements without using a content size fitter
you are using it only to propagate the preferred size upwards, since it can't control its own layout
its parent is controlling its size. You just need it to let that parent know what size it wants to be
the other option is to change your layout such that it can control its own size, and then you can use a content size fitter there as you wanted
Sorry I'm trying to understand what exactly you mean. I have this structure
VerticalLayoutGroup (This shows a preferred height of 472)
LayoutElement - Flexible Height 1
VerticalLayoutGroup (This shows a preferred height of 800)
LayoutElement - Flexible Height 1
I need the parent's preferred height to be the childs
why flexible height on the child?
I was just trying different things to make it work, but removing does nothing
Okay I got it, I needed to have control child size on the parent VerticalLayoutGroup.
It makes sense to me now, The child group feeds the preffered size and then the parent layout group actually sets it
Ty
Iโm on phone so I had to really zoom in cause I can barely notice the jitter
I have a crazy idea what if you multiply by time.deltatime instead of fixeddeltatime
that just doesn't make sense
FixedUpdate happens with a different rate to Update
deltaTime is the time between calls for Update
fixedDeltaTime is the time between calls for FixedUpdate
The documentation for rb.moveposition uses regular deltatime
And this post from 2017 has a response that reinforces the view to use deltatime https://discussions.unity.com/t/should-i-be-using-time-fixeddeltatime-here/193101/5
well, apparently
Time.deltaTimeWhen this is called from inside
MonoBehaviour.FixedUpdate, it returnsTime.fixedDeltaTime.
So ??? Maybe thereโs something there
so no, there's no difference
tbf, me neither lol
Thatโs weird that normalizing the movement vector makes it worse
Is the player object the only thing in the cinemachine follow
And look at group is empty
Idk I havenโt worked with that
well, try disabling it i guess?
Tbh I still barely see any jitter in the video
If anything it looks like itโs part of the pixel art aesthetic
Now I see it a little bit in the bottle
It looks correct
Have tried disabling pixel perfect?
I donโt know. Unfortunately I am very bad at camera stuff and also often get camera jittery issues with my own projects
There is a post on unity forums saying that these 2 lines give different result:
transform.position = newWorldPosition
transform.localPosition = transform.InverseTransformPoint(newWorldPosition)
shouldn't the transform end up in the same place?
Since the InverseTransformPoint method translates the world position into the local one, they should give the same results
It's also about performance, since it's probable that localPosition sets the position to the translated with the TransformPoint method value
Although the source code is decompiled
Is it possible to extend Unity's built in classes like Vector3?
I'd like to add a constructor for Vector3 from int3 cause it's apparently not a thing
just make an extension method sure
No, you cannot directly extend them. You have to create a static class e.g. Vector3Extension. Since extensions cannot contain constructors, you have to create a short method e.g. Create with the required parameters.
Vector3Extension.Create(int3)
Yeah I don't think it's possible to extend constructors
Without modifying the source code, yes
Kinda annoying they never included any conversions but then again, int3 from mathematics package was probably made as a whole separate thing
Although it's possible if the struct or class is partial
If you're talking about int3x3, it's actually partial
Oh wait, there's Vector3Int
Meaning you should be able to add a new part to it
And there is no convention from Vector3, if we are talking about constructors
You can directly cast Vector3Int to Vector3 though, which is kinda what I need
Right, can only be done via Vector3Int.RountToInt in the opposite direction
Yeah I think int3 was mande as an unmanaged data type for burts and such, you'd actually want to use Vector3Int for integer vectors in managed context probably
Can't I just do this?
Ah, the opposite direction right
Hey everyone! I'm starting a multiplayer project and everything seems to working except when I spawn in a client, they aren't able to move. It just jitters. Any ideas?
EDIT: I'm using Unity 6 and Netcode for GameObjects
#archived-networking and theres also a pinned message for the ngo server in there
Thanks!
Hello, I'm unsure where I should put this question, so I think general would be best for it as I don't know, anyway, onto the question:
I'm trying to get the rotation of a hit point through a raycast, my ray reflects correctly, but I'm unsure how exactly I can get the rotation from the ray reflection, I draw rays to debug it to know it was reflecting right, it seems to reflect right, but I just don't know how to get the actual rotation of what I hit and then apply that rotation to a transform (in this case just transform as it's attached to the object)
void FixedUpdate()
{
if (AutoAdjustRotation)
{
Ray ray = new Ray(Base.transform.position, Vector3.down);
Debug.DrawRay(ray.origin, ray.direction * 50, Color.red);
if (Physics.Raycast(ray, out RaycastHit hit, 50, mask))
{
Vector3 surfaceNormal = hit.normal;
Vector3 reflectedVector = Vector3.Reflect(Vector3.down, surfaceNormal);
Debug.DrawRay(hit.point, reflectedVector * 10, Color.green);
Vector3 reflectedRayEndPoint = hit.point + reflectedVector * 10;
Debug.DrawLine(hit.point, reflectedRayEndPoint, Color.blue);
Quaternion rotation = Quaternion.FromToRotation(Vector3.down, reflectedVector);
transform.rotation = rotation;
}
else
{
Debug.Log("No hit detected.");
}
}
}
This isn't my whole code, just the part that is needed in this context (There is no code aside from it causing issues)
I kept getting questionable results so added indicator game objects and actually trying to position to game objects, one assigning it a local inverse world position and the other one assigning a world position directly - they end up in different spots:
var world = carryablePivot.position + offset;
indicator.SetParent(carryablePivot.parent, true);
indicator.localPosition = Vector3.zero;
indicator.localPosition = carryablePivot.InverseTransformPoint(world);
indicator2.SetParent(null);
indicator2.position = world;
indicator.rotation = Quaternion.LookRotation(offset);
indicator2.rotation = Quaternion.LookRotation(offset);
Debug.Break();
(assigning Vector3.zero) doesn't change anything, and while the indicator transforms are top level (or at least their parent has an identity / zero transform), the carryablePivot is nested in the hierarchy - which somehow influences the inversetransformpoint?
whats the use case you're trying to apply this to, something like having an object standing along this surface normal and be rotated?
you can create the quaternion using the method if you just want a rotation facing the reflected vector https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
The use case is to make a character automatically rotate with the terrain they are on (The character is non-playable), and I just need it to be rotated when standing on it, as you said, I'll check out the method you stated
I have a float, and I want to check if it's >= some value. I'm aware of Mathf.Approximately - is there anything I can/should do with a >= comparison for floats?
Why can't you just do like
if (1.1f >= 1f) { }
Just random values
Yeah, happens quite often in coding when there is a very simple solution it's thought that isn't right ๐ญ
Tried it by changing my FromToRotation to LookRotation, sets the rotation degree to 90 on the X axis (The right one)
The actual rotation is 32.713, so it's not getting the rotation correctly, and I am confused as I've never used LookRotation
I have a question regarding update and fixedupdate. You are supposed to put everything about physics in fixedupdate, but my question is, if I have a method with logic - physics logic - more logic how can i split it so everything goes to the corresponding update? Also, another problem is that fixedupdate goes before update so if the physics logic is in the middle or at the end is going to be a problem
It might be due to the += position, try using Vector2.Lerp for smooth positions
Or Vector3
Either one for whatever you are making
Probably want to post an example of the problem, but usually if you question where it should go, you'll less likely run into problems just sticking into the physics update.
this 2 methods
Just run the function in fixed update?
It should work that way
Anything that says rigidbody goes into fixedupdate. Now, input on the other hand can be placed into update, but that requires a little more setup of polling it and then checking it again in fixedupdate.
yeah but here the big problem is splitting all this methods where i have physics running with other type of code
Anyone can review this code ? I just want an opinion to know if im wrong and need to use another way
like how can I split code into fixed and update and having track on both executing like if it was only 1 method? Also fixed always executes first, but if i need it to execute it last or in the middle what should i do
fixed is only for physics
Both, moveplayer and jump methods should be called from fixed update from what is shown there.
but there are more things apart than physics
๐ญ I know fixed is for physics only, but you asked how to run them in fixed update with separate methods so I told you just run the methods inside fixed update
Right, but most from what I'm seeing there isn't that frame dependent beyond maybe preventing the audio from overlapping which should be handled with additonal checks.
well, its just an example but imagine there is something which is indeed frame dependant
... I helped you and you ignored me ๐ญ
!code
What I throw into my updates is usually just input if I am using Unity's rigidbodies. CharacterBody on the otherhand is specifically ran with update.
๐ 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.
oh, I had the wrong parent set..
directly replacing the method with LookRotation wouldnt work, and also i dont really think you need that reflected vector now that i look at this.
i was thinking something along the lines of
Quaternion rotation = Quaternion.LookRotation(desiredLookVector, hit.normal);
but i dont exactly have time to test right now
so if I want here to do it right i need to split the method in 2 and each of the method goes into a different update?
Also, this doesnt solve the execute order problem
Like I was saying, if you want to split something up there it could be input as that should be polled on a non-fixed update (even though documentation does do it)
everythign else there seems fine to me, and like I was saying if you aren't sure of the correct update, you're less likely to have problems sticking it into the physics.
Is there any way I can make a variable in the inspector that you can drag a Script to? Not an instance, but the script itself, to use as a type for a Generic function? If I have a MonoBehaviour that calls SomeFunction<DataType>() where DataType : AbstractDataType, is there any way I can let a user define what DataType to use via the inspector? Ideally, they could just drag in a script that inherits from that AbstractDataType into a variable in the inspector, but I am open to other solutions I haven't thought of
It's better to be correct with the physics than running into problems later because you're doing something in update you aren't supposed to.
yeah but if i want to execute first all the non physics code and then the physics code how can i do this? Cause unity always executes first the fixed update
Using that, when the gameobject im hitting rotates below 0 on the x, the transform im using rotations on z -180 and when it rotates above 0, it goes on Z 0
To be more clear, It doesn't rotate where it should, only goes on Z (the transform I want to rotate based on the surface) to 0 when the surface is below 0 degrees on the X axis, and the transform goes to -180 on the z when the surfaces X axis goes above 0 degrees
Well, for example you have input. If you're taking input at 100 frames a second compared to fixed's 50 frames, you're just collecting input twice as fast, but ultimately it doesn't matter if you think about it.
Unless you have a specific question on what needs to be executed in a orderly fashion.
You really shouldnt just be reading the inspector values for your debugging here. It's not at all clear what this means tbh
Honestly you could even just assign transform.up to be = hit.normal
I'm debugging what it does, that's all it does, hence why the inspector values
If there wasn't any clear changes I would use Debug.Log
Anyway, i'll try that
This would basically be the problem of serializing a type which isnt possible by default. You could just go with strings and let them plug in an asset (the script) and then grab the name of the asset in OnValidate
Not too sure what you mean but not an instance when plugging into the editor, but sounds like you'd need to use SerializeReferences if the generic type isn't explicit
This worked, problem solved, thanks for the help
Well not in this case but putting input in fixedupdate is not a good practice and there will be scenarios where order execution affects
The reasoning for input being in fixedupdate being "incorrect" is less about ordering and more about input being missed.
Making an extensible asset, the component in the scene is going to add a component that extends an abstract class to objects it generates. The idea being, a user would create a script that implements an abstract class in the asset, then drop the ready-made "Initializer" prefab into their scene and assign that newly-made script to it in the inspector.
There aren't any specific instances of AbstractDataType in the scene or in any prefabs, but I want the user to define which one gets passed to AddComponent later in the code
uh so delegates seem like array of methods , is it actually like that
Strings have the problem of potentially entering an invalid name, which I would prefer to make impossible
Sounds like bawsi may have the solution of just using strings from the sound of it which honestly sounds like a solid idea
A delegate is basically a "Pattern" of a function. public delegate void MyActionDelegate(string s) matches any function that returns void and takes a single string as a parameter.
for something that doesn't require editor scripting
The only other option would be some custom editor scripting and reflection, to give the user a list of the derived types (which still would be presented with strings)
I might have to dip my toes into that. I want to try to make this as idiot-proof as possible. This asset is going to be used by interns
oh i havent used delegates with parameter yet , let me check
If you don't specify a parameter, that means you are specifying a delegate that takes no parameters. delegate void MyActionDelegate() means any function with no parameters that returns void
bro is chat gpt ๐ thanks
No, my answers are actually correct
Im no reflection genius myself (never really used it) but iirc it should be easy to get all the derived types
Another idea is using naughtyattributes/odin with show/hideif and making an enum of data types I guess
Ironically, I'm more comfortable with reflection than I am with custom editors. I can definitely get all scripts inheriting a type. I just need to come up with a way to pick them
Nah, can't do that, no external dependencies outside of the Unity Registry and our own internal repository
That'd make it pretty easy though
naughtyattributes ๐
The script file assets are MonoScript (editor only type), but inherits TextAsset, which can be referenced in serialized fields. I can't say for certain that the references will be maintained in builds, but I'm fairly certain that it will. The text contents would be empty, but the name should be readable. For MonoBehaviour and ScriptableObject types, the name of the file has to match the name of the type, so you can use the asset name to search for the type. But not useful if you have multiple types with the same name under different namespaces.
If my vs intellisense stops working after creating a new script how do i fix It?
I need to restart the IDE each time
regen project files, maybe restart unity a couple of times while doing so
did already
- Make sure it's configured correctly. !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
I've also been having issues with VS intellisense breaking every time Unity recompiles. Tested in a new clean fresh project with everything up to date, and still happening. Anyone else getting this / found a solution? It's worked without issues for years and just started suddenly.
I'm trying to wrap my head around how to make a Top-Down 2D Platformer in Unity. I know that it's possible since Lifeflame Compendium exists, but I don't know what the best approach would be.
Make any type of 2D isometric game and the idea should come to you once you start figuring how layering works with it
2D tileset is pretty good for it too
Dont crosspost, this also still isnt a coding issue
Sorry, I just donโt know where to go I joined the server I think a day ago or a few hours ago and what does donโt cross post mean?
It means dont post in multiple channels, #๐โcode-of-conduct
If you arent sure which one then theres always #๐ปโunity-talk
with unity netcode, and animations, would it be better to :
#1 Just fire the animation on the host system that moves a gameobject, and then have the animator component disabled on the other systems, and have them follow the host movement via network transforms?
or #2 run the animation on all systems at the exact same time with rpc methods?
yo! i need to have a dictionary of a class with any type. (like, i should be able to put EventProperty<string>, EventProperty<float>, EventProperty<Vector3>, etc)
I don't exactly know what to do here, or even how to putthis into words for a google search. does anyone know how I can do this?
public class EventProperty<T>
{
public string propertyName = "";
public string displayName = "";
public T value;
public EventProperty(string name, T defaultValue, string displayName = null)
{
propertyName = name;
this.displayName = displayName ?? name;
value = defaultValue;
}
}
public Dictionary<string, EventProperty<ANY TYPE> properties = new();
i would prefer to not use any sort of casting, since ideally an EventProperty<> can be ANY type
What if I want an elevated tile to have a backside so that it hides the lower half of a character's body when approached from behind?
y sorting?
If the character were to jump onto the tile, they should be put in front of it.
How are you going to use properties?
I'm making a rhythm game with a level editor, and each event can have properties (for example, a Move Character event can have a vector3 destination property)
From the dictionary of properties (the key is just the propertyName of the property), i'll use that to create fields to edit the property value (for example, if theres a Color property in the dictionary, the level editor will intantiate a color picker in the property editor)
All events are made from my Event class
public class Event
{
public string displayName = "";
public EventCallback function = delegate { };
public EventCallback preFunction = delegate { };
public float preFunctionLength = 2.0f;
public int priority = 0;
public bool sceneEvent = false;
public Dictionary<string, EventProperty<ANY TYPE>> properties = new();
public Event(EventCallback function = null, EventCallback preFunction = null, float preFunctionLength = 2.0f, int priority = 0, bool sceneEvent = false, string displayName = null, List<EventProperty<ANY TYPE>> propertyList = null)
{
this.displayName = displayName ?? "Unnamed Event";
this.function = function ?? delegate { };
this.preFunction = preFunction ?? delegate { };
this.preFunctionLength = preFunctionLength;
this.priority = priority;
this.sceneEvent = sceneEvent;
if (propertyList != null)
{
foreach (EventProperty<ANY TYPE> property in propertyList)
{
properties.Add(property.propertyName, property);
}
}
}
}
There's not really a way to make it type safe. You have to cast at some point.
ah.
Think about it this way: there is no relationship between they key and the value in your properties
But this code still doesn't show how you want to use properties, it only shows how you want to write to it.
You can have unsafe write but still safe usage, depending on what you are trying to do.
oh, well i haven't done it yet lol
i'd probably do something like
foreach (KeyValuePair<string, EventProperty<ANY TYPE> kvp in event.properties)
{
// first argument is the name of the property to save it in dynamicData, second is the property reference for making the type of editor, showing the value and display name, etc)
PropertyEditor.ShowProperty(kvp.key, kvp.value);
}
where PropertyEditor.ShowProperty() is a function that instantiates the property fields in the property editor
I'm asking because if your usage does not need to care about the specific type, eg if you just need to grab a property from properties and then .ToString() it or something, then a common pattern is to have a non generic base below the generic version:
class EventProperty
{
// Shared code that does not need to know the type
}
class EventProperty<T> : EventProperty
{
// Code that does need to know the type
}
And your properties can then simply be Dictionary<string, EventProperty>.
I'll need to know the specific type eventually for instantiating (for example, it needs to know its a Vector3 so it makes 3 fields for the property, or a Color so it makes a color picker)
which will likely happen in PropertyEditor.ShowProperty
You can do pattern matching inside the PropertyEditor.ShowProperty method.
The point is that the place where you access properties, does not need to know the specific type.
thats correct
public class EventPropertyBase
{
public string propertyName = "";
public string displayName = "";
}
public class EventProperty<T> : EventPropertyBase
{
public T value;
public EventProperty(string name, T defaultValue, string displayName = null)
{
propertyName = name;
this.displayName = displayName ?? name;
value = defaultValue;
}
}
so something like this?
public Dictionary<string, EventPropertyBase> properties = new();
Sure.
And instead of doing pattern matching on an unknown EventPropertyBase inside of PropertyEditor.ShowProperty(), you can make the EventPropertyBase have a ShowEditorProperty() method and you just call that.
oh, smart!
how would I access the EventProperty<T>? wouldnt getting a dictionary value just return the base part of it?
Didn't you say you don't need to?
i'd need to get to it eventually to change/save the value
Similar to how EventPropertyBase can have a ShowEditorProperty() method which means you no longer need to know the concrete type in order to show editor property, you can also have a Save() method.
actually, i'm a bit confused about that too; the base still wouldn't have any information about the type of the property, right? how would it know what type of property edit fields to make?
I thought you liked the suggestion of putting ShowEditorProperty() in the base class. Isn't that all you'd need? you can still CREATE it as a generic... eeg. EventPropertyBase base Obj = new EventProperty<Vector3> (name,Vector3.zero....);
i liked it until i realized i had the question I just asked, lol ๐
Inherited classes can override method of the base class.
OH
You probably wouldn't use a generic, and just have EventProperty (the base class), EventPropertyInt : EventProperty (which overwrites base class' ShowEditorProperty() to show an int field), EventPropertyString : EventProperty, etc.
so i would do something like this
public class EventPropertyBase
{
public string propertyName = "";
public string displayName = "";
public virtual void ShowEditorProperty(){}
}
public class EventProperty<T> : EventPropertyBase
{
public T value;
public EventProperty(string name, T defaultValue, string displayName = null)
{
propertyName = name;
this.displayName = displayName ?? name;
value = defaultValue;
}
public override void ShowEditorProperty()
{
//stuff here
}
}
mhm, thats probably a better idea
okay, that makes a lot more sense ๐
and ShowEditorProperty() would do the overridden one if i call it, right? adding the EventProperty<T> to the dictionary won't just throw away the EventProperty<T> stuff (including the override)?
Correct.
awesome! thank you so much for your help tonight ๐
hey i was trying to create a minimap with 2 cameras (render texture and camera for it) and now i am trying to create a fov viewport box to show what the camera can see of the minimap like in an rts. i can't raycast because the game is in space (homeworld kind of game) with no ground
- my code doesn't work properly because the fov box doesn't scale with the camera zooming in and out (y position changing) and idk how to get it working, i can't think anymore... maybe it's simple but my brain melted
https://hastebin.com/share/ulejuhapug.java
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How do you handle an override where you have three classes that inherites and want to use each others base, basicly want to use both parents and grandparents base:
public class A
{
public virtual void Func()
{
Debug.Log("A");
}
}
public class B:A
{
public override void Func()
{
base.Func();
Debug.Log(B);
}
}
Public class C:B
{
Public ???? void Func()
{
????
}
}
You just use override again
The exact code from B should work fine in C
What's the consensus regarding UI in unity?
I'm making a menu based game (think rpg), so I expect the user to be able to pick moves/item/etc.
I'm not looking for styling advice, I'm more concerned about if there is a dynamic method to populate a unit's moves/item/etc into similarly scripted menus at run-time.
There seems to be a lot of ways on youtube and some of them just don't really make sense in a real-world project. (as in it's fine for the example but not really scalable or dynamic)
Any recommendations or links to learn more about this would be greatly appreciated.
Your question is so vague, it can't be answered. You can dynamically add UI items. Do this in a system that scales the way you want, I guess?
okay, let me rephrase
I'm looking for a "clean" way to dynamically manage adding/removing UI items from menus on a regular basis with the least amount of spaghetti possible.
So make a class that dynamically manages add/removing UI items from a menu (maybe more than one class if there are different menus), but write them with the least amount of spaghetti possible... Your question is still super vague, the only thing that comes to mind is don't have menus add themselves directly to their parent RectTransforms, and that if you use GetChild or Find in any of your menu code, you failed the task
define your requirements so you can get better advice by defining things like: how many separate ui items are there? Are they defined by the characters? Can you generate them ahead of time and just disable the ones you don't need? Do they need to be updated realtime? How complicated are they? Do they need to control their layout? Are they simple "event" type actions or can they have submenus themselves?
most of the tutorials you find are going to be toy examples because it can become a complicated problem that's really specific to your use case
Thanks it turned out that the fact that I had it private on C while doing proteced on A & B caused the error
Just me not reading the error message very well
Hello, I got a problem I can't for the life of me figure out, I'm trying to do a Vampire survivors clone, and I can't seem to figure out how to make enemies crowd around the player (For when the player is overwhelmed) without the enemies influencing each other's velocity.
For example if there's more enemies to the left than to the right of the player(As they're already crowding on and around the player), the overall crowd of enemies will start pushing themselves to the right due to the majority of them pushing in that direction.
Is there a way I can simply make the enemy move towards the player but not influence the velocity or push other items(or enemies), while still stopping if they come in contact with them?
I hope I explained that correctly...
this is like a whole ass research topic
I'd start by looking into crowd simulations/pathing for RTS games
and see how they solve it there
Can I make and run unit tests without assembly definitions?
no, unity's testing framework requires them
โ ๏ธ
what's wrong with using asmdef in your case?
you can just make a root catch all assembly if you don't wanna interface with it a lot
this also mirrors how other testing frameworks outside of unity work. you would do all of your tests in a separate assembly
why
Reads the docs that are mentioned about how to reference TMPro. Hint: it has its own assembly definition
Yeah, I did this and it worked, just have to do too much to simply run unit tests...
does the Enum.GetValues method return an array of integers?
no it returns an Array object which will be an array of System.Object. but each object in the array will be one of the enum's values which can be cast to int if that is what you need
actually scratch that first part, the array will not be of System.Object, the Array object returned will actually just be an array of your enum type. just returned as an Array
There's a generic overload that returns an array of the given generic type.
@inner shuttle check the docs and it will be explained in detail
yeah its fine i got it
quick question does anyone knows where i can find a trained version of the ml-agents Soccers Two
this overload is .net 5+
anyone use steam in their game? im having this problem where SteamClient.isValid becomes false sometimes
This depends largely on what your requirements are and what UI framework/solution you are using but if I were you, I would probably look into the MVP (Model-View-Presenter) pattern. There is a lot of information about this pattern and some Unity-implementations as well, this will ensure that your UI (View) is separate from the data (Model) and they communication via a Controller/Presenter. Once you have this type of structure in place, you can expose events to switch between presenters and this should update the view as well. Maybe you could have a Stack<T> of presenters or a way to inject them when needed (if using some DI/IoC framework) but this will help keep your UI clean but also able to switch it out at runtime (however you choose to do this depends on your requirements and architecture). Here is an article that goes over how to implement MVC/P in Unity: https://unity.com/how-to/build-modular-codebase-mvc-and-mvp-programming-patterns
@civic girder There is also a good video on the topic that shows how to implement this type of pattern for UI: https://www.youtube.com/watch?v=v2c589RaiwY
Demystify MVP and MVC Architecture for Unity in simple terms focusing on the Separation of Concerns and a practical example building an MMO style hotbar using a Model, View and Controller.
๐ Subscribe for more Unity Tutorials https://youtube.com/@git-amend
Discord: https://discord.gg/FDRZGQBBUC
#unity3d #gamedev #indiedev
โฌ Contents of this...
hey, im looking to use the discord SDK for RPC, every time i have tried, if discord is not open on initialzion, the game crashes (and somehow so does the editor), and if it is open and it gets reloaded (ctrl+r), i get the error NotRunning, when i try to handle it to keep checking and update the status, it doesnt detect that its open, and keeps spamming the custom error i made
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Discord;
public class DiscordController : MonoBehaviour
{
public Discord.Discord discord;
private bool isConnected = false;
// Use this for initialization
void Start()
{
// Attempt to initialize the Discord SDK once
InitializeDiscord();
}
private void InitializeDiscord()
{
if (discord != null)
{
Debug.Log("Discord SDK is already initialized.");
return; // Prevent multiple initialization attempts
}
discord = new Discord.Discord(1299033841154920529, (System.UInt64)Discord.CreateFlags.Default);
var activityManager = discord.GetActivityManager();
var activity = new Discord.Activity
{
State = "Still Testing",
Details = "Bigger Test"
};
// Update activity and handle the response
activityManager.UpdateActivity(activity, (res) =>
{
if (res == Discord.Result.Ok)
{
isConnected = true;
Debug.Log("Discord SDK successfully loaded!");
}
else
{
Debug.LogError("Failed to update activity: " + res);
}
});
}
// Update is called once per frame
void Update()
{
if (isConnected)
{
try
{
discord.RunCallbacks();
}
catch (ResultException ex) when (ex.Result == Discord.Result.NotRunning)
{
Debug.LogWarning("Discord SDK is not running: " + ex.Message);
}
}
}
private void OnApplicationQuit()
{
// Clean up Discord on application quit
if (discord != null)
{
discord.Dispose();
discord = null;
}
}
}
Hey
Pardon the late reply.
I'm using the built in stuff for now, but open to anything.
My requirements are similar to any menu based combat system (think srpg/ttrpg like disgaea, fft, any older ff game, etc)
I'll read through the material you linked, thanks ๐๐ป
I suggested the MVP pattern because that works well with Unity's UGUI/canvas system and having a structure like that will make it easier to switch UI's based on the controller/presenter, you can do this via events or in a variety of different ways but it should help you keep and maintain a clean UI. Especially if you have a heavy-UI project which tends to be the case with RPG-type projects
No problem
I have a UI that comes up when the player is looking at an object, but i want another tracking ui to come up when the object is in screen within a certain range like for instance inside the dotted lines (the normal lines is screen edge) what is a good way to go about this since it should depend on distance and also another raycast looking if somethings blocking it?
don't normalize it. Clamp it
movement = Vector2.ClampMagnitude(movement, 1);
you're clamping the final position
you're not clamping the input vector
you're doing some pixel perfect thing
after movement gets assigned
delete the if statement
it is not necessary
If Unityโs social api is deprecated, then what to use now? (Iโm specifically talking about the android google play services package from the github - it still uses the social api)
they're both mag of 1 they are 0.7 together
I fixed this easily on new Input System by switching composite type, forgot how to do it on old input system now tbh lol
omg it works
IEnumerator MyCoroutine(int waitForSeconds)
{
yield return new WaitForSeconds(waitForSeconds);
yield return true;
}
IEnumerator CombinedRoutine()
{
var list = new List<IEnumerator>();
for(int i = 0; i < 5; i++)
{
var enumerator = MyCoroutine(i);
list.Add(enumerator);
_ = StartCoroutine(enumerator);
}
yield return new WaitUntil(() => list.All(x => x.Current.Equals(true)));
}
game changer
yield return true; ? ?
also the amount of garbage here
yield return new WaitUntil(() => list.All(x => x.Current.Equals(true)));
like do list.Any instead
this code is filled with wtfs
list.Any(x => !x.Current.Equals(true)), so it doesn't always have to check the whole collection, it stops at the first non-match
why not just use tasks anyway
its basically experiment to see how these coroutines would work and if i can use linq for simple stuff
you can just TaskWaitAll
yes but task have to be cancelled manually
yea, didnt check these out yet, but i will. For now i just do playground around coroutines to better understand how they work
yeah , did you get the new Input System
my script is literally this cs void OnMovement(InputValue val) { movement = val.Get<Vector2>(); }
my input values diagonal never output to 0.7 which is what causes slowdown moving diagonal
nah you don't use Update with the new Input system
you can but you generally use Events or Messages
this is using Send messages which is more or less like events
the movement action is called Movement so the method called is just OnMovement ( this is standard out the box for new input system, yes its that easy)
sorry to disturb, but could you tell me more about that? Afaik .All and .Any dont allocate much garbage, but im not sure about YieldInstructions, which are basically just another coroutines, so no idea how to avoid it here. obv its not about .Equals
idk if its a big deal anyways, if not used too frequently
its not a huge deal just being pedantic on performance, i was meanly refering to the new() WaitUntil (()=> part
I don't do pixel clamp, but I use this in regular .velocity or whatever other style rb movement, yes I always use FixedUpdate for rbs
idk wat you mean by pixel perfect clamp
boost
oh idk I use cinemachine and let it take care of it, but I don't often do 2d
idk I haven't noticed jitter on mine
my game is a platformer so it doesn't snap to grid
Is it recommended to have all your inputs in one singular action map
so question. when you use Physics.OverlapSphere or Physics2D.OverlapCircle the sphere/circle that is created, is it usually a child or something or is it not parent to anything at all?
It doesn't exist at all, it's a query made directly to the physics engine
Depends entirely on the needs of your specific game
Is it possible to split a navmesh agents path corners into multiple vertexes to smooth the path out?
ive been googling for ages but i havent found anything on that in particular
So I upgraded my project to unity 6, and now all of a sudden some random TextMeshPro scripts have 1-6 errors each
Most of them are like this:
this is the specific script these 4 errors are in btw:
Update TMP from the Package Manager, and reimport the TMP assets
i was using safe mode, so i didnt see this popup
Also what happened here?
Yep that'll overwrite the scripts with their new versions, hopefully fixing the issues in the process
oh ok
would deleting this make my visual studio unlinked with unity?
so i wouldnt see errors anymore?
VSC now uses the Visual Studio package as a backend
Is that built into VS or is it something I download?
It's a package that should be right aside the deprecated one in the Package Manager
OH I JSUT REALIZED
"Visual Studio Editor"
VISUAL STUDIO CODE AND VISUAL STUDIO ARE DIFFERENT
Yup, but now both use the same Unity package to run
I dont use Visual Studio Code, I use Visual Studio 2022
Oh lol
No worries
Hey question
i have this class DamageInfo
its is passed through OnHit() everytime an entity gets hit.
The question is, would the TryGetComponent() cause lag or other issues in my case?
For context im making a vampire surviror-esque game
so expect a lot of bullets/hits
๐ค maybe its better to have a field for PlayerStats and check whether its Null
public class DamageInfo
{
private PlayerStats _playerStats;
public float GetDamage()
{
if (_playerStats == null)
{
bool didFind = TryGetComponent(out _playerStats)
if (!didFind)
{
Debug.LogError("oops");
}
}
// .. damage calc here ...
}
}
does the tryget once instead of every time something gets hit
better would be to do the trygetcomponent in an awake or init, but unless you have hundreds+ of items that are all doing the tryget at once, it's probably fine
this is within the damageinfo, every possible damage source creates a new damageInfo so it would still call tryget... right?
Assets/Scripts/Gun.cs(7,35): error CS0115: 'Gun.Use()': no suitable method found to override
using System.Collections.Generic;
using UnityEngine;
public abstract class Gun : Item
{
public abstract override void Use();
public GameObject bulletImpactPrefab;
}
i dont think you put abstract in the void
Oh, I didn't see that. Then yeah, better would be to pass a PlayerStats to this since it's just a static helper class
just override
im getting this error from my gun script but when i remove override i get more errors for other scripts and when i fix them more errors appear
does Use already exist in item?
fix one error at a time, but also don't just remove/add code blindly... in this case you've got an abstract gun class (good) inheriting use from an abstract item class (good), but you don't have an implementation for use.. you don't need to, to place it in the actual gun children
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Item : MonoBehaviour
{
public ItemInfo itemInfo;
public GameObject itemGameObject;
public abstract void Use();
}
@modern creek correct me if im wrong but you use virtual void even in abstract right?
i do
public abstract class Item
{
public abstract void Use();
}
public abstract class Gun : Item
{
// nothing required
}
public class MachineGun : Gun
{
public override void Use()
{
// shoot
}
}
gun doesn't need to say it requires an abstract signature for "use" - it already inherits one from item
when you create your "real" gun class, then you have to implement use
virtual is different than abstract
whats the difference between the abstract and virtual void
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class SingleShotGun : Gun
{
[SerializeField] Camera cam; // The camera to shoot from
[SerializeField] GunInfo gunInfo; // Reference to GunInfo
PhotonView PV;
void Awake()
{
PV = GetComponent<PhotonView>();
}
public override void Use()
{
Shoot();
}
void Shoot()
{
Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f)); // Center of the screen
ray.origin = cam.transform.position;
if (Physics.Raycast(ray, out RaycastHit hit))
{
hit.collider.gameObject.GetComponent<IDamageable>()?.TakeDamage(((GunInfo)itemInfo).damage);
PV.RPC("RPC_Shoot", RpcTarget.All, hit.point, hit.normal);
}
}
[PunRPC]
void RPC_Shoot(Vector3 hitPosition, Vector3 hitNormal)
{
Collider[] colliders = Physics.OverlapSphere(hitPosition, 0.3f);
if (colliders.Length != 0)
{
GameObject bulletImpactObj = Instantiate(bulletImpactPrefab, hitPosition + hitNormal * 0.001f, Quaternion.LookRotation(hitNormal, Vector3.up) * bulletImpactPrefab.transform.rotation);
Destroy(bulletImpactObj, 10f);
bulletImpactObj.transform.SetParent(colliders[0].transform);
}
}
}
!code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh i see, abstract requires you to override/implement it
abstract must be implemented, virtual can be
good use case is .. abstract is for members that make no sense unless implemented... virtual is for members that are usually the same but can be overridden
i see i see
this might just be me but wouldnt Shoot() be better as abstract void of base class Gun since every gun is supposed to shoot?
Example: I have a tile game like 2048. Everything's a tile:
public abstract class TfeTile
{
public abstract int MoveSpeed { get; } // makes no sense in the abstract - every tile must define a move speed
public int Id { get; set; } // doesn't require implementation - it's the same for everything
}
public class TfeNumberTile : TfeTile, IMergeable
{
public override int MoveSpeed => ITfeTile.MovesInfinitely;
}
public class TfeSnailTile : TfeTile
{
public override int MoveSpeed => TileType switch
{
ForegroundTileType.Snail1 => 1,
_ => throw new ArgumentException($"Invalid tile type for snail tile: {TileType}"),
};
}
Since the base is an Item, it makes sense to just have a Use although more complex cases would require more methods probably
depends on if "use" means equip or something, but that's up to the developer to decide what "use" means
I'd probably have guns be their own thing (and not derive from item)
yeah so youd use abstract for base classes you would never want to instantiate on their own
but that's just sorta how i think of things, depends on what the game is, how your world is structured, etc
because guns have all kinds of unique behaviour.. reload, aim, enable safety, fire secondary mode, etc
abstract classes can't be instantiated - they're abstract
You already have a GameObject Attacker and Target. Those shouldnt be GameObject as that's pretty much useless. Change it to something that every object which can be damaged has
Im lost now
in this case, there's no such thing as Gun - there's only a MachineGun which is a type of Gun (and so shares all the details described in gun)
inheritance is hard, but ... you'll need to learn it, probably, if you want to do it right.. it's why computer science degrees exist ๐
But if it's confusing you, there's no problem with just making a class for each type of gun and just copying and pasting code
im still in school lol
ie, do away with all of abstract/virtual
currently in yer 10
you'll start to find out why you'll need it in time
learning unity for IT
yet they are MAKING me work with python on my second IT study
๐ญ
it's good to learn multiple languages tbh
so you can see why one language does things one way, or what aspects of a language you like or don't
c# is king though ๐
ikr
i already have an IT graduation in mostly c# and im going for that higher education one
@modern creek so u reckon the best option is to remove override and go through all the errors it gives me
Here's another example from a different game. In this game, there are Entities - they have things like health, location. The abstract class I've made is called EntityBehaviour. There's no such thing as an EntityBehaviour by itself - only a derived class like "Engineer" or "Commander" or something.
if this helps its a multiplayer fps game
public abstract class EntityBehaviour
{
public abstract int StartingHealth { get; }
public virtual int CurrentHealth { get; set; }
public virtual void Initialize()
{
CurrentHealth = StartingHealth;
}
}
public class CommanderBehaviour : EntityBehaviour
{
public override int StartingHealth => 6;
}
note - abstract starting health but virtual "current" health
the commander doesn't need to "implement" (or "derive" this integer - it's the same for everyone - ie, it's set to the starting health)
that being said, there's no "default" starting health.. since every entity is different.. so that data point must be overridden in the child class
the reason to do this is that you can always perform entity-specific code on a commander (or anything that inherits from entity)
ie:
// kaboom
foreach (EntityBehaviour ent in AllEntitiesList)
{
ent.CurrentHealth -= 5; // everyone takes damage
}
@lean sail the thing now is that when the hit is registered and the DamageInfo is created i still have to call a GetComponent()
@sterile reef What you really want is a "model" for your player - google up "plain old class objects" or "data access object"
You'd then have your game object rendered by a class that handles rendering, but has a reference to the player in question
the getcomponent is the enemy being hit
(or player depending on whos hitting who)
public struct PlayerData // not a MB or GO
{
public int Health {get; set;}
}
public class PlayerRenderer
{
private PlayerData _playerData;
public void Initialize(PlayerData player) => _playerData = player;
private void Update()
{
/// show their HP somehow
MyTextComponent.text = _playerData.Health.ToString();
}
}
You should only need one get component, that is the IHittable. IHittable should contain everything needed
oh yeah true
Is this a issue because Iโm trying to get my characters camera to move, but it says this thing in the bottom left of my screen thatโs all in red
That's a runtime error
You should open the console window
To see your errors and logs
It's basically telling you exactly what the problem is
You didn't assign a variable that you're trying to use
How do you assign a variable?
most likely if you click on your object that has that script, you will need to input a transform for groundcheck, so just drag N drop a "groundcheck" object into it
This is gonna sound super crazy but how do I dragon and drop a ground check and what is it?
I mean, Drag
Click the mouse button when hovering over one, and move the mouse without letting go of the mouse button, until your mouse is over the variable you want to assign it to, then and only then, releasing the mouse button
click on your gameobject that has the script, you should see a missing field in where your groundcheck variable is, you need to literally drag and drop an object from the heirarachy to that field, supposedly a "groundcheck" object which you should have
I thought that was what it is. I just donโt have to drag and drop it. I just have to press on it.
But now itโs showing a yellow bug
a warning?
Again, https://screenshot.help/
yes so a warning, they are not errors and will let everything compile but they will tell you useful information
First of all, Iโm not learning how to take screenshots. I have a thing called a phone.
You are using unity on a computer
A computer that can take screenshots
Yeah, but itโs just easier to take screenshots on my phone
These aren't screenshots
Then where are they are shots? ๐
People will very quickly stop helping if you wanna insist on sharing things in a worse way. No one wants to read bad quality images and fight to help you
It says release mode do you think I should do that cause Iโm quite new to this whole unity thing
I don't know what that is, if I'm being honest
Give me a sec Iโm talking to dec
Ok
bawsi and digi are correct though
Win+Shift+S the region, Ctrl+V in discord, literally done
Ok I have discord on my phone, not my computer
Iโm doing the release thing hopefully it doesnโt do some bad crap
It said to release ?????
Oh my God, it works finally after hours of painful smashing my keyboard JK it works!,!
ah just looked in docs, you probably do not want to go in release mode for debugging since it disables C# debugging AKA external debuggers
https://docs.unity3d.com/Manual/managed-code-debugging.html
Now I just have to repeat that painful cycle, but this time make it so my character can move
Iโll keep that in mind for next time
yo, i'm back! i need to put these EventPropertyValues in a List. They need to work as ANY TYPE (like EventPropertyValue<string> or EventPropertyValue<int>, so I have it wrapped in a typeless class that i can put as the type for the list. this works, but unlike last time, there's a problem. i need to be able to access the value, which I can't figure out how to do. does anyone have any solutions?
public class EventPropertyValueBase
{
public virtual void GetValue()
{
Debug.LogWarning($"Can't get a value because there's no type!");
}
}
public class EventPropertyValue<T> : EventPropertyValueBase
{
T value;
public override T GetValue()
{
return value;
}
public EventPropertyValue(T value)
{
this.value = value;
}
}
oh hi again lol
You can return a value like object but, why do you need to access the value?
what do you need to get the value for? with this current setup, the only way i can see this being done is by trying to cast but that usually is against the whole usecase of generics/inheritance if you're checking for every single possible value
generics/inheritance is specifically so you dont need to do this
You could probably cut the generic on the class, and make a generic GetValue method.
private object val;
public T GetValue<T>(){
if (val is T outVal) return val;
else{
Debug.Log($"Value is not of type {typeof(T)}");
return default;
}
}
this is for my rhythm game, specifically the chart save/load system. Theres 2 main concepts: Events and EventEntities. Events are reusable objects that don't change; they contain stuff like the function delegate, priority, scene toggle, etc. you don't need to know what tjose are, the important thing is that every Event of the same type has the same stuff.
example:
eventDictionary.Add("pulse", new Event(PulseCharacter, propertyList: new List<EventPropertyBase>
{
new EventPropertyInt("charID", 0, false)
}
));
EventEntities are like the individual instances of an event; theyre stored in a list as the level's chart, and contain stuff like the datamodel (aka the event name), beat to run the event on, and (relevant to this), a dictionary of the event's properties known as dynamicData (since each event can have different properties)
example:
new EventEntity() {
datamodel = "pulse",
beat = 0f,
dynamicData =
{
{"length", 4f},
{"startColor", new SerializableColor(1,1,1,1f)},
{"endColor", new SerializableColor(1,1,1,0f)},
{"instant", false},
}
},
None of this seems related to the part of why you need to get the value from a list which doesnt know the type, or doesnt even know that the value exists
i'm getting there
You can just state the related part, if parts of it dont relate then it's just more confusion
ah sorry
i thought it was important to mention i guess
the point is, i'm going to be making those dynamicData entries by looking at the event's properties, but i need the defaultValue to do that (and later, i'm going to need value from EventPropertyValue<T>)
foreach (KeyValuePair<string, EventPropertyBase> property in RhythmGameManager.eventDictionary[datamodel].properties)
{
dynamicData.Add(property.Key, property.Value.defaultValue);
}
what exactly is outVal here?
A local variable of type T that the val is cast and assigned to.
couldn't i just do (val is T)? Sorry, I don't know much about is
since outVal isn't used
should return outVal rather than val otherwise it will error because you can't implicitly cast object to T
How is dynamicData going to use the default values?
Right my bad, I wrote this quickly
It's the result of casting the object to T. If it's successful, outVal will be a variable of type T and should be what you return instead of val
Because I don't see how dynamicData can be type safe just like you can't make property type safe.
right now, dynamicData is just a Dictionary<string, object>
If your dynamic data is just going to do something like dynamicData.SerializeToJson(), then you can just store the properties (rather than the values), and dynamicData.SerializeToJson() simply loops through the properties and call property.SerializeToJson().
Basically the same idea as how you solve the property problem, have a common base to represent what you actually want to do.
actually, thats what i was planning to do (if i understand you correctly)
wait hold on let me think-
Don't think in terms of the implementation, think about what you want to do with dynamicData first.
okok hold on
i need to access the property value somehow, whether thats as an object directly in the dictionary or the value of an EventPropertyValue<T>
public void SetFlash(EventEntity entity)
{
float beat = entity.beat;
float length = (float)entity.dynamicData["length"];
Color startColor = (SerializableColor)entity.dynamicData["startColor"];
Color endColor = (SerializableColor)entity.dynamicData["endColor"];
flash.SetColor(beat, length, startColor, endColor);
}
i think i'm confusing myself even more ๐
Have a common base class/interface that exposes Length/StartColor/etc as properties, and your dynamicData can just be that base class/interface.
A base class/interface is how you do "I don't need to know what it is, as long as I can use it in a certain way"
Did they remove RoundToInt? All the documentation says it exists but when I go to use MathF.RoundToInt it says it doesnโt exist
Mathf
Not MathF
You want the UnityEngine one
Oh wow thank you. I thought I was crazy
im having some trouble with my save system, for some reason when I save it, it duplicates the number of cubes (i.e. if there's 1, it places 2 in the save file)
private bool isSaving;
public void SaveGame() {
if (!isSaving) {
isSaving = true;
foreach (SaveManagerInterface saveObject in saveObjects) {
saveObject.SaveData(ref gameData);
}
dataHandler.SaveToFile(gameData);
print("save");
isSaving = false;
}
public void SaveToFile(PlayerGameDataFile data) {
string fullPath = Path.Combine(filePath, fileName);
try {
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
string JSONDataString = JsonUtility.ToJson(data, true);
Debug.Log(JSONDataString);
try {
File.WriteAllText(fullPath, JSONDataString);
} catch (Exception ruhroh) {
Debug.LogError(ruhroh);
}
} catch(Exception err) {
Debug.LogError(fullPath + ", " + err);
}
}
could someone help me figure out how to make the ball not clip through the windmill
So you see the duplication in Debug.Log(JSONDataString)?
nvm i fixed it
Yes, thereโs two cubes placed inside the JSON
The JSOn prints once though
Check if you're just adding text to the file. Maybe you should clear it before writing to it.
i added:
try {
File.Delete(fullPath);
File.WriteAllText(fullPath, JSONDataString);
} catch (Exception ruhroh) {
Debug.LogError(ruhroh);
}
before it shows 2, and in the actual file there's also 2
if i play again, there's 4 this time
it seems to grab two before somehow
Then there's something wrong with your data. What exactly are you serializing?
all the children of a gameobject called Cubes
this gets added to by the player
i want to save these objects, however they seem to duplicate
Share the contents of that class. Is there a list or something?
[Serializable] public class PlayerGameDataFile {
public Dictionary<float, Color32> Colours;
public float Cash;
public float MaxSize;
public List<Cube> Cubes; // important part!!
public List<Machine> Machines;
public PlayerGameDataFile() {
Cash = 0;
MaxSize = 0;
Colours = new Dictionary<float, Color32>();
Cubes = new List<Cube>();
Machines = new List<Machine>();
}
}
Print the number of cubes in the list before saving it.
before collecting items to save, it finds one, then it collects and has two
it's here:
public void SaveGame() {
if (!isSaving) {
isSaving = true;
foreach (SaveManagerInterface saveObject in saveObjects) { // cubes collection
saveObject.SaveData(ref gameData);
print(gameData.Cubes.Count);
}
dataHandler.SaveToFile(gameData);
print("save");
isSaving = false;
}
}
Well, then the issue is not with your saving system but the "collecting" logic.
sent it just now
Where are you adding to the Cubes list?
where it says saveObject.SaveData(ref gameData)
-# this code is a bit convoluted i think, even for myself ._.
i had an idea: where upon loading, i get each item with a unique position, because no items can clip inside each other
however, if cubes data isn't overwriting which i suspect is another issue, it may not work properly
the cash and maxsize objects do overwrite, the cubes list just never overwrites i think, which sounds strange but i don't know what the issue is
How exactly are you trying to overwrite it?
And no. This is not where you add to the list
im pretty sure WriteAllText overwrites it, but i also have another thing before it to Delete the file before creation
As I said multiple times, the problem is probably where you modify the list.
public void SaveData(ref PlayerGameDataFile file) {
foreach (Transform cube in CubeParent.transform) {
print(cube.name + ", " + cube.transform.position + ", " + cube.transform.rotation); //dbg
file.Cubes.Add(new Cube(cube.name, cube.transform.position, cube.transform.rotation));
}
}
And how many times does that print?
it prints once, but counts two cubes
Wdym? How do you know what it counts?
print(file.Cubes.Count)
Where?
after the Add
public void SaveData(ref PlayerGameDataFile file) {
foreach (Transform cube in CubeParent.transform) {
print(cube.name + ", " + cube.transform.position + ", " + cube.transform.rotation);
file.Cubes.Add(new Cube(cube.name, cube.transform.position, cube.transform.rotation));
print(file.Cubes.Count);
}
}
it prints once, but has a Count of 2
Then the list has cubes added previously or somewhere else.
before saving data, im gonna try file.Cubes.Clear()
after all, it should add cubes to the list after that, so it will be empty in theory before adding
it works
You were probably never clearing it, so saving multiple times would keep on adding more elements to the list.
if i remember correctly, I populated the list, then loaded data based from the list, and then appended cubes on top whenever i saved instead of clearing it
If I configured VS Code to be my IDE when working with unity and I can autocomplete the methods but it doesnt show the descriptions, how do I fix it? Also want to change the icons from the autocomplete thing cause the default ones are kinda bad
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
Clamping the vector to 1 makes its diagonal length "shorter" then one axis. Imagine going one inch up and one inch right, the diagonal from 0 to 1,1 is not the length of 1, right?
yeh, but you are clamping your vector length to 1. So it will never reach 1,1
you should just take pen and paper and visualise it to know, what happens ๐
Your movement is 0.71? You are still clamping it in update
The pixel perfect clamp is not really needed unless you are working with certain stylized effects that might affect rendering
based on what I am seeing here diagonal movement should be the same speed, I would assume optical illusion
Is this good practice to use StringToHash?
It is, but prehash them. It's gonna be heavier than just using strings if you keep it as is, since you calculate the hash every time.
Ah that makes sense
Hey folks
I'm doing a top down placing board, I want to move camera in XY plane. But also have a nice effect to return camera to position if you pan too much in one direction
I've kinda achived that with cinemachine virtual camera with 3d confiner
But, when I control VirtualCamera, it confines actual camera, and position of acttual Cinemachine camera is absolute, so I continue to move it infinitly in the direction
Now, I tried a fix _cinemachine.transform.position = _cinemachine.State.FinalPosition; if _confiner.CameraDisplaced(), but now it feels laggy, any ideas how to improve it?
void Update()
{
if (_panAction.IsInProgress())
{
Debug.Log($"Raw {_cinemachine.State.RawPosition}");
Debug.Log($"Correction {_cinemachine.State.PositionCorrection}");
var direction = _panAction.ReadValue<Vector2>();
Debug.Log($"Move direction {direction}");
transform.position += Time.deltaTime * moveSpeed * new Vector3(direction.x, direction.y);
if (_confiner.CameraWasDisplaced(_cinemachine))
{
Debug.Log("displaced");
_cinemachine.transform.position = _cinemachine.State.FinalPosition;
}
}
}
Hello I am looking into the Unity 6 Design Patterns demo and I always was wondering why properties are done like this:
private bool isActive
public bool IsActive => isActive;
Isn't it just cleaner to use IsActive in the first place with private set? I am not sure but I think it's something from "back in the days" where we didn't have option to separate accessors for it?
you use it for properties you want to publish to the inspector but not to other classes
[SerializeField] private bool _isActive; // Shown in inspector but not to other classes
public bool IsActive => _isActive; // Now published to other classes
But you can publish auto-property to inspector too?
and to keep the declaration of properties to the inspector the same, regardless if you want to publish it to other classes or not you always use that method, you just omit the bottom part if you dont want to publish to other classes
yes but the auto properties are always also shown in code completion as they are part of that classes public properties
I think it would be helpful to explain the practical reasons for doing things like this
if you want to show to inspector but not to other classes -> only the private property
if you want to show to both -> private property + public property
Ok, that convince me more
Like just cause I want to expose 15 sprite fields to the inspector i dont want other classes to show them in autocomplete (or be able to access them) all the time ๐
And no, public bool IsActive => _isActive is not shown in the inspector
Auto properties are with [field: SerializeField]
not shown by default* ๐
That's why I use "can" in that sentence ๐
anyone know how to get the "Visual Studio For Mac" outline in the Windows version? look how beautiful this looks, compared to the bloated, messy visual studio for windows...
visual studio for mac was actually a completely different program that was just rebranded to be called "visual studio". it's unlikely you'd be able to get the real visual studio to look like this
and using code is not an option for this case...
I tried minimizing mine to look as debloated as possible, but it still looks wild
To add onto what has been said, creating a backing field for the property will allow you to keep that field private/local to the class. This means that if other system need a reference to "isActive", you just pass around the property instead of the field but another thing that properties allow you to do is add some sort of validation or notification to the getters/setters. So for example, in the property's setter portion, you can raise an event each time it is called/invoked. So you could have something like this:
private int age;
public int Age
{
get {return age;}
set
{
if(value < 18)
{
//throw exception/error
}
RaiseAgeEvent();
}
}
Use Visual Studio Code instead if you want something clean and minimal
this was basically a Xamarin app reskinned to look somewhat like VS
Is there a "code review" channel here?
You can ask in here
Its a very long script, I just wanted to post it so people can notify me if I made any errors or if I can make something more efficent
This is it ^
Is there any parts of it you are concerned about?
Not really
Anything physics related should be done in FixedUpdate
why are there so many static variables that don't even need to be static? you just assign them in Awake regardless of whether they are already assigned
normally, but character controller has better results in Update for some reason
that sounds... weird ๐
also you use regions to separate behavior inside of a method. Split that into different methods for each type of behavior and just call those methods from Update
I don't believe the CC uses physics to move so it would make sense that it might to better in Update() than in FixedUpdate()
That's a good idea
Thanks
I dont think charactercontroller counts as a physics component
Does it?
its like a weird kinematic controller or something lol if you use SimpleMove it does use gravity for example
its technically a physics object but its handleded like a kinematic so its not affected by other forces or anything.
My bad then, never used the character controler, always just custom implementation + rigidbody and assumed it just uses physics too
technically anything with a collider is a physics objects
collision = physics
it automatically uses Gravity if SimplemMove?
I didnt even notice the static keyword
might need to test that
Really? So I didnt have to manually apply gravity this whole time?
you can't jump if you use SimpleMove because it ignores all movement on the Y axis
no its best you apply your own
Why
even the manual mentiones
Velocity along the y-axis is ignored. Speed is in units/s. Gravity is automatically applied. Returns if the character is grounded. It is recommended that you make only one call to Move or SimpleMove per frame.
Thats strange
thats because its overriding it on its own
Returns if the character is grounded
But what does it return
so its a kneecapped RB
I never use simplemove anyway, but either way that should be the only physics a CC gets
I mean like I said, technically all collider objects are physics but yeah its not DYNAMIC physics
I wanna code a grapple hook mechanic. How can i do that. Its a first person platformer i wanna make.
I just made one in 2D recently so, maybe I can help
Should i use character controller or rigidbody
well yes, it still responds to collisions so im wrong that it isnt physics object. thats my bad on my part ๐
thats mostly a design choice on your game though
this qustion has been beaten to death
its mainly up to preference
Rip
do you want to deal with fighting the "natural" physics forces etc.
if you know how to code physics and need snappy movement, sure use a CC
if you are a beginner or an expert alike, but want the physics "feel" of a RB and dont want to code physics, sure use a RB
Kinematic is best for most control. Now do you want to deal with stairs on your own?
otherwise use CC (also has other benefits)
Coding your own physics sounds harder
Kinematic can feel snappy but again its similiar to getting CC to work nicely
except CC already can hop step-height, kinematic rb can't
Their is a trick for stairs. Use straight collisions
tbf you need to code stair and slope movement for a kinematic RB
you mean slopes? yes thats normally how its done anyway. no one likes feeling the "bump"
I wish i could use both cc and rb
why.. that would make no sense
thats like saying I want to drive a car while driving a truck
jeeptruck lol
Anyway how do i code a grapple hook
those exist and are abominations
depends how complex it will be
its a lot harder with a CC since you will need to know how to use vectors and quaternions and trig, while with a RB just use a physics joint and some forces to move around
maybe just use Dynamic RB(whilst grappling ) if you plan on adding some type of "swing" otherwise you need to manually code it with Sin/Cos functions
I am just working on a passion project. Nothing overly complex
How does physics joint work. Havent heard about it yet
!docs
I personally used a Rigidbody and Spring joint
works well for my usecase
you canmake the rb swing on it and stuff
Cool.
basically I shoot a ray, then the Hitpoint gets the anchor of the Spring and attach to my player rb
play around with the spring amount to control shrink / extending "the rope"
Do you have to point your cursor to the hook?
point the cursor to the object which the "hook" will lay on? yes
my game is a sideview platformer (think contra) so you just point your weapon towards it (shoots an arrow that you can swing from)
only when firing it though
Sounds cool
Also something unrelated to thiz, i am looking to learn math and physics specifically for unity gamedev where can i start
well gamedev uses traditional math, you can learn how physics work by any physics textbook out there
mostly trig math
was hard to get a swing in that spot lol i couldve picked a better spot smh..
thats terrifying that that beam can shoot through walls
Wall hax
it can't it can only aim through walls, but will shoot whatever is in way of ray (walls including)
but you can see the visual so you know when not to poke your dome ๐
are structs just a group of similar group of variables and can call them like such struct.VarA/B/C?
I'm not entirely sure if I should use them over/with classes or not
structs are value types and (typically) live on the stack rather than the heap. they are passed by copy rather than reference
structs are just like classes, except internally they are handled different
whenever my fields/props are mostly value types, I stick to structs are they are slightly more performant since they not need to be GC like ref type
one annoyance is that Unity doesn't support the latest c# so you can't initialize structs fields with values..
public struct SomeInterestingData
{
public int Bleep = 40; //not allowed
public int Bloop;
}```
so instead of referencing the struct like a class, it copies itself like struct Mystruct St;?
instead of Class _Class;?
notice how when you change .position you have to assign a new v3
you can never change the original position of an object
you always get a copy / replace with a new struct
instead with transform a reference type, once you store the reference in Awake lets say.. its always the same transform
thats why you can't cache an objects position in awake if you want to constantly have the current value
so instead of directly modifying them, it creates a copy so you modify the copy instead
yea thats why you assign it back
Yo need a little help here please.
Here is what it's supposed to happen:
the player has an empty object with a trigger that when got triggered like collides with a weapon in this case, it should made the weapon a children of the player and move along the player, like what happens after the NPC moves across the weapon. But it didn't. The NPC part works, but the player will always get nullref. I don't understand why, could someone help me?
please?
if you want help you should at least post the related code..
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag=="supply"){
Debug.Log("collected");
supplt.pickup();
picked=true;
}
else if(other.gameObject.tag=="melee weapon 1"){
weapongrab.grab(player.transform);
}else{
Debug.Log("eeee");
}
picked=false;
}
the part where the player got nullref, but not the NPC
dont cross post
we can't see from this what is line 23..
you outta post the code properly @gritty badger
โฌ use links
๐ 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.
stupid halloween sound, you can change it in sound settings
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag=="supply"){
Debug.Log("collected");
supplt.pickup();
picked=true;
}
else if(other.gameObject.tag=="melee weapon 1"){
weapongrab.grab(player.transform);
}else{
Debug.Log("eeee");
}
picked=false;
}
mate also this belongs in #๐ปโcode-beginner
and the geab function
public void grab(Transform _parent){
knife.transform.SetParent(_parent);
knife.transform.position=new Vector2(_parent.transform.position.x,_parent.transform.position.y-1);
}
grab
what are you doing my guy
you just posted the same code 3 times
you just ignoring what was just said
but this is different
this helps nothing
literally
you have to show the script and what is LINE 23
the sensible thing most people do is post the entire script, properly through a link
weapongrab=GameObject.FindGameObjectWithTag("melee weapon 1").GetComponent<weapongrabscript>();
idk why you're making this fucking diffuclt
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Scripting;
using UnityEngine;
using UnityEngine.InputSystem;
public class triggercollectscript : MonoBehaviour
{
public GameObject player;
public suppltscript supplt;
public bool picked;
public weapongrabscript weapongrab;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
supplt=GameObject.FindGameObjectWithTag("supply").GetComponent<suppltscript>();
weapongrab=GameObject.FindGameObjectWithTag("melee weapon 1").GetComponent<weapongrabscript>();
picked=false;
}
// Update is called once per frame
void Update()
{
supplt=GameObject.FindGameObjectWithTag("supply").GetComponent<suppltscript>();
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag=="supply"){
Debug.Log("collected");
supplt.pickup();
picked=true;
}
else if(other.gameObject.tag=="melee weapon 1"){
weapongrab.grab(player.transform);
}else{
Debug.Log("eeee");
}
picked=false;
}
}
the entirty of it
this is horrid to do in Update.
supplt=GameObject.FindGameObjectWithTag("supply").GetComponent<suppltscript>();
jfc
anyway doesn't seem like a gameobject was found with that tag
USE A PASTE SITE LIKE YOU WERE TOLD
also one player gets nullref, NPC don't.
I used debug.log for the else if statement
why would you put that line in Start and then update
this is big time #๐ปโcode-beginner question. You need some basic understanding on wat a null reference is and what it means
if line 23 is spitting error, the only thing it could be is GameObject.FindGameObjectWithTag("supply") not returning a gameobject, you can't GetComponent on a null object
there is absolutely no reason to even do this every frame..
or call that function.. if its a pickup, all is needed is grabbing that specific component on that specific object through the collider in the Physics trigger invoked
no I tried comment the line and the player can't be able to collect those supplies
Anyone know how to recreate something like this, where you collect and the money size grows. I am not making this type of game but kinda want the mechanic bc it is useful for somethings
because you're not grabbing the specific component on the specific collider you triggered
youre trying to literally grab the first object that has tag "supply" irrelevant to being the one you walked over
Basically pickup money and money pile in hands grows
I will do something basically like that except that it will be different objects the user holds
so how do I fix it?
just parent them ?
I told you how, you grab the specific component thorugh the trigger message parameter
you mean write the component into the trigger as a parameter?
public GameObject player;
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.TryGetComponent(out suppltscript supplt)){
supplt.pickup();
Debug.Log("collected");
}
else if(other.gameObject.TryGetComponent(out weapongrabscript weapongrab)){
weapongrab.grab(player.transform);
}
}```
thanks
everything else can literally be deleted
Thanks, although I know how props work. I just was wondering why in today's version of C# someone would not use auto property, but exposure make sense for me. I need a senior with like 15-20 years of xp in my life...
does anyone know how photon fusion made their script look like this in the unity editor? i want to make something similar to that for my own scripts.
it's a custom inspector. see the pins in #โ๏ธโeditor-extensions to learn how to make them
thanks!
So I wanna do localization, I have a custom script that will load the text onto the text box, but more importantly I'd like to know how can I reference global names in my locale text, like places in the game or character names, and when it comes to string tables, what's the best practice? Should I have one table for every story act in my game? Can I then still reference my characters from a global string table or something, it's all a bit new to me :3
hello, im having an issue with rotating my nav mesh agent to face a certain direction. the direction is set as the first corner of the agents next path, however sometimes it doesnt work it depends what orientation he is at the time, ive tried different types of rotating and ways of calculating the direction to face.
https://pastebin.com/s0Cs0Az2
this is what it should look like:
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
this is what it usually looks like:
float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float parsedVal);
I parse a val which is 0,5 using InvariantCulture, but it returns 0.
Any ideas what is wrong with the above?
Debug.Log would help
Also pretty sure invariant culture expects . as the decimal, not ,
it does indeed
Then which one expects , as decimal? I guess that I can just parse the string and replace , with .
lots of languages use a comma separator Spanish for one
I thought there is a generic one, but I will go with replacing , with . then.
Idk why I didn't think of that earlier lol
point is you should serialize using invarient culture then you can deserialize it using that as well
I am using Inky which returns a value based on my system settings and there is nothing I can do about that except fix it after I get the value.
problem with that is, what do you do when the users language is English?
you replace , with . and . with , then you have the same problem
val = val.Replace(",", ".");
This will replace only 1 way right?
I want the float to always use .
or rather the string which is parsed to float
then Invariant is fine
yes and say I have 1,000.00. you end up with 1.000.00 which wont parse
This returns 0 from "0,5" string
exactly
because 0,5 uses ,
you said you always want to use .
where is the string coming from
inky egine
is a player typing it in?
then that is what needs fixing
what part of inky engine is giving you a numerical string?
I cant fix it, its just going to be either , or . based on User system settings
Its hidde in source code, I don't know, but I can't fix it
do you have the source code
I'm trying to understand the context
I tried, I reported it to them, but it may or may not be fixed.
of why you're getting a numerical string in the first place
and in any case - if it's using user system settings then you could do the same
and parse without providing a culture
audiomusic:asset'music_prologue',loop'0',volume'0',volumeend'0,5',time'1000'
We use tags
volumeeend'0,5' would be volumeend'0.5' on different system
I get those tags from the engine at runtime
Let me parse without providing culture then
I assumed that Invariant is specifically for that purpose, but I got it wrong?
Float will never be 1,000.000 btw I dont know which float can have multiple separators, but we wouldnt have them
yes you did
You could just do something like
inputStr = inputStr.Replace(System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.CurrentDecimalSeparator, ".");``` then
all kinds of numerical and date/time data has culture related separators, you're only storing up trouble by not dealing with them correctly
I understand, but this is a relatively small game, we just need to be able to parse simple floats on various systems.
Tbh I never had to deal with that issue until recently when we started to parse strings to floats.
I will try this if float.Parse doesn't work(without invariant culture)
public static float GetParsedFloat(Dictionary<string, string> dict, string key, float defaultValue)
{
dict.TryGetValue(key, out string val);
if(val != null)
{
float.TryParse(val, out float parsedVal);
return parsedVal;
}
return defaultValue;
//return dict.TryGetValue(key, out string val) && float.TryParse(val, NumberStyles.Float, CultureInfo.InvariantCulture, out float parsedVal) ? parsedVal : defaultValue;
}
This works, left commented code for reference
Thanks! No idea why I got stuck with InvariantCulture for so long tho, I need to fix the rest of my code that is parsing floats ๐
hey! I'm currently working on this 2D point and click puzzle game and I was just curious how people handle scenes? I started by having a bunch of canvas and deactivating them and activating when need be however that didn't really feel right. So I started creating those canvas in the scene, and that works for one of the places in my game, and I know I can use the scene management library to just move the player between a new scene but I also have a lot of different data I would want to use so feels difficult if I had to do that each time a player wanted to go between two places. Just wanted to see if anyone could point me in a direction to get that figured out as I can't seem to put a label on it to research it good enough.
Not sure what exactly you are struggling with. Having a consistent gamestate throughout different scenes I guess?
if I've got an object with several child objects that each have their own colliders, and I want multiple of the children colliders to have their own OnTriggerEnter functions, do I need to give each of those children their own script, or can I somehow assign an OnTriggerEnter function to a collider that is not on the exact object the script is on?
any chance I could get some assistance on a rotation issue. I have a floating model that rotates at a fixed speed, but I have also applied a rigidbody to it where a user can spin the model with mouse input. I want it so that when torque is not being applied though, the object slowly returns to its default position and rotates as normal
you'd have to give them their own component
Blech. Alright.
Did you try anything related to this? It's not really clear what part you struggle with. This just sounds like having a desired position and rotation speed
Not sure what exactly you are struggling
Compute shader (FFTSpectrumViewer): Can't find kernel (0) variant with keywords: CHANNEL_BLUE CHANNEL_GREEN CHANNEL_RED. Does anyone know why I'm getting this error in the snipped code (FTTSpectrumViewer) provided in the hastebin. The error comes from the dispatch line on the computer shader
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yeah I basically have a pivot point as a parent object to a 3d model. using transform I have the pivot rotating over time which in turn viusally spins the model. The user can also use their mouse cursor to spin the object in any direction. My goal is to have a "reset" key which sets the pivot point (and in turn the model) back to its orginal position just in case the model gets all outta control. the problem is that to do the manual spin I have a rigidbody and then then constant spin is done by transform. I am confused as to how to reset both to their original position
maybe best if you have a moment if I dm you my code?
Would a question regarding ontrigger enter and triggers go to physics or here?
If it's related to code, possibly here. If it's related to the Editor, inspector or physics engine.. probably there.
No idea what it's related too or whats causing the problem so that's a problem..
With Transform, it seemed like you were able to go through the door and with the CC you were not.
The main difference would be that moving the Transform does teleporting whereas CC does not.
Maybe something is blocking you from going into the door?
It's rather difficult to tell what's happening from the video.
Without the TriggerObject im able to walk throught it just fine, so therefore i have no idea what's causing the issue. Been sitting on it for the past 30 mins and havent figured anything out
Show the inspector for the trigger object
Above the MeshRenderer is just an ProBuilder MeshFilter
Show the inspector for the Character
I don't believe you should use CC and rigid body together like this. Consider using one or the other only?
for ontriggerenter dont you need both cc and rigid body?
You'd only need a Rigid body and a collider.
The problem is i cannot use an collider in the Player as it messed up the whole FPSController and makes the player bug out of the game and fly away three times the speed of the light, so that's why i use an RigidBody instead of an collider
CC has its own physics system
Would it be possible to only use CC, as it "technically" is an collider isn't it?
Sure, remove the Rigid body component and implement your collision event using CC's callback method
Firstly thanks, i never even knew an Method like that existed, Secondly still doesnt work :,)) Pretty sure it's something up with the CC itself
Instead of describing your code, just post it so people can see and help. Though you shouldnt also combine rb and transform movement like this.
i'm new to coding and unity and i'm just trying to get familiar with the syntax. in my project, i have GameObjects with colliders and one with a RigidBody2D but OnCollissionEnter2D doesn't detect any collisions
doesn't work
no no .. did you read the signature carefully
also look at my screenshot, my IDE tells me whats wrong pertaining to unity
i feel very stupid
my problem was that i spelled it "collission" and not "collision"
well actually now that you pointed out thats probably why you didn't get that message
I'm blind ig. ๐
but that would still not solve your issue but your IDE should now tell you why its wrong
you changed the type as well?
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
Debug.Log("Touched ground.");
}
}```
good good
I'm getting the same result every time from this
am I missing something?
I don't mean the same sequence, I mean literally the same result: 2, 2, 2, 2, 2, etc.
#๐ปโcode-beginner but an int variable can only hold one number at a time. Every time you assign a new random number to it, it overwrites the previous one
yes, and I am stepping through each line
this was just for debugging purposes, and the result is 2 repeatedly
the range is 0, 4
so I don't see why it is not behaving like I would expect
Have you tried printing the values in between
hm, so I just gave that a shot and it changes the random value now, but without the Debug.Log statement the result is always the same
Random.Range has no side effects so it might optimize the repeat calls away if you don't do anything with the value
actually it does advance the rng generator so who knows, maybe debugger issue?
it would affect the rng
yeah
i assume theres something else going on, where do you see this repeated value of 2? because the debug.log changes absolutely nothing
I think it's actually just a coincidence..
I tried difference seeds and increased the resolution, and the behavior is what I expect
if you're manually setting the seed, then the same seed will give you the same result
yes, that part makes sense
but I didn't expect the sequence to be 2,2,2,2,2,2 by chance I guess
it's working though, thanks for the sanity check
it is actually random chance, I can't believe it
there's like 8 islands that all got the same random number
HI, guys. How can i avoid triggering OnTriggerExit() if i am still touching the same object that is close by?
Don't exit the trigger? You'll need to provide more context if you're somehow triggering the event whilst it shouldn't.
there are wall objects that a followong each other. I want to trigger change hand animation to avoid wall clipping when i am touching a wall. So, when i don`t touch, the animation is set to normal. So when i run near walls, ontriggerexit is being called as i stopped touching the first wall. bit i am still touching the second..
Some ideas is using some flag when you are touching the wall which is checked every frame. Maybe something like OnTriggerStay() instead, so perhaps a statemachine is probably how I would do it.
Hi guys, my game switches between two different input modes, but this detection always says that there's a mouse device, I'm confused why...
InputType input = InputSystem.devices.Any((InputDevice device)=>device is Mouse) ? InputType.Mouse : InputType.Touchscreen
Does WebGL by default always provide both?
Do you have a mouse plugged in when your testing this?
On my mobile? No
I'm testing the WebGL build
The devices property would simply return an array of the connected devices.
I have a hunch that it's an issue that only occurs on WebGL builds
I'd be curious to see what devices it thinks are connected 
