#archived-code-general
1 messages Β· Page 281 of 1
oh
You could also just do... GetKey...
getkey how?
No up or down
But yeah, GetAxis is preferable
Exactly the same, just without the word down
Yeah
and how does that change it?
GetKey checks for every frame the input is true
GetKeyDown only checks for the first frame the input is true
Start with configuring your !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
β’ Other/None
i think a better word is "unfamiliar". you're learning broski
vsc is fast but π© but vs is great but slow π€¦π½ββοΈ
Why is it shit?
Both can be configured
I have this weird bug where if I overwrite the code during in game, dictionaries can no longer be found, they are in void start(), and could only be found or referenced if i start the game again
i have the unity extension i have the sdks and its still shit
probably because is local
show code
It doesnt seem to be configured correctly though
Is it set in your external tools menu?
Your error is not showing underlined
ah it is too long here
!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.

Sometimes clicking regenerate project files helps π€·ββοΈ
It can have issues on some systems. I wouldn't say that makes it shit though
when i overwrite the script, they lose reference to dictionary
oh looks fine here, so what do you mean exactly you cannot find anymore
it is like, when i start the game and when i click the car, it can flip, but when i overwrite anything in script, it will show that 1 (itemType) cant be seen in dictionary, but works again if i click start
it is very weird 
the reference wont automatically be null unless the garbage collector has bugs
this is key not found exception
Are you editing the code at runtime?
Do you have assembly reload and stuff disabled?
hmhm, is ok? or no
It's ok, but that would explain the code breaking.
is this perhaps... a skill issue? (that's a joke i just thought it was funny)
Hot reload and similar features have their limitstions
Static and non serializable variables (like dictionaries) reset to default when you reload scripts
would the bug happens also if game reloads (like changing levels)? or only happens when changing the script?
or does void start() mean the game or exe starts?
Start is after the object was created
im trying to replicate a similar scenario where scripts would do the same when it was edited in unity but in game, or it wont happen?
Actually, I'm not sure if hot reload is a thing by default. Disabling domain reload shouldn't allow you to edit the script at runtime and make use of the changes.
As far as I know, it should not really happen outside of script reloading
Can you explain what exactly you're doing? Maybe record a video.
With 'it' I mean domain reload
i dont know how to record, hope this is ok 
unity reloads script when saving also
it is like dictionary becomes empty when it is reloading
but when i run the game again, it functions normally
It should stop play mode on reloading script also.
hmm, it continues it for some reason, I use it sometimes to check if script is ok also
So what you're sayin is that the dictionary is empty when outside play mode?
dictionary becomes empty when it reloads script in play mode
not sure if it becomes empty or it cant find it
but works ok if i reload the game
I'd assume that it reloads the domain or something similar. It normally would exit play mode as that messes up a lot of stuff.
ah okok, but it is a scary bug, should i be worried of it happening in the game (without unity editing)?
You can't edit code in the build, so it's only relevant to the editor. Not to mention that it's not a normal workflow.
I feel like you have some kind of plugin or asset that allows it
Because it shouldn't allow you to stay in play mode on script reload normally
not sure how, i havent touched unity settings, but is useful sometimes 
but also, it shouldnt happen i think
thank you everyone 
It's a setting you can toggle. It's off by default nowadays I think but used to be on by default.
I suggest you turn it off because it causes more trouble than it helps
That shouldn't cause any changes on script edit though
It does, if it's set on "Recompile And Continue Playing"
yeah but it's not very good at it so it causes issues like this
Hmm? I reload scripts while playing all the time
Yeah, I didn't know that was an option. Only knew about domain and scene reload options.
I fixed the code 
instead of .rotate, because it adds it, i dont like it adding, I used interactable.transform.localRotation = Quaternion.Euler(rotationValue);
so it stays like how it should be
im tryign to implement an undo function to a blockpush puzzle game, any guides?
Save your game state in a LIFO collection (Stack)
I presume you have a grid array which contains the current state of play
i dont think so
im pretty new so i just follwed a tutorial for the bascis
Link to source code: https://patreon.com/GameAssetWorld
I will show you how to make a Unity Grid Based Movement, where you can move 1 tile at a time + push a box. Just like Sokoban.
3D models and Sprites used for my Videos, can be found on my page.
Support me on Patreon: https://www.patreon.com/GameAssetWorld
β Subscribe: https://www.youtub...
this is what i followed
ok so that is the first thing you need to implement.
So you need an array which contains the state of each point in the grid
why is hit 2 not being triggered?
so i would have like a big 2d array that contaions each object?
im also not sure how to differentiate between the different boxes
basically, yes. say you have a 3 x 3 grid and each point can contain a game object then you would have
GameObject[] grid = new GameObject[3,3]
GameObject[,] grid = new GameObject[3,3]
But maybe use a jagged array instead: https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1814
Depends on use case but it's explained in the link
What do you mean? The example shows how to initialize the array
is htere like an article on this so i dont have to like consntatly come back to ask
The whole point is an undo feature, right? Or is this about the video?
And you want to undo the last change in position? The position is an XY value?
yes
Then first read on this: https://learn.microsoft.com/en-us/dotnet/api/system.collections.stack?view=net-8.0
You can use a Stack containing Vector2 values, and each change in position is added to the stack
sounds like he first needs to learn about using Arrays
A stack is a LIFO collection, which means the last value that goes in is also the first to come out
Oh, I assumed that this is known considering the channel
I think not based on his earlier question
Does hit 1 trigger?
so the idea is to have a stack with all the different vectors?
Your code is weird. Are you aware the debug statement is triggered when the if-statement above is matched?
Yes, and a stack is perfect for an undo feature because the last added value is the last position change in this case
But if arrays are new for you you should really learn about these, and collection types in general
but if i have like more than one object that moved on each turn then would i have a stack of arrays or something
for hte previous one iwas just confuseda s why a gameobjec can take a [3, 3]
exactly
it does
do i still need to do like the save scene or the grid thing u said earlier
if i can just do this
that is an Array definition
but the gameobject is not an array right
Please properly share the relevant !code so I don't have to try and retype whatever you wrote
π 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.
It is an Array containing GameObjects
oh so the type in the array is gameobjects and each square is either an object or empty
ok
yes
Scene? Each Turn
yeah like the posiiton of everything each turn
yes so you have
GameObject[,] turn = GameObject[3,3];
and
Stack<GameObject[,]> turns = new Stack<GameObject[,]>;
so you can have one array per turn and add the turns to the Stack
when you read the Stack you get the previous turn array back
void OnClick() {
drawweapon();
audiomanager.Instance.playsfxrandom(0, 4);
lastclickedtime = Time.time;
noofclicks ++;
if (noofclicks == 1){
_playeranimator.SetTrigger("hit 1");
}
noofclicks = Mathf.Clamp(noofclicks,0,2);
if(noofclicks>=2 && _playeranimator.GetCurrentAnimatorStateInfo(0).normalizedTime > 0.7f && _playeranimator.GetCurrentAnimatorStateInfo(0).IsName("hit 1"))
_playeranimator.SetTrigger("hit 2");
}
void Update()
{
if (_playeranimator.GetCurrentAnimatorStateInfo(0).normalizedTime > 0.7f && _playeranimator.GetCurrentAnimatorStateInfo(0).IsName("hit 2"))
{
noofclicks = 0;
}
if(Time.time - lastclickedtime >maxcombodelay)
{
noofclicks = 0;
sheathweapon();
}
if(Time.time >nextfiretime)
{
if(Input.GetMouseButtonDown(0))
{
OnClick();
}
}
}
So now log all the variables in that if-statement. noofclicks, normalizedTime and whatever GetCurrentAnimatorStateInfo(0) returns for the name.
the nail is cliping π
Please use the proper channel #πβfind-a-channel
as my zombie and my bullet have the same speed component and locaTransform . how can i select specific one of them in job ?
public void Execute(ref LocalTransform localTransform, in MovementSpeed movementSpeed, in BulletEntity bulletEntity)
this is my method
do u have better way ?
why cant i add packages from git url?
Is that the complete error?
yes
Your link is incorrect for how their project is uploaded
Their installation steps also contain the proper link.
- What's the matrix4x4 size in bytes?
sizeof(float)*16?
Hey @wicked river , we've released Muse Behavior 0.5.10, can you let me know if that helps some of the issues you had? Still happy for you to DM if needed π
Also there is now a Muse-Behavior tag for questions in the #1202574086115557446 channel π (although I'll admit I keep more of an eye on the discussion pages as I mostly use Discord for personal stuff)
i have a platformer with moving blocks. my issue is that blocks can very easily move to slightly offset positions (eg 1.02), so my player and other things that move get caught on weird overhangs on colliders that are not really visible.
Any suggestions on a good approach to address this?
I have 3 types of items which I wanna spawn, they have circle colliders and box colliders. Now I want a system to be developed such that no item should spawn very close to each other or touch each other (or appear on top of each other). The system should be aware of all items instantiating and be responsible to have a distance between every item respective of each item's size. How do I approach this?
do not cross post
Thank you very much. I will give it a crack and let you know where I get stuck.
Use physics queries (Physics.CheckBox/CheckSphere/OverlapBox/OverlapSphere etc)
did that, didnt work out
can i share my set of code here
if you want help with it, that would be prudent yes
{
Vector2 spawnPosition = new Vector2(xPosition, yPosition);
// Get the collider size of the item
Collider2D itemCollider = itemPrefab.GetComponent<Collider2D>();
// Check if there's any coin too close to the spawn position
Collider2D[] colliders = Physics2D.OverlapCircleAll(spawnPosition, itemCollider.bounds.extents.magnitude + minDistanceBetweenCoins);
Collider2D[] boxColliders = Physics2D.OverlapBoxAll(spawnPosition, itemCollider.bounds.extents * 2, 0f);
if (colliders.Length == 0 && boxColliders.Length == 0)
{
Instantiate(coinPrefab, spawnPosition, Quaternion.identity);
}
else
{
// If too close and attempts remaining, adjust the position and try again
if (maxAttempts > 0)
{
AvoidCloseSpawn(itemPrefab, xPosition,Random.Range(-5f, 5f), maxAttempts - 1);
}
else
{
// Max attempts reached, do something else or log a message
Debug.LogWarning("Max attempts reached. Unable to find a suitable position for coin spawn.");
}
}
}
so i tried this
but the items never follow this logic
they sometimes spawn on top of each other as well, or very close to each other
basically im making a 2D endless runner game
- Why are you using bounds.extents for the size of the queries instead of the actual collider size?
- Why are you doing both OverlapCircle and OverlapBox (and then ignoring the results of the box one?)
- every collider will be of different sizes as many items are instantiating
- I have 2 types of colliders being used
I would do something like this:
- if the prefab has a circle collider, do an OverlapCircle with the radius of the circle collider
- else if the prefab has a box collider, do an OverlapBox with the height and width of the box collider
your code doesn't reflect the reality of your prefabs
is this the only thing i gotta change?
well there's also the presumption here that your colliders match the visuals of these objects
yes they do
you also need to incorporate the offsets/centers of the colliders if such exist
what about the polygon colliders
TBH I would probably give the prefabs a separate collider just for placement purposes that is simple
either a box or circle
oh
and rather than using GameObject, I would make sure there's a script on all these things like PlaceableItem and it should have a public property like PlacementCollider which directly references the placement collider
that way this script doesn't have to do anything like dig around in the prefab for colliders and guess which one is which
how would that work out
what do you mean by that
What part are you confused about
that's what our whole discussion has been about so far
didnt get this one too
excuse me for being a little silly but can u explain that a bit more
I'm just saying all your items should have a script on the root of the prefabs
like
public class PlaceableItem : MonoBehaviour {
[field: SerializeField] public Collider2D PlacementCollider { get; private set; } // assign in inspector
}```
And then this code you shared above can say like:
```cs
void AvoidCloseSpawn(PlaceableItem itemPrefab, float xPosition, float yPosition, int maxAttempts = 5)
if (itemPrefab.PlacementCollider is BoxCollider bc) {
// do an overlapBox
}
else if (itemPrefab.PlacementCollider is CircleCollider cc) {
// do an overlapCircle
}```
would this code automatically do this for all the instances that get randomly instantiated
You would be calling this to decide whether the spot is ok to instantiate
so every prefab would have PlaceableItem script, so when I reference it, what instance of the script it would refer, like to which item's script
because there are total 3 prefabs
every prefab has its own spawning script
it would refer to the instance it's referring to....
why? Seems like you could just reuse the same one for all
yeah
im making one script that works in the hierarchy
that manages all 3 prefabs
but the thing is i want to have 3 different spawn logics for all of them
for coins, they do spawn more
for cars, they do but frequently less
for pickups, they will have a lot of if else conditions to decide when shall a pickup item should spawn
ok but the concern currently is the placement logic
so... it refers to whichever you refer to
decides where to spawn an item if its gonna collide with other item
you know you make a reference like
public PlaceableItem[] placeableItems;``` and drag and drop them in the inspector for example
shouldnt i make one instance of this script and put it inside the same gameObject in the hierarchy which has the other 3 spawning scripts. And this script should have all the colliders of all prefabs. then other 3 scripts can refer to this same instance
I don't see why that makes more sense than putting it on the prefab. it represents a placeable item and has information about itself
i want this script to automatically get all the colliders and their size as well, because cars will have different sizes right, colliders will have different sizes, so this script will have their collider size, and then other scripts can refer to these sizes maybe
yeah agreed
Could I request advice on this sort of problem again? I expect slightly offset objects are a common occurrence/issue, and Iβd like to know how other people approach it.
Since I have a custom physics engine, I have the luxury of being able to insert corrections or special cases into any part of the process.
Is it maybe better to add conditional movement to try to grid-align specific objects?
Or maybe a special case for things to not get stuck on tiny ledges? Both?
Anyone have recommended reading material (preferably with practical examples) of creating a flexible weapon system? I want to be able to create weapons that can have additional effects (damage buffs, visuals, sounds, etc).
I've used Scriptable Objects for simple use, and I get how I can use it to manage number values for the weapon. I'm scratching my head though when it comes to additional visual effects since I don't think Scriptable Objects really deal with that.
composition
minimal abstraction, keep the majority of the behavioral logic at the base
Have the SOs refer to prefabs for the extra effects
Hi @everyone hope everyone would be fine!
I am facing some errors in my unity project when I am using addressable bundle.
I am sharing the errors if someone known related them then please let me know.
Thanks in advance
Here is Errors:
Unable to open archive file: Library/com.unity.addressables/aa/Android/Android/ed3c0a8dae69eb5def6b163b48e1f784_unitybuiltinshaders_902d97b8e1277922e9f46a7a3fa469a4.bundle
RemoteProviderException : Invalid path in AssetBundleProvider: 'Library/com.unity.addressables/aa/Android/Android/ed3c0a8dae69eb5def6b163b48e1f784_unitybuiltinshaders_902d97b8e1277922e9f46a7a3fa469a4.bundle'.
UnityEngine.AsyncOperation:InvokeCompletionEvent ()
OperationException : GroupOperation failed because one of its dependencies failed
RemoteProviderException : Invalid path in AssetBundleProvider: 'Library/com.unity.addressables/aa/Android/Android/ed3c0a8dae69eb5def6b163b48e1f784_unitybuiltinshaders_902d97b8e1277922e9f46a7a3fa469a4.bundle'.
System.Exception: Dependency Exception ---> UnityEngine.ResourceManagement.Exceptions.OperationException: GroupOperation failed because one of its dependencies failed ---> UnityEngine.ResourceManagement.Exceptions.RemoteProviderException: RemoteProviderException : Invalid path in AssetBundleProvider: 'Library/com.unity.addressables/aa/Android/Android/ed3c0a8dae69eb5def6b163b48e1f784_unitybuiltinshaders_902d97b8e1277922e9f46a7a3fa469a4.bundle'.
don't crosspost.
Also everyone tag does not work, why do you feel the need is necessary to tag everyone in a server for your personal problem lol
https://hastebin.com/share/saxaposada.kotlin
Some ideas to get started
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I am sorry for my that behavior but i am finding solution of that error past 15 to 20 days but i cannot find it here is my last hope to find out.
pathing issues, Im not sure how to solve it. I haven't fully used asset bundles yet
1000 times i can check path and match with other all ok but cannot find out where the problem.
are you ever resetting velocity to 0?
Creating a flexible weapon system
Trying to make a jet like player movement for the 2D game I am making and am hoping for some guidence. Currently I made a system that will steadly decrease the velocity after its provided some with the press of the W key, but its very laggy, looking less like it is slowing down, and more like its teleporting each step.
Here is the code:
public class V1PlayerMovement : MonoBehaviour
{
public Rigidbody2D rigidbody;
public int ForwardThrustSpeed = 10;
public int ReverseThrustSpeed = 10;
public int LeftThrustSpeed = 5;
public int RightThrustSpeed = 5;
public float decelerationFactor = 0.99f;
private void Update()
{
//Vector2 currentVelocity = rigidbody.velocity;
//currentVelocity *= decelerationFactor;
//rigidbody.velocity = currentVelocity;
Debug.Log("Current Velocity: " + rigidbody.velocity);
}
public void ForwardThrust()
{
rigidbody.velocity = Vector2.up * ForwardThrustSpeed;
Debug.Log("Providing forward Thrust");
}
}```
do you have a camera follow maybe its that?
also try turning on Interpolation on the rigidbody
This is what it looks like. No camera follow yet.
Interpolation smoothed it a bit. That may help
where are you calling the movement
ForwardThrust
Using Input system.
so here under my player object
Its a Onpress event
*No idea how to handle holds yet
You configure that inside the action map iirc
i think Zane meant actions that you hold down for a while
like movement
you wouldn't use the "Hold" interaction for that. The Hold interaction is used for an action that fires after you hold the button down for long enough
PlayerInput will run your method each time that the action value changes.
what method are you actually calling, though? it has to take an InputAction.CallbackContext
and ForwardThrust doesn't
I co figured it through the events dropdown, so I made one under my player action map within that dropdown and added the Forward Thrust function to it. Not quite sure about the Input Action method as the guide I followed didn't mention it
Ohh I only learned the way I've seen done on Unity FPS demo, so for held button I do as follows : I set Action type to Value instead of Button then use bools like so
Since i use Send Messages mode btw.
public bool Fire;
public void OnFire(InputValue val)
{
Fire = val.isPressed;
}```
Ah, okay, that makes sense.
Do you want to constantly set the velocity as long as the button is held?
Yeah, though soon I want it to have a form of acceloration going up to the velocity aswell. Cureently it jumps right up to that speed
Can anyone link me a code snippet of placing buildings on a plane (free placement) with preview, I feel like that's probably something really common but not quite sure how to search for it.
Edit: Found this!
https://github.com/MinaPecheux/unity-tutorials/tree/main/Assets/07-BuildingPlacement
What is a good name for an interface for a Monobehaviour that needs to have a method invoked when the collider on its gameobject changes size, shape, scale, or a totally different collider is assigned?
IShapeDependent?
IShapeWatcher
IHasDynamicCollider
Is there any way to make like an If(RigidBody2D has been hit with a force higher than <number> with the floor) (That's what i want to do) but i dont knwo how it's called
or optionally, ICanHazDynamicCollider
https://docs.unity3d.com/ScriptReference/Collision.html has a bunch of data on it, try relativeVelocity
i like IShapeWatcher
I don't feel like it tells me anything...why is it watching the shape?
it sounds like what you really need to do is distinguish between things whose colliders will not change and things whose colliders will change
this doesnβt make sense, because it will go onto monobehaviours on objects that have colliders that do not change
oh, why?
it is just a monobehaviour that needs to be notified when the shape is different
well sounds like i'm not understanding, carry on
so when exporting to WebGL, none of my videos work.
google tells me i need them in a folder called "StreamingAssets".
for some reason, whenever i put a video file into that folder, its immediately corrupted. putting video files elsewhere in my project works out fine.
im on linux and i know it comes with some weird things with unity's video support so it might be important.
webGL doesn't support reading from files, so you'll need to download the file using a WWW request
so have a link instead of a file on the videoplayer component?
also these are the errors that it gives me with the corruption stuff
I'm not familiar with the component (VideoClipImporter) but you'll probably need to write the code yourself to get the byte stream and send it to that component
Would it work on Rigidbody2D?
im using the VideoPlayer component
If the app were a windows app you could just drop it in /StreamingAssets and read it in code - but IO operations aren't allowed in WebGL
heres a video showing the weird thing with the folder incase this provides more information (ignore the goofy pics of my mate, i was using them as placeholder assets)
I'm not familiar with this component but it looks like you should just be able to drop those clips in your /Assets somewhere, link them to the component, and do myVideoPlayer.Play()
im aware of that
they play in the editor
but in WebGL they juts do nothing
some youtube video said i just need them in the StreamingAssets folder but thats being weird and glitchy as i have shown
Don't put things in StreamingAssets - the video clips are imported by unity (I imagine) and compressed into a format that it can use.. but in StreamingAssets - it's a special folder that says to unity "no touchy" and it won't import them (or do anything with them at all)
ok that explains the corruption
well "some youtube video" is probably not a great source π but if that's what the youtube video is telling you, it's probably also saying that you'll be needing to read in the content of the clip via code
for him the videos just import normally with no corruption
it's not really corruption, per se.. it's more that it's not importing the clip in a format unity can use in that folder
so i figured i had something very wrong
on the linux version of unity you can exclusively only use WebM videos in a very specific codec etc, so idk if there would be a supported different version for this one folder
So you'll need to read up on VideoClipImporter and do it that way
And it even looks like the docs say specifically that you need to use video clips via URL in webGL:
So yeah, you'll have to upload your video clips as separate files from the game, and get the content via a URL.. so look for tutorials on that (how to download a file with C#, how to use a webrequest in unity, etc)
maybe? I don't know that component but.. read the docs, follow the instructions, try it out and see :p
upload your video clip somewhere, make sure it works (something like www.idoblenderstuffs.com/coolvideo.mp4), copy and paste the url into the URL field (or set it via script) and try
for some reason the "browse" button for the url is a file explorer thing
ill just upload the video somewhere and use that
as you suggested
jesus christ ive only got half an hour to sumbit this these videos better bloody upload : ))))
hi i keep getting weird false warning " variable is assigned but its value is never used" it's actually being used, if i remove the variable i get an error right away
turns out it was somehow too big for github pages so im having to export as windows instead of for web or else ill just lose my mind
That means you're doing something like this
int x = 1;
x = 2;
that's the most likely scenario, at least
Even if you assign to the variable again later, you never actually use it
Share codeπ€·ββοΈ
[SerializeField] private GameObject gate2;
how do I make this variable nullable, meaning it wont always be assigned.
GameObject? game2; ?
It is already. GameObject is a reference type and reference types are nullable by definition.
I wanted to not show on the console the errors, do I just ignore it?
No, you handle the errors
It being nullable, doesn't mean you can ignore errors
Make null checks before accessing the variable
i think that is exactly what i did yest thank you β€οΈ π
does anybody else procrastinate on the game design side by cleaning up your code?
burned by copilot
cleaning up code is more of a chore
when i have to go and implement a new system, i find it easier to do a little sweeping up than expending the mental effort implementing the system
I know the limit for vertices in a mesh is 2^16... is there a limit to the number of triangles in that mesh?
Hi, I'm currently using a for loop to add sway to multiple child Transforms using this code:
{
float mouseX = input.LookInput().x * (inverse ? swayMultiplier : -swayMultiplier);
float mouseY = input.LookInput().y * (inverse ? swayMultiplier : -swayMultiplier);
Vector3 targetRotation = new Vector3(mouseY, mouseX, 0f);
// For some reason, this stops working after switching weapons
for (int i = 0; i < targetTransforms.Length; i++)
{
targetTransforms[i].localRotation = Quaternion.Slerp(targetTransforms[i].localRotation, Quaternion.Euler(targetRotation), smooth * Time.deltaTime);
}
}
Only one of the targetTransforms is active at a time, but I've noticed that sometimes its rotation will just stay completely at 0,0,0. This is just running in Update with nothing else on the script. Any ideas?
I'd bet on the incorrect slerping.
What's the smooth value?
8f
The interesting thing though is that despite the other targetTransforms being inactive, their rotations still get adjusted (which I would expect from the for loop), but the currently active transform doesn't. Weird
I can "fix" it by adding the script to each individual transform, but that seems needless
EDIT: This has been fixed by setting the Animator component on the targetTransforms as "Root Motion". Not sure why that fixed it since I don't use any root motion on the transforms but whatever...
Hi! So I've been trying to make a backup of my project. I have had no problems making or opening a backup before. However, recently after switching to Unity's newer input system. I have been getting errors when opening backups in regards to Unity's input system. My normal project is fine, this only shows up when I try to open my project backup and it opens in safe mode with these errors. It leads me to believe that something is wrong with the PlayerInput. Does anyone know the solution to this problem?
How are you making backups?
Copying and pasting the Assets and Project Settings folder
well that explains it. You're not backing up the Packages folder
Ahhh I see okay thank you!
I'd suggest using Git to version-control your project
It's a lot simpler (and more space-efficient) than just copying entire folders around
Sounds good! I'll look into Git!
mightve found two problems , whenever i grapple forward then change my direction backward and grapple then , sometimes the player wont jump to the position but backwards , and the second problem at the end seems like the rope doesnt get destroyed after grappling , its not there visually but it still makes the player not go anywhere , only within the grapples maxDistance radius , im not sure how to fix it
https://paste.ofcode.org/bBKd3hu2WUCuMZaUrjs8FW , grappling hook script
you may have to clarify more, like where these issues are in the video because its really hard to see whats wrong. Im assuming the first issue is due to just physics, the player has velocity in one direction and then the sprint joint is not strong enough to immediately force them in the grappling direction.
Did you get this code from somewhere? it looks like standard youtube hardcode mixed with AI comments
Yeah I combined Dani's grappling hook with Dave's grappling hook to make a grappling hook with two modes , the modes work but just those two problems appeared and I'm not sure how to solve them ngl. I can send you anything you need. And also you meant spring joint?
Also you mentioned one of the issues , the player if he grapples forward then changes direction backwards and then grapples , sometimes the player doesn't grapple to the direction or it sends the player back. The second issue is the rope seems to still be there even tho it's not there. Like it doesn't let me move after I hit the grapplers maximum distance radius so I can only walk in that radius
Not really sure how I can explain it better. But I hope you understand somehow
yea meant spring joint. I havent seen Dani's content but dave's has always been just duck tape and glue while putting on a brackeys impression. Probably better off to not use his stuff and just create your own.
The first issue to me still just sounds like physics as i initially described, where the players existing velocity messes with the joints attempt to bring it closer. If you want it to feel snappy, then maybe set the players velocity to 0 before creating the joint.
The 2nd issue sounds like you could really use a state machine here, or at least something similar rather than all the code being just mixed and matched.
Also here's more example of the second issue
I already use a state machine for currentModes if that's what you mean and use it to yk be able to determine the currentMode of the grappler
Everything about the grappler is in the script I sent here
Hopefully setting the players velocity before creating the joint fixes the first issue lol
And I didn't know Dave's code was that bad π
I was doing the movement based on his code
Im cooked 
thats not really a state machine, everything is just together, there are no states. A lot of logic exists just by itself, it just so happens to check an enum as well
His code really just works for the purpose of the video. When you want to experiment around more or even add features, you'll notice bugs or things just dont work nicely
No wonder I got these bugs and the grappling hook normal mode doesn't feel that nice , should I remake the whole player movement scripts and not use Dave's code or just let it be?
I based it around Dave's movementstate for the player movement script to check if the player Spriting , crouching etc
That's entirely up to you. If it works for the purpose of your game then keep it
I mean it works fine for my game since it's just really white blood cell killing viruses/bacteria ultrakill/doom style so it works nicely imo
My game supposed to be fast paced so it works nicely
how can i move even tho allowmovement is false?
Do you have allowmovement in the move player?
Moveplayer()
Check what the value is set to in inspector
Verify that it's false
https://youtu.be/qsIiFsddGV4?si=Xoa9DuXXQsoqQ1bN , is this what you mean?
Take your programming skills to the next level and learn how to build a better state machine in this brand new tutorial and break down!
This tutorial explains how we can create a reusable state machine in C# by implement abstract classes and generics! It also breaks down core pieces of any state machine with helpful visuals and explanations.
...
havent seen the entire vidfeo but from a quick glance, yea thats a state machine. You dont need anything too complex but just a way of saying what a state is and what it can do.
Oooh alright , I will explore more of state machine vids to see how they are done and etc
So I recently added an action buffer system to my game. But I have been running into some problems with it when I playtest it versus when I build it. I have a feeling that it has to do with the way I made my system so I was actually wondering if anyone had any resources or tutorials for a good action buffer system. I can't seem to find one the fits my game.
How can we help you find a system which fits your game if you didn't tell us anything about your game? What are your requirements? What roadblocks have you hit in the ones you've tried?
unity keeps freezing on reloading domain π
Break with a debugger during the freeze and see what the main thread is doing
GetComponent<T>() is not working in Start()
after running a few tests, it turns out GameObject.Find() is working just fine, but grabbing the script component seems to go wrong
ignore the weird objectC stuff, it works the same
I have no idea what's going wrong...
i feel like i'm missing something big
also, the code used to work, but some magic caused it to fail. I still haven't restarted Unity to test if something went wrong there
For one that's not GetComponent<T>(), that's GetComponent(string type)
and elaborate what "not working" means
oh, that's a different class, it just looks different
the string finds the object, it works th esame
what?
in essence, the moment I get the component, it returns null
so I'm stuck with a null reference
this is the objectC jargon
im gonna remove it someday, it used to be my idea of splendid code
caching all my objects and connecting them to a string dictionary
ok but does it work with the standard GetComponent? If it does, the problem is with the cache manager
unfortunately, nope
so can you be sure that the object returned by that is still valid etc? if you're caching the reference maybe it's old, the wrong object, etc
that was part of the tests i ran before coming here
GameObject.Find("GameUI").gameObject.GetComponent<GameUI>(); returned null, yep
Then you'll have to show the inspector of the object and the code you used
i still havent restarted Unity, this might be some silly error
if that was the problem, sorry for wasting your time
what you're doing looks suspiciously like an extremely brittle and confusing singleton that is already punishing you before it's even out of the cradle
strangle it now before it's too late and infects everything
attach the debugger and have a look at the object returned by GameObject.Find("GameUI"), you can see which components it has there in case it's different at runtime for some reason
or put in logs, whatever floats your boat
going for this
That's not going to give you any useful information
do you have two objects with that name?
nope, UI is UI
in fact
it's returning that little UI object
for some reason
this is just conjecture, but see how the parent Game connects to the child UI? there's no way...
well, none of your objects are named GameUI π€
it's below Cursor
oh, right
I'm going to try seeing what changing UI's name does
From this issue, I got the following: If you have a parent named Bob, and a child named Sally, doing GameObject.Find("BobSally") actually gives you Sally, according to this issue
this shouldn't work, but it does
yeah, by the docs you should have to write "Bob/Sally"
anyone know why?
every other animation works fine even idle injured works fine
only when the injured walk is played
ive tried replacing it with every animation but every animation does it in the "injured" state
except idle
well i can't repro it here, but maybe it's worth reporting a bug
that'd be great, oh also I'm not using the latest Unity version, so it might've been dealt with in later versions
Hello I am working on a resolution setting for my game.
This line of code is obsolete:
currentRefreshRate = Screen.currentResolution.refreshRate;
But while reading the documentation, I can't seem to find how do this part. Does anyone how to get the current refreshrate?
what's the actual problem? are you expecting this Unarmed-Crouch-Walk-Forward-Right event to do something?
What about it is obsolete? currentResolution or refreshRate
Can't find a deprecation notice for either one
Deprecation notices have a proper alternative explained 99% of the time. Does this not have one?
is it possible to change whether it's the cursor or some other object that collides with a Button? without using colliders*
I have a custom cursor that does funny things, such as changing size a bit when clicked (an animation), and being able to change sensitivity in-game
Unfortunately, it doesn't align with the system cursor, and as a result the button picks up the cursor information of a hidden cursor different from that which the player sees
I was hoping I could trick unity's Buttons to look at the custom cursor instead of the system cursor, without having to rely on colliders
unity screen resolutions now use ratios for the refresh rate: https://docs.unity3d.com/2023.3/Documentation/ScriptReference/Resolution.html
Sorry just any basic buffer system. My current one is a little weird. The gist of it is I have a queue and coroutines for blocking an action. For example, playerController.StartDashLockCoroutine. This method would be called in other scripts usually in the logic for another action. For example, I put it in my MeleeAttack logic and it's telling how soon the player can dash after attacking. It honestly works fine in the playtest, but the roadblock I have is that the time does not match up in a build, which leads me to believe that it is due to the logic behind the execution of the buffered actions in the update method. I kinda just thought of this method of action buffer just because I didn't really find that many tutorials or resources.
Update and the coroutines are located in my playerController, which acts as a state/action manager
You should ping him, not me π
well, you asked π
You could try locking the system cursor to the center of the screen, or extend thee button class and handle mouse events like hover, click etc yourself, or you could maybe try using boxcasts in replacement of colliders, though even with a collider or cast im not sure if that would help, unless your virtual mouse has physics on it
Is anyone the inbuild Localization package? Is it worth using?
@native prawn
I got it to work in another way, forgot to tell you that my bad
does anyone know how to refresh TMP_Dropdown options list dynamically? im making a search filter and cannot for the life of me figure it out
I know that
I need to update the list (and for it to actually show in the dropdown) based on the text in an input field
you can create options and add it to the list
How can i do curve based procedural recoil system? have any tutorial for this?
You could have a few animation curves that you either choose randomly or blend rendomly
What I do is I have a struct, RecoilImpulse. It has knowledge about the curves it uses and its start time
Every time the gun is fired, I generate a new RecoilImpulse and add it to a list
Then in Update/LateUpdate I sample each impulse and their animation curves, and rotate/move the gun according to those
And remove the impulse from the list when its startTime > Time.time + impulseDuration
Hmm that look's good way. I'll try it π
Hey guys, I'm moving a game object that is a child of HorizontalLayoutGroup (using OnDrag and changing the loacalPosision), and when OnEndDrag is called I'm trying to reset the position of the object to the position that it started with, I tried storing that location and manually change the localPosition, but it's not resetting to the location that intended When I was trying to figure out I noticed if I paused the game And just moved that child with the mouse it will try to move but will rest to the location that I want (the inforced location by the laoutGroup), Any Idea if there's a function that I could call It will reorder the children?
Hey maybe anoyone know how to fix such issue: There is my settings of Input text field KeyboardType->Decimal Pad works nice on Android (can use and "," and ".") but on IOS there is only "," Is there any way to add also "." to that keyboard?
And I cant use character Validation because "." is correct separator and "," is not correct one and I cant use dot at all when Character Validation == Decimal.
yeah, I know...
but it does not mean that it will update in real time
then it is nothing related to the tmp dropdown
if you need updating something dynamically look at the callback of tmp input field
I figured it out already, it had nothing to do with the input field but with the fact that refreshing that damned dropdown is tricky
Surprisingly I cant find anything on this: I have an object moving towards a transform but the issue is I don't want it going through the ground. I went at this with spherecasts which.. partially worked? It worked at first until the spherecast would constantly hit the ground and never move again
I suppose what I should be asking is if there's a more efficient way to do what I want to do that actually works?
I'm not asking for code just pointers in the right direction
It cant be a rigidbody by the way no objects have one
Can anyone point me in the right direction on how to implement Strategems from the game Helldivers/Helldivers 2? A player holds a button (say left bumper) which lets them input up, down, left, right. If they input a correct sequence of input they can use an ability.
For the uninitiated, you can see the mechanics in this video (ignore the speaker): https://youtu.be/IxrZ5MYM4SU
How would I even begin to implement such a system? I can only imagine how monsterous the if/else if/else statements would look if I went with that approach
Why would it not just be an array of buttons and a current index within it?
The UI is the easy part. Iβm talking about how to match the input
That's literally what I'm saying
array of keypresses and the one you are up to is just an index within that
Erm⦠I mean there are like 40 stratagems each with a unique sequence (4-8 directional inputs). Assuming a player could input any valid sequence from the 40 options, how would I know which stratagem the player wants to use?
Another loop. There's 40 of them, that's nothing
If you had thousands I would suggest a quadtree, but you don't.
You could have a set of currently valid indices into all of the options, and whittle that set down until it is 1 long and the current length is the same as the length of the last option left
Erm, I'm still not understanding the solution you're proposing
Agree, using a tree data struct is probably the answer
I'm curious about the "another loop" solution though.
If you want to do that, that's fine. Personally I wouldn't think it even necessary and would just loop over the options and compare them with the current sequence, whittling down a set (which could just be a list)
Is the idea something like (1)I have a set of strategems, (2) each strategem is a list/array of inputs, and then (3) as the player provides strategem input I whittle the set of strategems down to whatever is valid (e.g. player inputs up + down, so all strategems starting with up + down are filtered from the initial set)?
Yeah, and you'd only need to check the latest keypress at the index in the array of inputs
I'm following.
Building a tree also works and may just be easier, it doesn't have to be a performant version and can just be class references
tree traversal should be easier then maintain bunch of candiates.....
you could literally do it with a bunch of bools
π€· at this scale literally any implementation works
You can, but would you want to? Lol
Depends on situation, compared to iterating a loop? maybe better, maybe not
even brute force comparison would work and you would not notice any performance detrements lol
it's a rare day....everyones correct XD
You're probably right, given the small scale.
Tree data struct seems more legible for the problem
Hey, I am currently working on a small game with a friend for a school project. its going fine so far and we have implemented our first networking solution.
it uses gRPC for normal communication (requests, logging in, fetching servers, etc) and uses a TCP Socket for real-time data such as movement updates when on a server.
The Problem we have now: every time a player moves the Memory jumps by atleast 2GB, I made a Memory Snapshot and noticed that most of that is "Managed Memory" marked as "Unused Heap space" is there a reason why that happens? is that somehow preventable?
How many network packets are sent on move? Is it once every frame for each player's movement?
Unused heap space just sounds like the game is reserving heap memory for later use. It's probably the engine eagerly gobbling up available memory and probably hardware dependent
for each move. but it doesn't happen when packets are sent but only when they are received
that being said - TCP is not generally suitable for realtime data, most realtime frameworks would be built directly on UDP
That might be but after around 20 seconds of movement, my M1 Macbook starts to shit itself and complains its OOM and Unity is taking 44GB
yes
I will send a screenshot in a sec, just had to force quit unity
and before someone asks: yes it also happens after I build the game
I think you're just in the summary tab
go to the other tabs and dig into it
I don't see "unused" here. do you mean the 2.12GB "untracked" section?
i.e. the All Of Memory tab
bottom left "empty heap space"
ah
that's from the all of memory tab
its reserving it for some reason
but it never stops reserving
it continues until the game is completely unresponsive
Well I don't really know how to get better details here but maybe sharing your code would shed some light
seems like you have a pretty serious memory leak of some kind
well I don't really know where to start, I can start sending some movement related code snippets maybe you spot something off
trigger warning tho: the code is meh
Recommendation: start sharing code around the βon receive network packetβ type code
no it's more likely your networking code that's the problem
so this is my MovementHandler, it gets instantiated once and the handle method is called for each incoming movement packet.
https://paste.teamhelios.dev/TeNS1NfWDg/
This is the MovementData Object that is being parsed via JsonUtility:
https://paste.teamhelios.dev/tG7vPdGGX1
This is the whole method that is responsible for reading from the TCP Socket
https://paste.teamhelios.dev/37HrzBhGI5
those are my PacketUtils used to serialize / deserialize Packets: https://paste.teamhelios.dev/tK26Z2SlqI
I really hope you guys find something that seems weird
Well one thing to note:
var buffer = new byte[_client.ReceiveBufferSize];```
Are you customizing `ReceiveBufferSize` here? By default it's 8KB which is a huge amount of data to allocate for every packet you receive
that can add up quick
what the actual fuck is that link
anyway, those are internal unity errors. restart the editor
ok thanks
no, I don't but would that cause those hugeeeee jumps? I mean my Movement Packet consits of a byte to specify the type of packet and then a payload. In the case of the movementdata its just a json serialized object containing the uuid, xyz, yaw, pitch
Can I ask a silly question - why are you building the netcode here from scratch?
it might be more useful to look at the memory section of the profiler so you can see frame by frame when the allocations happen
Just overall I'm seeing lots of inefficient/questionable things like the use of managed strings over the network, use of TCP, use of json serialization/deserialization
you will save yourself lots of headaches if you used a premade network framework
TCP is a bad choice for multiplayer.
A single lost packet will completely block the stream.
Well the biggest reason is: Learning purposes.
But the other one is: there is nothing similar to what I am trying to build.
I want to have a standalone backend responsible for all the user management, stats, etc.
And have the possibility to self host each individual game server.
the current setup is:
Once a game server starts up, it contacts the Backend (which we call Central) and lists itself on the public game server list.
that might be, but I doubt that would cause the memory leak.
https://github.com/ValveSoftware/GameNetworkingSockets is worth looking into if you want to build the networking system yourself
it provides a solid transport layer
there's also Unity Transport, too
maybe its worth mentioning our current backend (which works 100% fine) is written in kotlin
GameNetworkingSockets do not have a Java / Kotlin binding
You can use a normal game networking framework for realtime stuff and then your custom web backend for TCP/Web app stuff
self hosting is possible with frameworks like netcode for GameObejcts and Photon Fusion
Right now the biggest problem is really the memory leak. Switching to UDP is not that hard and probably won't solve the issue
that would mean I need two completely different network frameworks. Is there no way to just figure out what is causing the memory leak without having to completely rebuild the networking
it works fine otherwise
its just the memory leak
no one would be a network framework and the other is basically just UnityWebRequest
I'm not saying discard everything you have, just an idea to consider
but based on what I'm seeing you're going to have a LOT of hurdles in front of you for realtime interaction
and this is a wheel that has been invented already
I really appreciate it, and we did consider that, but the only big problem we have is the memory leak
like I said so far it works absolutely fine, its just the memory leak.
Movement is synced perfectly and with very little latency (we will implement interpolation once we fixed the leak), Connect and Disconnect events are instantaneous and our very quick weapon demo also worked fine.
try reducing the buffer allocation and see if that makes any difference
if it does it's a signal that's the right direction
any suggestions on a value?
none of these
var buffer = new byte[_client.ReceiveBufferSize];
var bytesRead = _stream.Read(buffer, 0, buffer.Length);
var packet = PacketUtils.Deserialize(buffer);
should be variables local to the while loop
Also wouldn't UDP require the client to port forward in order for the server to be able to send data to the client?
well I just moved the buffer out of the while loop, but doesn't the reading and actual deserializing of the packet need to be inside the while loop?
yes, but the variables involved should not be, you are just allocating more and more memory every loop without ever releasing anything
so like this?
void WaitForMessage()
{
var buffer = new byte[1024];
int bytesRead;
Packet packet;
try
{
while (_isRunning && _client is { Connected: true })
{
if (!_stream.DataAvailable) continue;
bytesRead = _stream.Read(buffer, 0, buffer.Length);
if (bytesRead <= 0) continue;
packet = PacketUtils.Deserialize(buffer);
switch (packet.PacketType)```?
yes, now when you use the variables the previous incarnation will be released, this is basic memory management which you should know if you are doing network stuff
anything else I can improve?
I'm not going to go through your code, but now, at least, you know what to look for
unfortunately those changes did not help at all: just after like 4 seconds of movement
How do i seperate colissions properly? I have 2 handlers, attack colission handler and body colission handler. In body colission handler, player dies when it touches an enemy. On the attack colission handler, player attacks layer and enemies layer interact to detect hit attacks (by the player). However, when i attack an enemy, my player dies because the body colission is triggered. Ill send pics of my setup.
Question: If i have 2 objects, 1 of them is a player which has a body colission handler and is on layer "player". This object has a child which has an attack colission handler and is on "PlayerAttackHitbox" layer. The 2nd object is an enemy, the enemy is on layer "Enemy" and collides with both other layers. Why is my body colission script being triggered when a colission between the attack hitbox and enemy layer happens?
All collision events are called on the RB, and that's where your body component is. If you put it on a child object along with the collider for body things - you should be good (I think).
My root object has a lot of children, likes sprite or interaction indicators. If i move the RB to a child object, how would i move the collective group of children?
Because my RB is triggering undesired colissions, even though my children have seperate hitboxes and layers
I dont want to move my RB from root, but i do need to seperate colissions
My enemies are triggers, and my player hitbox is not. So im using entertrigger func to determine how to handle colissions. This leads to my attack move box trigger to also pickup that we are hitting an enemy and the player should die. But when i hit the enemy with an attack move box, the enemy should take damage and player should not die.
moving the RB won't change anything about the collisions
Put the OnTriggerEnter things on the specific colliders you want them to happen on
I did this. I have a body colission script which causes player death. Its a very small hitbox in the middle. But when my player attacks (big hitbox) the body colission script is still triggered. They are also on different children with the same root now.
It seems all of my triggers are called when one of them hits an object. I would however like to only call the script attached to the trigger object. Is this possible?
That's how it works by default I'm pretty sure... so something's off with your config, I'd guess
Are you sure there are no other colliders/triggers involved? Maybe the trigger gets triggered from something other than what you expect.
You can do a small repro scene just to test how the physics system behaves, but am 98% sure that if you have a collider + script somewhere not on the root, you would only get triggers events for that specific collider
Is it expected that when I change the Layer of one GameObject in a prefab it also changes the layer of all other gameobjects within that prefab?
(no matter what I do)
Pretty sure it asks if you would like to change layer of children as well?
It does but behavior is the same no matter what
It even changes the parent
for whatever reason
Never tried to deny so idk then lol
I'll just work around it I guess, very confusing
In the editor or from code?
Just in case what editor version are you using?
Editor
Hey so i need some help, i'm making a project with portal which teleport you to the other portal, only problem the velocity just stay the say so when i go inside instead of shooting me out it just send me in which direction i was going. I would like than when i get in the portal it shoot me out at the same speed than when i entered it but the right way anyone who can help me?
2021.3.22f1
Hmm, it should ask you if you want to set child layers too
It does but disregards it
Ah. Weird
Illusion of choice β¨
"no , you're gonna change the layers of the children as well and you'll love it" - editor probably
Show the flow
presumably because you are teleporting from portal A to portal B and so are losing your velocity. you will need to save it before entering the portal and re-apply it when exiting
i'm not losing velocity it just not going the right direction
You'll need to calculate the angle difference between the portals and multiply that times your velocity
or rather, rotate your velocity by that much
ok, so you need to adjust the velocity to the forward of the portal
i know i have to do that but can't find anything about it on the documentation or anything
or rotate the player to that forward
it a ball that work with add force so not really a good way of doing it
how can i do this?
oh wait yeah could work
not multiply, but rotate
yeah but how can i rotate velocity?
by...... rotating it π
Can also just do portal.transform.forward * previousVelocity.magnitude
Unless if you want the relative velocity to stay the same
same way you would rotate any Vector3
wait you can just rotate velocity like that i tried but wasn't working must done it wrong then
osmals solution is simpler if you don't understand quaternions
how to make something like this? https://i.gyazo.com/cf40d8ca14692f2653101f7699e08259.gif

man, you really need to learn how to ask questions
collider with raycast and onclick to determine if it's started the grab; onmouseup to un-grab; save initial raycast, difference the raycast of "current direction" while dragging, and move the lever accordingly within the bounds of it's geometry
each of my bullet points is a reasonable amount of code, so.. if that's not helpful and my comment looks like gibberish, you might want to try something a bit simpler.. π that diagetic UI is a nifty thing but not super simple
I saw a code about it, not sure if it works ```public class SimpleLever : MonoBehaviour
{
public LayerMask leverMask; //Layer mask of just the lever object's layer
public LayerMask leverPlaneMask; //Layer mask of just the invisible plane object's layer
bool isUsingLever = false;
void Update()
{
//Initial mouse click on lever to begin dragging on lever
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 10, leverMask))
{
isUsingLever = true;
}
}
//Continued holding down of mouse button after initially clicking on lever
if (Input.GetMouseButton(0) && isUsingLever)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//See where a ray from mouse position hits our invisible lever plane, and have lever look at that point
if (Physics.Raycast(ray, out hit, 10, leverPlaneMask))
{
Vector3 lookPosition = hit.point - transform.position;
lookPosition.z = 0; //We can zero out one of the axis because the lever cannot move in all 3 axis
Quaternion lookRotation = Quaternion.LookRotation(lookPosition);
transform.rotation = lookRotation;
}
}
//Stop lever interaction when mouse button released
if (Input.GetMouseButtonUp(0))
{
isUsingLever = false;
}
}
}```
yep.. that's... pretty much what I said. π
but problem is, I can't seem to put it in my raycast code or integrate, i get confused 
yeah so.. probably start with something simpler.. this is definitely not a trivial thing
Plane.Raycast exists too. No need for a whole plane object and 'lever plane layer'
Just a side note
Raycasts are not objects, they are methods
Plane.Raycast means, the raycast from the Plane?
And yes ofc
Plane is a built in class
Or a stuct I think
it is not physical? or I need to put the plane thingy
It's infintely wide tho so you would need to check for distance
Not physical
https://docs.unity3d.com/ScriptReference/Plane.Raycast.html
Anyway this is not super relevant, was just pointing it out π
The normal determines its rotation
it is ok
I might use, thank you osmal, sharping
Hi, does anybody have a script for auto card positioning like big cards games have? It would take forever to do it by myself to look good.
I mean in hand
You draw a card and it is getting placed somewhere, different depending on amount of cards you already have in hand.
like here, the position of cards is different depending on how many cards one have
you can do it, I believe in you
sure i can, but it would take a big ammount of time
i still can't see how i can do it.
i tried but it just don't work
anyone used addressable asset pack?
and since it is something that many card games have, i think there is a ready script somewhere
exactly like this #archived-code-general message
but i teleport the player this way
oh god why are you calling GameObject.Find every frame
So why are you using transform.position when you use rigidbody?
just drag in the reference, no need for find
even if you did need find why every frame
it just some left over part of what i tried to do
man, do you seriously expect us to work with crap?
all i'm trying to do is when the player touch the collider it teleport him but in the right direction which is where the portal is looking at but everything i tried to this point failed
yes, and things are failing because you're searching for a random game object by its exact name
we know what you are trying to do and you have been told how to do it, but that code reflects none of that
it cause right now i'm showing how it was
why would I care how it was?
can't you just show me the code that i can use to just get is velocity teleport him and apply it the right way cause i try using this in a lot of way but still can't get it to work
that not working sadly
Show what exactly you tried
but it would obviously not work but i don't see how i can use that.
yeah
Orange is other portal?
other is the object touching the portal
So the thing you want to teleport
There is no = on the line with the error
Get other's rigidbody, and set its current velocity to what I said earlier
So that would be orangePortal's transform forward, normalized, multiplied by the rb.velocity magnitude (so that you keep the same speed).
also still using transform when he has a rigidbody
ok gonna try
Yeah. Should use rigidbody.position to teleport it instead
is it like this cause right now all it doing is i think litteraly bringing me down
i just done -test and not it bringing me the right way thanks dude ^^
Yeah it just depends on which way your portal's local Z axis (blue arrow) is
Np
Where could I write single variables, like setting a projectile's owner through a GameObject variable?
It doesn't seem right to place this in ProjectileMovemet
It's unclear what you're asking. What do you mean by "write" a variable? DO you mean where should you declare it? It should be declared in whatever place makes the most sense for it to be declared. Hard to say more without specific details about what this variable is and does.
It's a variable called Owner that's assigned after cloning the projectile, done to prevent the player or enemy from damaging himself/his allies
Why do I get this errors? This should save my data and load my data using Json files. Here is 2 codes
you cannot directly assign property like that for transform position
but why did it worked in the start? how can I save player x,y,z position and camera x,y,z position then?
how should I fix that
for starters, why are you saving them as individual floats instead of just Vector3
the problem is assignment not saving, also yeah you're using JSONUtil just save the V3
It should live on a script on the projectile instance
Can't think of a script to place that
Put a script on the prefab
put the variable on it
I would call the script Projectile
okay so i make playerPos Vector 3 variable right?
But why have a projectile script with nothing except one variable?
to mark the owner of the projectile
You could also name the script OwnedObject or something of that nature, and it could be reusable for other things that have owners too
Can't I just call the script ProjectileOwner? But I feel like having a script with, literally, just one line of code is bad practice
You can call it whatever the heck you want
it's not bad practice at all honestly
You'll likely find that more than one thing will live in this script anyway
Generally a projectile would have several variables on it
for example DamageAmount
Owner
any other properties it needs
Already have many of those other properties somewhere else
where is the "somewhere else"
Damage is handled through a DamageOnCollision script
Movement is handled through ProjectileMovement
you've got the wrong using statement
how do i assign x,y,z position to vector3 variable in GameState
Either repurpose one of those scripts to be more general purpose, e.g. ProjectileMovement -> Projectile, or accept the world of lots of little scripts with a single purpose each.
wait how to fix that
use the correct Vector3 type. not the one from System.Numerics
Vector3 from UnityEngine not System
I'm aware that you'll end up with many, many script components on just one object. But, when should you stop? Is 30 script components too much?
Performance wise many of them don't even have an Update or Start function so it won't affect anything
when it becomes unmanagable from a project maintenance standpoint or when it becomes a performance problem.
I suspect you're not near either of those thresholds
@pliant sapphire
So would, say 20, be too much?
no..
personally I probably would have just had a Projectile script that does all those things you mentioned (movement, ownership, damage on hit), but depending on the structure of your game you might have objects that only have some of those features, in which case it makes sense to separate them out.
my guy do you know what a namespace is?
oh my god you need to change the using directive from using System.Numerics; to using UnityEngine;
please go learn how c# works. there are beginner courses pinned in #π»βcode-beginner that will help you get started
hey all π im doing some dynamic mesh generation at runtime. it's performant enough, but i was curious if calling Mesh.MarkDynamic() would be good? im using the same mesh instance when changing the mesh, but it happens only once every 5 or so seconds. is that too much time for it to matter? i plan to try it out anyways but i was curious if anyone had experience
https://docs.unity3d.com/ScriptReference/Mesh.MarkDynamic.html
have you tested the differences with Profiler ? I'd start there
So i have 3 box colliders on seperate children, 1 small and 2 big ones. Both are a child of the same parent. When big box collider 1 gets triggered, the small box collider somehow also gets triggered. When big box collider 2 gets triggered, the small box collider also gets triggered. The big box colliders do not trigger eachother. The small box collider is not touched for sure. Does anyone know about this problem or can help me figure out the cause?
Where can i find the FPS sample project that work with the latest engine?
unity hub usually has the most updated templates
So I got the github version which is outdated. Is it going to be in Learn or COmmunity section? I don't see it
Make a new project and you can select them
I don't see it there as well. I am talking aboout this one. https://unity.com/fps-sample
Ah, then it's w/e it is in the repository
It's outdated. Look at the update dates and release date oct 25, 2018
Update about the state of the project: This project is based on Unity 2018.3 and no longer being actively maintained. Feel free to continue to use it as a learning resource or simply for inspiration. As always, you should upgrade to latest version of Unity and packages if you intend to start a project.
im having this problem when crouching , the charactercontroller center goes up as it supposed to but my playerobj stays the same and im not sure how i can pull the playerobj abck up and make the player scale to 0.5 when crouching and back to 2 when not crouching
https://paste.ofcode.org/LgfXbaQRACVUWDfpnmCKd9 , player script
I'm new to unity. I tried to run it using the latest version and i get this error:
Package com.unity.entities@file:D:\Unity3D\FPSSample-0.0.0\Packages\com.unity.entities has invalid dependencies or related test packages:
com.unity.jobs (dependency): Cannot connect to 'staging-packages.unity.com' (error code: ENOTFOUND). Verify your environment firewall policies allow connection to this host name. If your system is behind a proxy, verify your proxy environment variables (HTTP_PROXY and HTTPS_PROXY) are properly set.
com.unity.properties... ```
Hello everyone!
I am currently working on my dialog system. The goal is that I want to pause the game time while the player is in dialog. With the use of Time.timescale = 0f this works perfectly.
Now I'm faced with the problem that I don't know exactly how to avoid the enter keys globally and cleanly.
The player should only press the space bar, all other inputs do not react. This behavior should continue until the dialog is closed.
How would you implement such a system? I know I could basically set an enum state and create an if statement for e.g. the items, where I check "if player dialog state then return void".
But I wonder how I should implement such a system in larger projects where you have many keybinds.
Does anyone know a concept for an input manager to solve this?
use an event that enables/disables your input
Cannot connect to 'staging-packages.unity.com' (error code: ENOTFOUND).
Indeed, if I type that URL in my browser, it's not found. Looks like the package you're trying to install has an old dependency which doesn't work anymore.
You'll need to install com.unity.jobs manually from the Package Manager to try and fix it.
Anyone know how to fix this pls
If you are using the "new" input system package, you can add all your input through an action map asset, and disable all your maps except for the specific dialogue interaction action, or as boxfriend suggested, you could setup an event and maybe a game state enum that some or all (except for the one you want) input can be toggled with
I am working on a visual novel rpg. Things I have done so far are room navigation, inventory, and parsing from a text file to display dialogue. Currently when the you go to a new room it just reads the text file assigned to that room. My problem though is with what I think is called progression. How do I structure my game so the game knows what the current state is in. Most games have this progression that as you do things npcs and the world react. How do I do this and keep track? For example I killed a boss and return to a previous room and it triggers a new scene with the npcs there.
save data, when you beat a boss, save a boolean somewhere that has happened, when you reach a checkpoint similar idea
the other logic can check this data to decide what to show the player or do next
do I need a new dialogue file for each thing like if a have a certain number of items in my inventory?
The idea of a "dialogue file" is going to be pretty bespoke to your system. How did you define it?
how did you design it to be used?
In a lot of visual novels you have a file like so
'''
Name: "Dialogue" [Emotion, Movment]
'''
And you parse them to display on screen
also in this kinda game, like a telltale style game the dialog is more addative. its not 1 totally pre writtne thing tossed at the player
but might play 5 of 6 dialogs all after eachother based on the current game state
also generally ends up being more of a tree structure where it branches based on game state or certain options
then maybe later in the story closes back in on its self
This was very helpful https://www.youtube.com/playlist?list=PLGSox0FgA5B58Ki4t4VqAPDycEpmkBd0i
sure but real visual novels are going to get very complex
when there's branching and state involved
the graph can be pretty complex and a "lets make our first VN" tutorial is not going to get into that stuff
so the first studio i worked at was doing a telltale style game
I haven't gone through the whole thing but It seems he is making something very linear. I want to know how to incorportate gameplay into it if I have to juggle alot of variables like an rpg.
yeah the dialog tree by the end was enough to cover the walls of the entire office
suffice to say you will basically need a way to have conditionals and the abiulity to jump to another labeled place in your graph
Do you know if the job system requires Pro version only?
all features work on all versions
Packages/assets are separate. At worst you pay for the asset once, else it's free
I dont see Job
well that is only showing installed stuff
it benefits from some pacakges but it not a package
is it already installed. I don't see it anywhere. Do I have to download the zip file then install it manually.
like i said and in the manual there its already part of unity
you will just want the collections and burst installed to get the most out of it
In that cse I can just remove the dependency from here. FPSSample-0.0.0\Packages\com.unity.entities has invalid dependencies or related test packages: com.unity.jobs (dependency)
@gloomy thicket desc of that package is that it provides additional jobs types
You can add it by clicking the + at the top left of the package manager -> add package from git URL and then input com.unity.jobs
Otherwise I think if you enable preview packages from project settings -> package manager, you'll be able to see it from the package manager
could be a untiy version thing too
Is this actually good practice or is it overkill?
I was just having a discussion about this, but ideally if you're doing component searches every Update() or in between, it'll always linear search through the specific gameobject. So, if you have a single gameobject packed with garbo, it'll searc through every single one unless you divide the search a bit more.
I somewhat like point one. I somewhat like two, i like three, four is important for many things, not others,
for five, if it's truly a QUERY, then use TryGetComponent, not GetComponent
Best solution? Layer mask the gameobject with a single component that provides references to other components.
This is basically the philosophy of an entity-component-system design
It's very different from traditional object-oriented programming (which unity's design pushes you towards)
Isn't inheritance generally outdated nowadays and should be used only occasionally when you need it?
No
I would not call inheritance "outdated"
its a approach i persnally prefer to not lean much on inheritance
but its still a tool that can help at times
Well, composition removes the need to manage any inherited class too much
they do not solve the exact same problems
So as I said, should be used when you need it and not relied upon
Composition and Inheritance can be used together..
inheritance helps grouping behaviors, but grouping too much can be problematic
you can totally not use inheritance but that means you end up using more comparison logics
So as I said x2? "Should be used when you need it, not relied upon"
also its not 1 or the other, like my programming style uses what is most readable and does the best job for each situation
That is kinda nonsensical with what you said before
some of it is very functional, some very composition based and even some oop stuff as its needed
well, sure
if you don't use inheritance, you don't use inheritance
use inheritance when you need polymorphism. use composition when you need to build things out of small features.
like i use langauges that dont have it, and get by just fine without the feature
First time I talked about inheritance I didn't say it shouldn't be used at all
but still make use of it when it is a tool i can use if its suited
inheritance is technically more performant since it helps lessen ambiguous objects and what they contain, but it's just harder to work with (well, it's more that it's hard to deviate from your original design)
No one said you did?
Well you said it's nonsensical
That doesn't imply you said it should never be used.......
Kind of hard to know what it implied with little to no context
That was kinda my point with what you said I guess.
It's ambiguous and nonsensical.
it was kinda implied calling it outdated, but really things never get truly outdated
Regardless I didn't come here to fight over inheritance
I don't see any fighting? But ok, good to hear
You asked a question and got answers π€·ββοΈ
concepts like composition are older then inheritance and getting popular again
I want to have my gun in a 3d game lag behind when you turn, any suggestions?
who knows in 10 years it might flip over again
maybe something like Vector3.SmoothDamp
Got one answer and I was about to ask more
more I use oop the more I prefer just popping out crappy one-track minded python scripts and getting done
My original question was whether breaking scripts into even smaller ones for composition (see above examples) was worth it or the performance would be overkill
?? Then ask more. But you certainly got multiple answers from multiple people. Why are you ignoring the others and only responding to me? This is getting weird
I'll just step out. Best of luck!
it will have almost no performance impact
as long as references are properly cached
This is a design problem, not a performance problem.
Composition can produce very flexible games.
just dont worry about performance, you got a profiler you can use to indentify problems if you have one
I recently took the plunge on breaking my monolothic "player" and "enemy" classes into an Entity class with a bunch of Modules on it
also how far things are broken up is up to you
i persnally feel you can share funcnality better this way then with inheritance
if I have an Entity, all I know is that it has:
- a brain
- a locomotion
- a body
absolutely
Everything else must be checked.
Could it turn into a performance problem if each object had 20-30 mono behavior scripts? Obviously not all of them would use Update()
it might be a player, a lever on the wall, or a spectator
my rule of thumb -> don't derive more than 2 deep
that is fine
I had a problem where the enemy's brain tried to figure out how to kill light switches
The enemy wanted to attack every other entity
it failed to actually find a plan, but it was wasting its time
though break it down into what makes sense for your game
having a bunch of components on 1 object is not going to be any worse then 1 massive component
and will be easier to manage and share some of its features with other objects as componetns
also composition does not always mean you need new components
having regular C# classes you use in multiple places does the same job if they dont need all the extra stuff a true monobehaviour gives
I'd argue you'd probably want to have a service locator and not search by (linear) component search, and keep gameobjects you want to interact with on their own specific layers.
meaning there would be some type of grouping via interface or class
i.e. An IEntity interface where you know this object has health, some methods that involve interacting.
Because you mention not all having update, one trick is to have a single updater for each gameobject, or even one for the whole scene, then updates can be controlled more directly, and even called less frequently (making your own update cadences). This can sometimes help performance (which should only ever be considered after profiling anyways) if having a bunch of updates becomes an issue
I'm aware that this exists, but would having 30 monobehavior scripts affect performance compared to one big script if all of them don't have update()?
Someone a while ago told me this does affect performance, and now someone's telling me the performance is negligible at best
No, it would not
I mean, EVERYTHING affects performance. So I think negligable is a good word for it
"Affect" is just a bit vague. It wouldn't overtly harm performance
I mean, it's not like I'm going to have a lot of high poly models so all I have to worry about is code performance
or worry about getting the game done
would worry about making your code do what its supposed to do and be easy to read before performance
if performance is a issue you can profile things and find out where and why
instead of jumping at any and everything
It always depends. So just try things and profile.
again, this is not a performance problem
this is a game design problem
I didn't rewrite my game from near-scratch because it was running too slowly
I did it because I couldn't express my creative vision (ow that hurt to wrote)
i couldn't make the thing i wanted
there we go
also 15 years of dev, in my experience what people think will be a perf problem is often not, and osmetimes they create a worse problem working around it
weather that be a new perf problem or just making it hard to maintain the codebase
seen that on both the art and code side
had artists cause fillrate issues by over optimizing for triangle count
Maybe a little more overhead than just creating 30 plain c# objects, but otherwise it's what you do in those update() loops
and this would be more of a mem problem than runtime performance which you're less likely to run into
which is miniscule at most, your loaded textures and models will contribute the majority of what's loaded into mem
How can I override the sort order of an overlay canvas to be below the sort order of another canvas tied to a camera?
sounds like rendering ordering of the cameras
Overlay cameras draw on top of everything else
they draw after the camera is done rendering
so, you can't
if you wanna do some hacks, there might be some options... but it'd be more preferable to adjust approach
What're you trying to make your UI do?
I have a UI piece on a canvas that I want to display independent of a camera--so it can display regardless of the current active camera.
However, there is a certain case where I want it to be hidden by another stacked camera's rendering
display it on another always active camera
I was holding off trying that solution, though it may work. I'd have to juggle some cameras
you can probably render some camera to a render texture and then display that on the other with the desired order, but that sounds like more of a workaround
Are these not two overlay canvas? I would assume you can get by with the ordering on the stacking interface
can anyone give me some input on making an ability system like this https://gdl.space/qurecuhuke.cs ? This is what I have so far. I want to know if it's worth continuing down this path or would it be better to just code each ability on it's own. I am making an ARPG similar to POE and Diablo and need to have interacting effects such as burning, poison, speed buffs/debuffs, etc
That's roughly how I've done effects in the past
I'm unsure about Apply needing to know about a caster, though
I think I'm going to have a script that disables the overlay canvases in this particular case
It makes sense for an ability to have a caster
But effects shouldn't demand a caster
although, maybe I'm just interpreting "Effect" too broadly
that makes me think of basically anything that can happen to something
yes it is, like SpawnProjectileEffect
the projectile needs the owner to know what targets are "allies"
for example
the issue im running into is passing stats into a system like this
and modifying the values of the effects at runtime
one huge issue I have with ability systems is targeting
and trying to keep abilities reusuable
I'd make the effect just define how to calculate the damage
actually, here, this might be relevant to you
i made a very elaborate system for a soulslike a while back
im basically trying to make a very simplified version of GAS in unreal
pass ownership into the projectile that sets masks
as always, I like to pass IEntity around everywhere which includes stats too
i made all of my stats into scriptable objects, so entities aren't even guaranteed to have all of the kinds of stats
you could replace those with enums
my stats are already enums
and all the stats on my items get summed on my character
a weapon deals base damage, plus scaling based on your stats
yep
well, there's two ways you can do stats
im doing it slightly different where the item is defined by affixes like poe
cache the calcs, or do it all on hit
im doing it all on hit right now, maybe a bad idea?
or go mid-way and try to cache as much as possible
poe cache's a lot of their stuff (and it still sucks because that game drops frames like crazy)
like if theres a poison on an enemy and i get a poison boost, the posion should increase
therefore it needs to know about the caster
true
ok, that's another problem, abit harder
should I just not do that? its not really neccessary i guess
snapshotting sources, vs updating sources
it could just snapshot
yes
now that I think about it, i think most arpgs just snapshot
That's also what I would expect to happen
on hit, mash all of your stats together and spit out a number
snapshot is easier too, so I'd go with that
that's what I do right now with a very basic attack system, no abilities yet
just shoots projectiles that crunch the numbers and apply damage
but with this system I can't figure out how to easily pass the "damage" "increase effect" etc around
and make it generic at that
In the last dev talk the Diablo people explained that they're trying to go away from snapshotting, because it allows people abusing systems to gain effects for longer than intended (of course, that's specific to some skill types and combos)
