#archived-code-general
1 messages · Page 213 of 1
Is the tag/layer of the right wall correct?
yep, cause it works correctly one 1 side of the wall and not the other
is there a way to debug this? drawRay isn't the answer
RaycastHit2D[] hit = Physics2D.BoxCastAll(position, groundedBox.size, 0, Vector2.zero, 0, mask);
And the whole wall is 1 piece with the correct layer then I would guess?
its only the hitting the left side of walls thats the issue
when it hits the right side of walls it works fine
does making an array initialize all the elements in the array to null, or does it just say "There can be two elems here, but there aren't right now"
like if I get Array[1] right after creating it what does it return
depends on the array
if its an array of integers, it will return 0 I believe
if it's an array of lists for example, it will return null
ok null then
Google "how to use lerp unity". There's an article
You can also test this yourself with your array by just printing out the first element or comparing it to null
guys I think I've got some fundamental misunderstanding about how to design something in unity. I have a composition based ability system where I create projectiles GameObjects then attach components to that have behaviours. How am I supposed to change the fields in these components? They need to on a GameObject to be edited because of monobehaviour, but then they would cause their specific behaviour on objects I don't want them to. I thought about making prefabs but I also want items that contain the components and copy them to the abilities. Should I just put the components on objects but dissable them? or is there some other method of designing this which I am not aware of?
? not sure what you are asking but did you make the variables public
Do you mean that you have some projectile gameobjects and you would like to change their variables/stats without having to individually go to each of their script and change it?
As to me, a ScriptableObject sounds like what you are looking for, like a data container kind of
yeah
but scriptable object doesn't have monobehaviour so I can't use update and stuff?
Value types (like ints that was mentioned) cannot be null. The array just declares space for these values to live, it doesnt initialize the elements to anything. So in your question for what array[1] would return, it depends on if the type is a value type.
Yes, but for that perhaps you could have 2 things? One projectile script that handles the logic and stuff, and then a scriptable object for each of the projectiles that contains their data? https://www.youtube.com/watch?v=aPXvoWVabPY
When making a game you need a good way of storing data. This is where Scriptable Objects come in! In this video we’ll learn how to use them by looking at an example: Making cards for Hearthstone.
● Project on GitHub: https://github.com/Brackeys/Scriptable-Objects
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
····················...
Value type means something specific, a gameobject isnt a value type.
Value type is more related to memory and where the object is stored (stack vs heap)
cool
this is what I mean. Am i making any sense?
You probably dont want to be instantiating objects like this and then adding a bunch of components for each projectile you are spawning. I'm truly not sure what "items copy to abilities" mean but you should definitely be using prefabs to save yourself the trouble
This is with the items
i suppose i should just use refereces to prefabs?
a prefab for items and prefab for abilityt?
I leave for two seconds and you've brought up diagrams
If you are putting a monobehaviour on a gameobject just because you need to edit variables from the editor and not because you need the monobehaviour to control the gameobject, then you can use ScriptableObjects, which are just data containers
if you need a ticking function in a scriptableobject, you could use a tickmanager that iterates through all the scriptableobjects and calls OnTick for each of them (although you would need a base class then)
that may possibly be the worst possible solution but eh
oaky thank you
You'll probably need to explain more about what an items relation to abilities are or like why these are even copied in the first place. Right now your diagram shows 2 completely unrelated scripts communicating to an instantiated object so it doesnt really make sense.
When making a game you need a good way of storing data. This is where Scriptable Objects come in! In this video we’ll learn how to use them by looking at an example: Making cards for Hearthstone.
● Project on GitHub: https://github.com/Brackeys/Scriptable-Objects
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
····················...
so the projectile uses composition based behaviours, I want the ability to add some behaviour, then an item to add some additional behaviour if you have it in your inventory
my question i suppose is just how should I store these components such that they are easily editable in the edtior and can be instantiated on the projectile object with the correct values
Without seeing code it is kinda hard to suggest anything, I'm not sure exactly what your items do.
In my game, my items only affect stats. The abilities dont directly know about the items, they're just updated with the correct damage or whatever stat is needed
the items just store the behaviour components to be added to the object
like 'explodes on hit' or something
then i copy these to the game object
the projectile will not communicate with the item
Hmm that might start to cause issues, like you wouldnt be able to use object pooling too easily in this case
if it were me I would just add behavior based on enums or bools and have the items set the enum/bools as needed
ok thanks you for the suggestion
Maybe you could have an event for when damage is dealt, then have a player script decide what effects to do after (like explode in the area that was hit)
yeah that's what i've got basically
So if I got down the scriptable object route would I need two scripts? A monobehaviour script to carry out behaviours and then a scriptable object to store value in the editor? like this?
Pretty much, you can also use POCO (Plain Old C# Object). That being said, using Prefab can really help because you get free copy.
public class Explosion : ScriptableObject
{
[SerializeField] private GameObject _prefab;
public void Spawn(...)
{
_prefab.Instantiate(...);
}
}
SOs are very good for passing around and coupling settings
You can do something like making a movement parameter SO, with things like speeds, gravity etc. And have several different obj with that SO.
The benefit is: 1) You can couple multiple things by using one SO instance for multiple gameobjects. So editting the one SO saves you from having to go find and edit them all. 2) You still reserve the right to make another instance of the SO if you want to make another that is decoupled
eg You have an EnemyMovementData : SO, make a GenericEnemyMovement.asset from it, and tie it to a goomba and koopa,
hey guys, any idea why it always stay null?
tried both GetComponentInChildren and GetComponent
The script is monobehaviour and on the player parent.
null means it did not find a component of type Rig in the children
thank you
thanks !
i know, but why? any idea, or is it the wrong way?
is the child inactive?
and does the child have a component of type Rig?
and by child, you sure it is a child in the hierarchy?
yes please check the second screen
Why are you using Find and GetComponents instead of dragging the references in the inspector?
GetComponent is good
most likely i will add coop and have different characters
but can get messy if you start splitting scripts across multiple gameobjects
so it need to find it "dynamically"
That makes no sense
If you have different characters you drag their references too
i would first check rigMelee is correct
should be a non-null reference to the right object. And also it only needs GetComponent since it isn’t in children
then debug.assert non-null
https://media.discordapp.net/attachments/763495187787677697/1167134293655568425/image.png?ex=654d0583&is=653a9083&hm=b6ba443585c84885a04636000d43e892efba4086c36cbe16f6e8f8810e8a83dc&=
the player has the script which handles this, now as children, i will have all the different characters, so i can't assign just one specific rig from one character
yeah, I would not use .Find
what could i use instead?
I would [SerializeField] private Transform rigMelee;
I would not fuck around with those GetComponents and find methods in this case. You want a direct reference to the thing
The rig is on the parent object right?
Rig component is on the RigMelee object which is a child of the main Player object
which has the script
Find and GetComponent will also get just one specific rig from one character so that doesn't solve anything
If you want a reference to multiple child objects then make arrays and drag all the references to there
in general, if you have multiple child objects, you want to avoid using Find or GetComponentInChildren. You want direct reference to the one thing you’re looking for
the non active characters are deactivated / the gameobjects i mean, it would/should only find the active one
That's not a good way to do it
yeah that’s bad
don’t do that
Serialize the field
specifically, serialize the transform of the child object
Seriously don’t fuck around with that
you don’t want your code for finding components to depend on what is or is not active at the time, unless you actually want it to depend on that
Assign the script that handles these things to all characters, then the one that is active automatically does what it should. Don't have one script that tries to pick the things it needs from the one character that happens to be active
just use a prefab, bro
prefab can serialize field for specific components in the prefab, and it will reference them correctly
hehe should we continue in beginner?
please continue...
just use a prefab, bro
ok fair enough, i never had a problem this way, heck my whole weapon sys is like that haha
I've decided to make a 2d top down platformer (like CrossCode or Alundra) and i had a basic idea: starting with all the colliders being not where they look, but rather where they would be if they were on the ground, so if there was a house on a hill, the collider of the house would be much lower on the y axis. When the player jumps it only moves the sprite renderer and not the colliders and stuff (similar to the shadow idea before). I'm using layers so when the playerHeight (a variable set in a script named PlayerHeightEntity)gets above a certain value, the player can only interact with colliders also at that height value (objects are dynamically changing layers to affect this). i also had a gravity variable which brought the players sprite renderer back down if the playerHeight was higher than the float currentFloorHeight. And that was it. Does anyone know if this would work well, because this is something that I'd really like in a game, although it might be hard to implement
thanks guys
gl
you don’t want to use Find, like ever, btw
anything where you search for a reference by string is a big red flag, unless you are super sure you know what you are doing
i never did, that's why i asked, but i guess it's really not smart
but theoretically it should find it right?
this sounds like garbo, tbh
you need to establish really firm rules for a game, and “you don’t actually know where you are” is a terrible premise
wdym?
if you are decoupling colliders, I expect the player to have good knowledge of where they actually are, and what the current gamestate is
if sprites get totally decoupled from colliders, that is a big red flag
if the sprites are on the ground then the colliders will be in the right place, it's only if they are percieved to be on a different height level
so…. why?
because the jump isn't supposed to actually move the player up the y axis, it's just supposed to look so
yeah
a lot of Cast methods for 2D have depth parameters, which I think are for objects of different Z
i could show a clip of crosscode or alundra if you want
i think I understand
this isn’t too hard to do, afaik
on collisions and triggers, you need to check Z as well, and for casts, you need to specify depth
I don’t think you need to make an artificial height system
what are casts btw?
Cast is when you project a collider by a vector to check collision
ok
does ths mean i'd need 3d colliders?
Example, BoxCast. Look at the last 2 optional parameters
it auto filters by Z
by default, it does not. But if you use the optional params, it does
Most casts are like that, and whenever you check collision, you could check depth
i still find it a bit confusing
i don’t understand the confusion
there are three ways to check for collision in code
you use Cast methods (Raycast, BoxCast, etc), Overlap methods (OverlapBoxAll), and collision callbacks (OnCollisionEnter2D)
in all of them, check that what you hit is in a specific range of Z
Cast can let you filter automatically
Overlap also lets you filter automatically
Where does the confusion start?
like how the cast is used
Ohhh- it's a method you would use for detecting collisions before moving something typically
you use casts to check collision outside of physics update
eg if I need to know if my character is on top of ground right now (this frame), I want to probabably Cast down
OnCollisionEnter etc happen after physics update
It might help to understand casts in general
The most basic form are Raycasts, which you might know from "hitscan" in shooters. Since just a line is a bit restrictive, we have shapes we can cast as well (Boxes, Circles, Spheres, etc).
They're just ways of checking for colliders along a path
does this make sense?
this makes sense
if I CircleCast from (0,1) by (4,3) with a circle of radius 10, then I am basically checking the area that a circle of radius 10 covers as it moves from (0,1) to (4,3), and reporting back anything I hit along the way
casts also return other info like distance until the hit, contact normals, etc
im kind of getting it now
but how would this change whether two objects collide or not?
So if my character has a BoxCollider2D, and I want to see if there is ground in the 0.1 units below him, then I will BoxCast a box of his shape by 0.1 units down. And then I will look through the hits to see if there was ground anywhere there
this should only influence dynamic rigidbodies
i think you’d need to check with someone to see how to fuck with the interaction between Z depth and Box2D (unity’s 2D physics engine)
do you have dynamic rigidbodies?
yes
then you’ll need to do some digging to see if there are settings for Z in the hitbox
ok
you’re basically looking for 2D with a Z axis like Link to the Past
i would lead with that
i don't think there are settings for z, changing the players z value didn't change what it collided with
how do i share a script code?
and , because it's a rigidbody 2d the rigidbody's position is only vector2
you type this (`) 3 times then cs
//your code here
unless it's too big then you can put it in a paste website and post the link 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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
okey
ill explain what im trying to do
im trying to do a basic movement set with a dash and a double jump
but i run into some issues
it normaly has to do with looking left side
whenever i dash to the right the dash works just fine but if i try to do it to the left then the speed is lowered to base speed
also i need to have a special movement codeline inside the if (GetKeyDown(KeyCode.A))
because either way it wont work
if someone can help me he would be a life saver
been trying to correct the problems for nearly 3 hours
it means "run the annotated static method when the player starts"
first you could probs change this
if (horizontal == 1)
{
rb2d.velocity = new Vector2(dashingPower * 3, 0f);
}
if (horizontal == -1)
rb2d.velocity = new Vector2(dashingPower * -3, 0f);
if (horizontal == 0)
{
rb2d.velocity = new Vector2(dashingPower * 0, 0f);
}
to this
rb2d.velocity = new Vector2(dashingPower * (3 * horizontal), 0f);
im just looking at the rest of it
do you have a screenshot of your game?
if (Input.GetKey(KeyCode.A) )
{
horizontal = -1;
rb2d.velocity = new Vector2(-1 * movementSpeed, rb2d.velocity.y);
}
else
{
horizontal = 0;
}
if (Input.GetKey(KeyCode.D))
{
horizontal = 1;
}
else
{
horizontal = 0;
}
take a look at this bit. what do you think this is doing?
i had it like that before but then it didnt dash correctly left side
stating wich direction the player is or should go
is it though?
if you are holding A, what is the value of horizontal after that code has run?
you weren't having any issues with JSONUtility, you got null because you probably simply had an ordinary typo. like you probably wrote JSONUtility.FromJSON<ErrorResponse2> when you meant JSONUtility.FromJSON<ErrorResponse1>()
were the brackets correct?
-1?
look again
srry english isnt my main language what is a bracket?
() these things
Why? dynamic only worked in the editor not in the build
im looking at it and still think that its -1 but if its not then i guess its 0
ah cool
i think so yes
these are curly brackets or braces{} these are sqaure brackets[]
if you are holding A but not D then horizontal will be 0
maybe, idk
it was like these rb2d.velocity = new Vector2(horizontal * movementSpeed, rb2d.velocity.y);
can you also use that in ScriptableObjects?
let me check 1 sec
yeah you dont need so amny elses
remove lines 51 through 53 and it will work the way you expect
you can have if, else if then else
maybe, idk
i had it like this before
so instead of if it would just be a math equation with the horizontal float choosing its direction
look at this
does anyone know if dotween removed SpriteRenderer.DoColor? I had this intro scene i've used for my games but now it suddenly started giving me this error even tho i didn't changed anything
since you have 2 seperate if statements
what does having 2 separate if statements do?
then if 1 isnt true then horizontal will be 0
oh
now i see it
holy
then what can i do to change that?
remove 1 of the else?
well no
if (Input.GetKey(KeyCode.A) )
{
horizontal = -1;
rb2d.velocity = new Vector2(-1 * movementSpeed, rb2d.velocity.y);
}
else
{
horizontal = 0;
}
if (Input.GetKey(KeyCode.D))
{
horizontal = 1;
}
else
{
horizontal = 0;
}
change it to this
if (Input.GetKey(KeyCode.A) )
{
horizontal = -1;
rb2d.velocity = new Vector2(-1 * movementSpeed, rb2d.velocity.y);
}
else if (Input.GetKey(KeyCode.D))
{
horizontal = 1;
}
else
{
horizontal = 0;
}
so then i can also delete the rb2d.velocity = new Vector2(-1 * movementSpeed, rb2d.velocity.y);
right?
OMG
YOU ARE GOD
i just saw it
kk good luck
nice
you made my day
yw
ty!
rb2d.velocity = new Vector2(dashingPower * horizontal * 1.7f, 0f);
changed that big part to this
and now it works
well it worked before but now its a cleaner code
yeah
i guess I’m confused why Box2D has many functions to deal with depth of Z, but there don’t seem to be any Z-related settings for the physics step
hi I have written a coroutine for an animation I want and I want to make a script that allows it to run in one direction when a button is clicked and another when anothe button is clicked?
does anyone have some intuition on how to do this
Pass in a parameter to indicate the direction
It could be a vector or even just an int (-1 or 1)
{
offset = offset * direction;
float elapsedTime = 0f;
var startingPosition = phoneHolder.transform.position;
var endingPosition = phoneHolder.transform.position = new Vector3(0, offset, 0);
while(elapsedTime < duration && buttonOperation)
{
float t = elapsedTime/duration;
t = animationCurve.Evaluate(t);
phoneHolder.transform.position = Vector3.Lerp(startingPosition, endingPosition, t);
elapsedTime += Time.deltaTime;
yield return null;
}
}
// correct now how can you do this
void Start()
{
StartCoroutine(TranslateModels(animationDuration));
flipButton.onClick.AddListener(delegate {
flipButtonClicked = true;
foldButtonClicked = false;
});
foldButton.onClick.AddListener(delegate{
foldButtonClicked = true;
flipButtonClicked = false;
});
}
I have this so far
then I tried before to just call StartCorotuine in the delegates with the different directions
but then it isn't smooth and happens instantly rather than executing over frames
I made this as well and tried another approach where I wait for one of the buttons to be pressed
{
while (true)
{
while(!flipButton && !foldButton)
{
buttonOperation = false;
yield return null;
}
buttonOperation = true;
yield return null;
}
}```
This looks busted
Did you mean + here?
Almost certainly
ok that was definitely jank but now when I just start the coroutines they dont even move
{
offset = offset * direction;
float elapsedTime = 0f;
var startingPosition = phoneHolder.transform.position;
var endingPosition = phoneHolder.transform.position + new Vector3(0, offset, 0);
while(elapsedTime < duration)
{
float t = elapsedTime/duration;
t = animationCurve.Evaluate(t);
phoneHolder.transform.position = Vector3.Lerp(startingPosition, endingPosition, t);
elapsedTime += Time.deltaTime;
yield return null;
}
}
void Start()
{
flipButton.onClick.AddListener(delegate {
StartCoroutine(TranslateModels(2f, 1f));
});
foldButton.onClick.AddListener(delegate{
StartCoroutine(TranslateModels(2f, -1f));
});
}```
my suspicion was that if you tried to interrupt it by clicking the other button then it would break because the coroutine would be restart however it not even running is not expected
What direction are you passing in
1f and -1f as parameters and I made offset serializable
unless inspector reset it to zero
in that case id have bruh moment
Hey guys if I have a delegate in script A that calls a function from script B that uses a variable in script B, why do I not get a null reference error when I delete script B and call the delegate? Does it remember the last value used?
hey gang, im once again puzzled by how unity rules work. i have this object:
knight_wooden has a mesh collider and an Enemy tag
weak_spot has another mesh collider and an Enemy_Weak_Spot tag
like so
when i hit the enemy and log the raycast hit tag i always get enemy tag
any way to get around this?
i want to be able to shoot the knight mesh and do one thing but if i hit the head i do something else, im trying to achieve this by getting the tag of the mesh that the raycast is hitting
Hello , I have a weird issue with my script
as you can see when I am shooting on an other player, the game of the other player receive a message to say that he has been hit, when he receive a message he verify the form of the message to see what kind of message it is (if it's a message of the position of a player, if it's damage that receive a player or if it's a player that disconected ) but the problem is that when he receive a damage message, the script see that it's a damage message because it's starting with "(" and ending with "#" but the script sometime analyse the wrong message because as you can see it sometime analyze a coordinate message instead of the demage message so it send me an error. It's like if the script receive message so fast and the computer so slow that when it's see the message it make the verification of what kind of message is it and directly switch to an other message that bypass the verification. Do you know how I can solve this issue ?
Does your knight has a Rigidbody ?
Use a buffer ? Also, if you use udp you might have message that are not sent are received not in the good order.
it does yeah
Then, it is the tag of the rigidbody and not the tag of the collider
oooh ok, i think i know how to fix it then
yea, got it
thank you! 
yes I know with UDP but how I can be sure that people receive all important message as if they take damage while using UDP ?
Use a real network framework like photon or Netcode for GameObject and you wont even need to think about it.
no I don't want because I already try them and it was so hard for me to understand and to use them whereas here by doing every thing myself I unterstand almost everything and I it's to much valuable because I learn a lot of usefull thing that I would have never learn with other framework 😁
anyone have a good way to prompt the user to download a text file with the operating system's native file explorer?
Basically I want players to have the option to save a certain string as a text file wherever they'd like
My friend, this is the first and worst mistaken that every programmer does. I know it is harder to work with something else, but believe me when I say that you are going to be more productive by using what has already been proven. It would be even more valuable knowing how to use the other framework.
You are still free to do what you want, however note that is way of thinking is in almost every case wrong,
of course It would be better to use those framework right now and will permit me to gain a lot of time , but even if my script and my work is not as good and as clean as those framework I feel like maybe later I would need this knowledge on something else than unity. also I know that by using those framework I would give up way early because i won't be patient anought to learn all that stuff while here it's been 3months that I am working on my multiplayer and even if it's not going that fast i'm still motivated because I'm proud of all the achivement I made by myself
What is more import for you:
- Make a game
- Learn about network
make a game that give me a lot of knowledge about Network 😂
Then you are going to do neither efficiently.
Hey so RaycastHit2D can implicitly be converted to a bool to check if it actually stored a hit. What's the equivalent for the normal RaycastHit?
check its .collider property for null. that's all the implicit cast to bool for RaycastHit2D is doing
I thought so. Wonder why this isn't available for RaycastHit.
maybe but as we say in french " rien ne sert de courir , il faut partir à point" 😆
well Physics.Raycast returns a bool whereas Physics2D.Raycast returns a RaycastHit2D
I know. I'm saying it's odd that an implicit conversion was defined for the RaycastHit2D structure and not also RaycastHit.
and the reason for that is likely because of what i just pointed out
It's because Raycast already returns a bool... why do the implicit conversions when that is the case?
Ah I see what you mean. Guess it's an artifact of decisions made 15+ years ago. And when they got around to implementing the 2D versions they just returned the data structure for simplicity.
Can't define implicit operators outside the class, so an extension method will have to do :/
public static bool DidHit(this in RaycastHit hitInfo)
{
return hitInfo.collider != null;
}
that's what prompted this :p
2D and 3D are ~just~ different enough to configure you from time to time
Yeah I just arrived lmao
Naming for properties in ContactPoint and ContactPoint2D are awfully inconsistent, and confusing when you try to compare the property names between the two types
Hello, is there a way to determine at Unity Gaming Services whether a player is an admin or a normal user?
no
Hi, can anyone help with issues about sound recording from device? I used MeltySynth to play a soundfont and used NAudio to record it. The issue is that although it can play the sound, it doesn't record the sound it play but the environment sound instead.
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Tilemaps;
public class BuildMenu : MonoBehaviour
{
public bool inBuildMode;
public Tilemap tilemap;
public TileBase tileToPlace;
public Camera mainCamera;
public AudioSource placeSound;
void Update()
{
if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject() && inBuildMode)
{
Vector3 mousePosition = mainCamera.ScreenToWorldPoint(Input.mousePosition);
Vector3Int cellPosition = tilemap.WorldToCell(mousePosition);
if (tileToPlace != null)
{
tilemap.SetTile(cellPosition, tileToPlace);
placeSound.Play();
}
}
}
}
``` Script for building with tiles, this works on 1920x1080 but not any other resolution
On other resolutions it just places it way away from the cursor, not sure how to fix it
Is it screentoworld method? Figure out exactly the method giving bad values.
the mouseposition variable is just not the same with different resolutions
are you using Orthographic or Prospective cam
orthographic
ohh
Sorry, it's orthographic. I have two cameras, I display the orthographic player camera (the one I'm getting the values from for this script) in a render texture
the other camera which isn't relevant is perspective, so I got confused for a second
hmm try Vector2 mousePosition = mainCamera.ScreenToWorldPoint(Input.mousePosition);
Didn't change anything
When I did the print line for the mouseposition variable, the Z value didn't change depending on resolution
it was the other ones that did
oh you changed it to ortho nvm lol
Thats such an interesting method for 3d for having no depth parameter
Oh wait your mouse has depth ah
Still what
Anyway, a bandaid if you can't figure it out is just use a large collider and specify the space
Then use a raycast for the point
I'm not familiar with how a camera will behave if it's not being used to draw to the screen.
point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));```
Is the example btw
like, what does it do for ScreenToWorldPoint if the camera isn't literally rendering to the screen?
Imput.mousePosition doesn't have depth so it draws it directly at the camera I guess?
This would be necessary for a perspective camera.
Ah, ok I see.
not sure why it works for 1920x1080 if it's a problem with the way the cameras are set up lol
perhaps something coincidentally lines up
With no target texture, the camera uses the screen size to determine world-to-screen pos. With the render texture, it'll use the render texture's width/height instead. If you then try and use that pos on the screen, there'll be a mismatch.
What is the size of the render texture?
Ah, 1920x1080
there you go
So what are you trying to do here? Figure out where on the render texture you clicked?
Yes
If you know where the bottom left and top right corners are, you can do it pretty easily
if you compute the screen positions of the corners, you could do Mathf.InverseLerp(bottomCorner.x, topCorner.x, inputX) to get a value between 0 and 1
0 on the left, 1 on the right
I feel like there should be a snappier way to do this, but you are just drawing this render texture onto an arbitrary chunk of your screen
you can turn off warnings project-wide with a file called csc.rsp
I've kind of struggled to find information about it
-nowarn:8524
this turns off warning 8524 entirely, for example
If you want to turn off individual instances of warnings, then I think you can add something to the source files
I think this is what you want. I actually need to look into this myself more..
There's supposed to be a suppress keyword that only turns off the warning for one line
When I first made the system the render texture gameobject only took up a percentage before i realized it worked better this way, but 90% of the game is solely done through the main camera with the UI being the game, and the top-down second camera is just used when you open a specific menu, so it's kind of strange lol. I'm not used to dealing with systems like this.
But I guess it's introduce in a later version of C#
100% a better way to go about it probably, I'm just dumb 
You need to know how large the thing you're displaying the render texture with is
I'm testing around with compute shaders, and I just started getting this error and I can't figure out what's causing it.
CircleTracingVisualization.compute: Kernel at index (0) is invalid
UnityEngine.StackTraceUtility:ExtractStackTrace ()
This is the line it's upset about.
computeShader.Dispatch(0, renderTexture.width / 8, renderTexture.height / 8, 1);
The compute shader only has 1 kernel, and this wasn't previously giving an error. Any ideas?
Nevermind, there was a compile error that wasn't showing up in visual studio.
Kinda wondering if I have completely the wrong understanding of UI Toolkit paradigms. I'm about to write a script where in Start() I use .Q() to grab a bunch of references and do things like set button callbacks. With the legacy UI system, I would be writing a callback and setting it as the action for a button in the editor. Am I doing this wrong?
MainUiDocument.rootVisualElement.Q<Button>("Buildings").clicked += OnBuildingsClicked;
There's going to be a lot of this sort of statement with this pattern
hello, I am trying to change the value of the sliders to match the values in the StatsHandler script. Sliders get the correct maxValues but not the correct normal values (so far tested with my HP slider as it is my point of focus). I have looked through documentation, forums, QnAs but I seem to find out my approach is correct. The values are correctly assigned, no errors. The script just won't change the values through Slider.value
Here are the most relevant scripts:
https://pastebin.com/8UL1Ssqm (Sliders Script)
https://pastebin.com/XhRWRtsi (StatsHandler script)
is this a "this works on my computer" due to a drunk Unity or me done goofed up scenario?
You have this:
changeSliderValue = EnemyAssetHandler.enemyHandler.isDamaged;
in Start, which only runs once in the lifetime of the GameObject
I don't see anywhere that changeSliderValue is changed other than that
using UnityEngine;
public class EnemyAssetHandler : MonoBehaviour
{
private static EnemyAssetHandler _enemyHandler;
public static EnemyAssetHandler enemyHandler {
get
{
if (_enemyHandler == null)
{
_enemyHandler = new EnemyAssetHandler();
}
return _enemyHandler;
}
}
public bool isDamaged;
}
sorry for the paste. Thats the relevant script all it's calculations are handled eslewhere
So this updates isDamaged, but that won't affect changeSliderValue
changeSliderValue = EnemyAssetHandler.enemyHandler.isDamaged;
And your update in the Sliders script is behind the condition of changeSliderValue being true
change slider value isn't relevant
Yes, this only updates the bool ONCE. It is not linked later
Oh... how is it not?
Don't you want to change the slider value?
the sliders don't initiate correctly from the start
Ohhhh, ok. Gotcha. Ok I misunderstood, sorry
The start HP is 1000, and so is max, but it starts with a slider value of 1
Reverse your code. You set max value AFTER the value
set max value first, then the value
I think default max is 1
I am so dumb
makes so much sense now. Slider can't go above max
I feel embarassed
No worries at all!
also, thank you for the debug, will take a look if it is really the case
Anyone have any issues with RaycastAll sometimes skipping an object?
i have an object at pos [0,0] i want it to go to a random position at 1 distance from is current position (example : [0.5,0.5] , [0.9,0.1]) how do i do that.
so i shoudl do
pos [Random.Range(0,1),Random.Range(0,1)]
but i could return pos[0.9,0.9] which ain't at 1 distance from the current pos
in 3d raycasts will skip the object they are spawned within. If this isnt your issue, then you should specify more of your setup to get proper help
You want* to do it for each axis
i'm not sure i understand here...? may you explain further?
Unless there's a vector3 random range which I forget
no for a vec2
(0.5, 0.5) is not 1 distance away from (0, 0). you should use this
https://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html
Oh, vec2, then random the axis of both with your range.
Ah, you want an area of a distance. Then yeah unit circle then
oh yea
Sometimes itll hit when spraying but most of the time it misses some objects.
RaycastHit[] hitResults = new RaycastHit[resultAmount];
int hits = Physics.RaycastNonAlloc(ray, hitResults, Mathf.Infinity, shootableLayer, QueryTriggerInteraction.Collide);
for (int i = 0; i < hits; i++)
{
RaycastHit _hit = hitResults[i];
if(!_hit.collider.isTrigger)
allHits.Add(_hit);
Debug.DrawLine(ray.origin, _hit.point, Color.magenta, 5f);
Debug.Log(_hit.collider);
}
allHits = allHits.OrderBy(hit => (hit.point - ray.origin).sqrMagnitude).ToList();```
what is your resultAmount set to? maybe it is "missing" because theres not enough space in the array but im not sure what this screenshot is supposed to show tbh
its set at 10, but its mainly missing the first one so there shouldnt even be a reason it would miss, unless the hits arent by order ?
its missing the column and hitting the floor behind it, then gizmos are showing start to end
yes there is no guaranteed order for this
wow.... just set it to 20 and it works now, is there anyway around it? as i didnt want a shotgun to to have a high hit result since im not sure how performant it is if its getting more results.
id be more concerned about why there are 10 shootable things in one line in the first place considering that screenshot shows a floor and a wall
well i actually had it at 2, for the minigun since it shoots more then one bullet at once, so my apologies
consider things like if you need it on QueryTriggerInteraction.Collide, since it doesnt really make sense for a trigger to get hit by a bullet. And how many things are on the shootableLayer
ah, i wouldnt be entirely concerned at having it at 10 vs 20 honestly. I assume it'll be rare that you'll actually get 20 results in one shot
float angle = Random.Range(0.0f, 360.0f);
float radians = Mathf.Deg2Rad * angle;
float radius = 1;
float x = center + radius * Mathf.Cos(radians);
float y = center + radius * Mathf.Sin(radians);```
That should work too
but it shouldnt be a common case that it goes near the limit
yea i did this so i can check if it is a trigger if so check if its a smoke grenade as i have responsive smoke and dont want to spawn a interactive projectile every shot unless it hits smoke
thanks !! you helped alot lol i was going crazy.
float angle = 2*Mathf.PI;
float radians = Mathf.Deg2Rad * angle;
float radius = Random.Range(0, 1);
float x = center + radius * Mathf.Cos(radians);
float y = center + radius * Mathf.Sin(radians);```
that too (probably better point sampling here, right)
How is it that there are more than 10 shootable objects though? I can only see a few at best on that screenshot
it was set at 2 not 10, if the gun shot more then 1 bullet at once i set it at 2, i didnt realize lol
Ah, ok.
yea you'll probably need to change that logic so it still detects everything shootable and then manually choose the closest 2
🤔 or possibly a single raycast followed by another after the first hits.. probably bad for massive piercing projectiles
yea i did this at first but it was quite messy and was only able to go through one wall basically lol, 3 raycast for one wall not sure how expensive that gets as you multiply it
Any way to get a stack trace on these?
Ah, nvm. Seems to be due to a bad interaction between gizmos and UI. Closing and reopening the game tab solved it.
Hello, everyone! Not strictly a shader issue: I'm trying to think of a way to get a semi-random number from an object's position such that it can vary wildly from another object with a position that's just slightly different. The purpose of this is to seed a vertex shader so that near objects have different starts to their animations, while avoiding instancing. So far, I'm not getting satisfactory results. Does anyone have any ideas?
Edit: I know division is sloppy, but I'm trying to get a result.
Perhaps instead of the absolute position, divide out the decimals?
#archived-shaders
If this were c#, itd be easier to recommend but I dont know what shadergraph can do. In c# theres definitely many ways by just generating some number from the xyz and then using that as a value in some simple hashing algorithm
In future, switching to full stack traces may work (note that the same setting affects builds ): so be careful when switching it )
oooh, nice.
thanks
weird that a setting in that menu would change build :-S
Why does that window look so clean and sexy and not the windows xp sterilised white
Because 2023 menus use UI Toolkit and are searchable
for some reason my logging wasn't giving a stack trace in my project either
That's not a bad idea. What I have does work, but isn't getting different enough results between near objects. I might do something with modulo rather than division.
Yeah, shader graph mimics a subset of what a compute shader is capable of. The solution has to be fast. Noise is already expensive, so hashing is definitely out of the question. Mao actually had a good idea about dividing against decimal positions.
Hello, is it possible to make a method listen to two event Actions? So that it will only execute when both actions have been invoked?
No, you need to code that coordinated invocation yourself
You can look into async programming patterns to do such things
Thanks! 🙂
Hello, I am using Unity Cloud Save to save my Player Data. So I have a Cloud Manager that uses async programming to Initialize and Get Player Data from the Cloud in its Awake() method. But now I have another manager that will get the data from the Cloud Manager, but the thing is the other Manager is already trying to get the Data even when Cloud Manager is not yet done with loading the Player Data. How should I approach this problem? It would also be cool if you can give examples with code
both are Singletons btw
i dont know too much about shader stuff so I cant comment on the efficiency of anything. Although i wasnt specifically referring to noise. Hashing can be very simple, like some value % n. A good hashing functions is by definition supposed to be very efficient. I cant imagine that doing division multiple times is gonna be any more efficient
does Debug.Log get completely stripped from builds?
do i have to compile as RELEASE for this
i have some code that is supposed to detect it the player is touching the target and display it on the console but it only work when the player is on top of the target and doesnt work if touching the side.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collidable : MonoBehaviour
{
public ContactFilter2D filter;
private BoxCollider2D boxCollider;
private Collider2D[] hits = new Collider2D[10];
protected virtual void Start()
{
boxCollider = GetComponent<BoxCollider2D>();
}
protected virtual void Update()
{
//collision
boxCollider.Overlap(filter, hits);
for (int i = 0; i < hits.Length; i++)
{
if (hits[i] == null)
continue;
OnCollide(hits[i]);
//clean up array
hits[i] = null;
}
}
protected virtual void OnCollide(Collider2D coll)
{
Debug.Log(coll.name);
}
}
Overlap wouldn't detect anything, since the object wouldn't be overlapping. It would get pushed out of the collision during the physics step, so during the update it's either didn't collide yet, or already got pushed out of the collision.
Why not use OnCollisionEnter anyways?
Could someone help me with an editor problem?
So I got rooms. KoboldRoom, KoboldLootRoom, KoboldBossRoom all inheriting from RoomType So I can call the same methods but with diffrent changes to the method
now I save an array off RoomType
and what I want is that when you add a new value to that array it gives you the option of all the existing RoomTypes
And when selecting the roomtype you want it will then show the properties of that roomtype
Thanks that helps alot
hey all, I do have a simple question. It's more like a math question really. so:
I do have a Stat which has flat and percent modifiers. im confused of order to get the modified value.
modifiedValue = (baseValue + flatModifiers) * percentModifiers;
or
modifiedValue = (baseValue * percentModifiers) + flatModifiers;
which will result in different stat values. what is the general way in this?
or would it result in different results, fck now I wrote it down, im more confused.
so let's say base is 100 and I have +15 flat modifier on top of that i have %10 increase.
in first formula it'd result in ~126 rounded down.
second one would be 125.
It depends on which one you want to have. In the first case the flat mod is affected by percent mod. In the second it doesn't.🤷♂️
since it's flat, I think it makes more sense that it doesnt I guess.
usually games have flat modifiers apply first
at least good games ;)
so I'm more of a fan of the top calculation
interesting point.
It depends on what those modifiers are and how they're communicated to the player. If the player picks up a bonus effect that does +15 damage, they might wonder why it does +16 damage instead. But if a character has a trait that gives them 10% damage boost, players probably expect it to appy to flat modifiers as well
You definitely want flat first, than percent. Let's say you have 100 base and 900 flat bonus, your player deals 1000 damage and picks up 10% damage increase, he would except to deal 10% more damage( 1100 damage), but with the first calculation it would only be 1% (1010)
Can always add like a true flat modifier that wouldn't be increased by other modifiers, because there could be items or abilities that have a gimmick of just adding a large flat amount of damage.
It really depends on the formula and it's intent. Some games have complex formulas that include both a flat bonus before multiplier and a flat bonus after.
good points. @mellow sigil I didnt like getting 126 after +15 flat and %10 increase either. maybe I should communicate like percents only adds to base in UI? stats are important because there would be items, status effects etc.
@cosmic rain could you give an example by numbers?
Whatever you do, just make sure it's consistent
i need to load up some rpg games and equip items that do both I guess.
intent is to show player both base and total modifiers (but not types.)
item or status effects abilities etc would show percents or flats separately
Take damage in Pokemon for example. It includes several flat bonuses and multipliers at different positions:
https://m.bulbapedia.bulbagarden.net/wiki/Damage
maybe I should separate what stats can get percents then. because it doesnt really fit my design. for example, 'Speed' stat determines turn order which I'd never modify it by percent. But health or damage may be modified by percent.
in that first formula would work better since you get more health or damage (which what player wants anyway.)
darkest dungeon does just that, now i've seen modding files.
Right now I have it so that it will animate OpenDoor() of a specific GameObject.
[SerializeField] private GameObject bossDoor;
private void Update()
{
Door door = bossDoor.GetComponent<Door>();
door.OpenDoor();
}
Is it possible to make it so that I have a list of GameObjects I animate?
[SerializeField] private List<GameObject> bossDoor;
Ah, this is super frustrating. I have a sequence that animates when my client opens in Unity. It uses a Unity Animator component to do that.
If I take focus away from the game window while the animation is running and then click back to the game window, the animation clip starts over instead of it keep on going.
How do I help this? I read that you could turn on "Apply Root Motion" on the animator component to fix it, but that didn't change anything.
I would not expect toggling root motion to have any effect.
I don't really know much about the animators inner workings.
But I am really running out of ideas on how to help this
How do you trigger the animation?
"when my client opens" is a little ambiguous
like, when the game starts?
When the client starts up, it sets a trigger on an animator and then enables it.
The trigger is evaluated to run the animation and then it starts going.
does it in a build as well?
Does this problem happen in the editor, or only in a built game?
Can you show us the script that sets the trigger?
But I need to debug things as I go, and I can't because the animator keeps resetting the last run clip or state
Oh, I see what you're talking about
If you do anything that changes how the animator controller works, the animator gets reset
That's my understanding, at least.
I can't show everything as it's a commercial project
This runs when the client starts up
It will transition into the BackgroundAnim state as expected
And then if I take focus away from the Game window and refocus the Game Window
That animation clip will just start over
And this isn't unique behaviour to that clip
This is a problem, because I have an editor tool that I need to give focus at times to write some things in and press some buttons
And when I give focus back to the Game window, it just reruns whatever animation was last run.
Which means there is state I can't actually work with...because the animation resets that state 😅
Any ideas?
I remember seeing this kind of thing when working on my VRChat avatar -- I'm pretty sure hitting undo or redo would always make my animator reset
It looks like the default state should be "Holding State", though.
Is the transition into BackgroundAnim getting taken?
It transitions to the state as I'd expect.
keep the animator window open while you're doing this (with the parameter list visible, too)
Every time you refocus the game window, I mean
I have done that. I can make a gif and show you.
So the problem is that it keeps re-entering the BackgroundAnim state, correct?
Here you see what happens to the Anim state as I take away focus and give it back to the Game Window
Every time the focus is given back, the anim resets.
Ah, okay, so it's not what I was expecting -- it's not going through Holding State at all
Does it happen with every animator?
Maybe you can attach a https://docs.unity3d.com/Manual/StateMachineBehaviours.html to the state to get some more information out, at least.
you can see if the state is being entered, or if the time is just getting reset to 0
If the state is being entered, you could get a stack trace by logging something
Which might tell you whose fault this is
Thing is, I already know it's Unity.
No scripts are being used to do what this Anim does.
I can tell that the entire state of the Animator resets, in fact.
There is most likely a call to https://docs.unity3d.com/ScriptReference/Animator.WriteDefaultValues.html somewhere
It was introduced around unity 2021
What version are you on ?
I am using Unity 2021.3
2021.3 should have the flag
but it's also present in 2021.3 .
missing using statement? I doubt it, but might as well check
I was surprised that you weren't winding up in the default state. But I'm not too familiar with the gory details of the animator.
The Animator variable wouldnt be reconized
ah, fair
are you perhaps on a really old patch for 2021.3?
If it is the case, being on an old patch, you might want to update it.
yeah wrong reply lol my bad
I don't know what part of this is working.
public class AnimatorTest : MonoBehaviour
{
public void Awake()
{
GetComponent<Animator>().keepAnimatorControllerStateOnDisable = true;
}
public void OnDisable()
{
GetComponent<Animator>().WriteDefaultValues();
}
}
But it seems like it does work
I never knew about those settings. Sounds useful.
this threw me off. i should go experiment with that some more
All I know is that the Animator is kind of archaic compared to most of the other unity systems
And that programmatically it's not fun to deal with
They are working on a new "Animator" as far as I know
Because, you know, you want a 3rd system.
I've used Animancer some and it's really nice
You make your animations into reusable data
And can just apply it to anything that can animate
No more "recreating the exact same state machine across multiple things"
Just use the same animation dataset
would that work for sprites?
I'm a huge fan of Animancer
It also prompted me to start using more state machines
I am unsure, but I would guess yes.
As long as you can express the animation as self-contained data, then I don't see why not
I seem to have found most of what I'd be looking for. There is a weird quirk going on with an animator I'm not quite sure why, but I can probably figure it out. There are still some animators that, despite the script, still reset when I refocus the game window.
Thanks so far @heady iris @steady moat
The gist is that it replaces the Animator Controller state machine with its own system.
ah
It just plays animation clips at the end of the day.
oh
It's fantastic. I'm working on a Soulslike game right now.
It has much nicer programmatical access to the animator though
Each weapon has a moveset. That moveset contains animancer clips.
I can play the clips from the weapon on the player and it just ~works~
Animancer also has fantastic documentation with both worked examples and plain reference material.
Also another wild Unity Moment™️
I have an Animator graph where no state is visible.
At all
You can't even delete the Any State, but yet the animator graph is vacant
maybe it's just scrolled way off? hitting A will focus the view
Nope.
All gone
But I restarted the Animator window and they reappeared.
If you press Ctrl + A while in the Animator window it will focus the states you have within the screen space given
Close Unity.
Sometimes, the Animator is corrupted
this is fine
if two trigger colliders touch does it call on triggerenter 2d?
I believe so
Only if there is at least 1 rigidbody present
what? really?
huh
so thats why
also im getting an error in visual studio saying The type or namespace name 'PlayerHeightEntity' could not be found (are you missing a using directive or an assembly reference?). the error isn't appearing in unity so its probs just vsc acting up
Try and rebuild in VS
well
did you define playerheightentity?
how to?
Build->Rebuild
has unity reloaded since you created the script that defines that class?
yeah
it needs to see the new file so that it can update your .csproj files
ok the error's gone now
i just closed the file and reopened from unity
it was vsc being weird
also about this, i put a rigidbody on one of the objects with a triggercollider but the code doesn't seem to be being reached
public void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Platform Checker"))
{
Debug.Log("platform checked");
GetComponentInChildren<PlatformChecker>().onPlatform = true;
}
}
thats the code
not getting reached even though i have something with that tag
please go to #💻┃code-beginner , check the pinned messages
there's a link for troubleshooting physics messages
k ty
Hello, is there any way I can visualize the FoV of the Camera in Unity? In a multiplayer VR setting, I want to make my FoV visible to other users.
thanks it was because i didnt have any non-static rigidbodies
but now im getting a null reference exception error at this line
GetComponent<PlatformChecker>().onPlatform = true;
even though the only thing with that tag definitely does have a PlatformChecker component on it
camera.fieldOfView to get the FoV, then put that value into an object that can display it in the world
That checks yourself, did you mean to do that on the Collider2D other parameter (the collider you collided with)?
I have a problem with unity... I have my main editior set as VSCode (or so I want). Whenever I open unity, it preselects the editor code.cmd (internal), which is NOT my VS Code. My VS Code editor in the External Script Editor value is Visual Studio Code [1.81.3]. This causes a handful of issues as the "code.cmd" version does not open the project folder, but just the script, resulting in no autocompletio, debugging, or changing my working script from the editor. Example photos:
Any help appreciated
I finally have the first prototype for my new physics engine. >1000 lines of complex code with zero testing. Can’t wait to watch it blow up
this change happens every time I open unity and it's annoying because I have to change it back to my VS code
nvm fixed it after weeks of troubleshooting. Always when you ask for help, the problem magically disappears. Sorry for the trouble
Whenever I utilize Application.focusChanged it appears to not register the first focusChanged event.
i.e. I can subscribe to the event, then I would have to unfocus unity and refocus it before it starts reporting the proper focus state.
Is this a "yeah, it has always been like that; work around it" or am I missing something here?
why would subscribing to the event also cause it to fire?
also, in the editor, focus is complicated
It doesn't fire until the client loses and regains focus
Then it starts reporting true/false for every focus change
i think you should try printing the focus state, wherever it is, before you subscribe
so that you can understand what the editor focus state is
at least what it's saying it is
the player has different behavior than the editor for focus state
imo you should not build functionality around focus state
really depends on the game. the best thing to do is watch for inputs and if it's been idle for a short period of time, you are unfocused.
That's not relevant to the question though. You subscribe to an event then you expect it to fire on changes; not just from the second or third change and on.
I agree that you don't make a game based on focus status, but that's besides the point.
so you're saying the following sequence happens
- subscribe
- unfocus (no event raised)
- focus (no event raised)
- unfocus (event raised)
- focus (event raised)
Is this correct?
like i said you have to print the state
before you subscribe
so that your mental model of what's going on in the editor matches reality
the game may appear to be focused but it's not
or vice versa
Does it technically change anything or is it just for me to peruse?
i can't help you if you can't write a debug statement
i'm just repeating myself. the editor focus state is complicated. print it before you subscribe
I'm subscribing runtime, but you have me intrigued. What's the complicated part?
Not taking the piss btw, I just want to know the quirks
I gotta go sorry
Alright, thanks for chiming in. I'll have a look at it
So the first focus does fire?
Client has focus.
Subscribe.
Let it unfocus. No event fires.
That doesn't answer my question.
Do you get an event when you re-focus the application after doing that?
That'd be my "off by one" I need to doublecheck.
The first unfocus after subscribing definitely doesn't fire though.
If the event fires correctly on the first re-focus, that implies the application started out in an unfocused state
- subscribe
- unfocus (no event raised)
- focus (event raised)
- unfocus (event raised)
- focus (event raised)
The weird thing is that I'm subscribing from within the client.
It definitely has focus, per definition.
As in, on the windows taskbar the client is highligted as active. And I'm clicking a GUI button.
Is there a TransformPoint for rigidbodies? I am currently changing rigidbody positions in fixed update and also need to use TransformPoint at the same time, but
transform.position != rigidbody.position
right after doing rigidbody.position = ...
Not that I'm aware of. The rigidbody doesn't have its own transform
Is there anywhere where I could get the TransformPoint code and re-implement it for the rigidbody?
I am thinking you could get the Matrix4x4 from the Transform, then modify it to account for the change in position
Yeah, I think I found something too that will help https://stackoverflow.com/questions/38675245/convert-from-local-coordinates-to-global-coordinates
You could then just multiply it with your point
alternatively, tbh
set the transform's position
do the math
put it back
you could also just create an empty object that you parent to yourself, and then set its position to the destination
you could do that once in Start and then keep it around
I've done something like that before.
can I serialize an entire gameobject into JSON? and If I can should I because that seems like a very inefficient way to readwrite data to a server and such
No and No

but Json will be faster than using a text file and telling the script to read a specific line I presume
not for the entire object of course, but just for some values
Json is text plus so probably not. But if you are sending data to a server it should really be in binary
hmmm
I would think it would be faster
more modular at least
why, more bytes == slower speeds
you're conflating two things
lets presume im doing the reading in a really, really, tremendously poor way
it'd probably be faster then
(I:E, I only read it once with the Json)
no
or if it's just a big blob of data that you must know a schema for to decode
imagine sending a Vector3 as three named floats, versus just packing the three floats into a 12 byte chunk and sending that
can the CS read and interpret bytes?
even csv is going to be faster than json
of course
how do you think we write binary serializers?
fair
oh well
ig I'll keep using this method then
and figure something else if it turns out the client runs at tremendously slow speeds
on a side note, if I wanted to store a database of some sorts, should I also not use Json for that?
if this is just a few lists of serializable objects, that sounds fine to me
no, definitely not
but if you really mean a database
then json is inappropriate, and you will need to use something like SQLite
I though SQL was a service not a format
Hmmm. SQL for Unity
well technically this sidenote is outside of unity
but I just thought I'd ask here because it was topical
yep but I bet you want to store things like Vector3's
I mean it was just going to be strings and ints
a small database
im not sure how many
but it would probably be ballpark 50-100 strings
oh
ig commas are faster than linebreaks then?
or something?
commas are faster than parsing field names and in a fixed format commas are all you need
so why would you ever use JSON then
so then one json file is probably also slower than having a different file for each object?
most definitely
cool
SQL is soo yesterday 😆
And you know why it is still popular, because it is fast and it works
json is high level readable language for human and can be used by reflection
but if you want compress and fast way to readwrite then you have to design your own syntax and parser
yeah they still have uses, but working with tables gets annoying lol
spoken like someone that does no data design
Performance is definitely not the only consideration. Im sure your user wont notice if you take 0.002 seconds to load a file once at start compared to 0.001 seconds for some other more efficient format
not sure what you mean, I've used SQL but I prefer document non-sql when possible
I was just thinking that doing more readwrites every frame on text would be slower than doing less readwrites every frame on Json
You wouldnt be writing to file every frame for anything
but what if i am
file io will be queued by your OS iirc
Then json vs anything else isnt your problem to be considering, the problem is that you've chosen to write every frame
fair
if you want to do IO intensive job, off load it from main thread if possible or use buffer temporarily stores the data that is needed to write to disk
The only real downside to json or plaintext is that the user can fairly easily edit it. If its in something else like binary or a database, its ever so slightly harder to edit that the average person probably wouldnt try editing it
caching can help with tons of reads
this may result in some very silly situations where whilst playing this game I go into the database and edit the position of my opponent
but eh
no one is going to play this anywyas
any lag may also be from the fact that my school wifi might not like me trying to host a local go server on it 💀
https://docs.unity.com/ugs/en-us/packages/com.unity.services.authentication/2.6/api/Unity.Services.Authentication.PlayerInfo How can I access that ? Sorry im pretty new at Unity Gaming Services
this is not something you should be worrying
yeah lol
If it's not multiplayer then meh let them do it. Onky a small percentage of the people that play will actually go look for the database, and not everyone will even know how to open it in the first place
yeah
well it would be multiplayer but like its not going to have an immense playerbase or whatever
I could always have a thing to check if they were edited and then give me the ip or client or whathaveyou
Is there a way to search in the hierarchy for active objects?
probably?
wdym ? its literally part of the Authentication Service
I think you could do like isActive:true or smth
PlayerInfo myplayerInfo = AuthenticationService.Instance.PlayerInfo;
obs you gotta login the user first
thanks!
I have a list of classes that is serialized in the inspector.
public List<EnumOption> enumOptions = new();
[Serializable]
public class EnumOption
{
public string name;
public List<OptionData> options;
public EnumOption(string name, List<OptionData> options)
{
this.name = name;
this.options = options;
}
}
When I click on the GUI Button in the inspector, one of the things that it does is removing some options from the TMP_Dropdown options.
So it removes previous options to find another, even if they might be the same.
The issue is that it removes them perfectly unless positions of items were changed in the Inspector. For example, when 0 and 1st items were replaced. This way it cannot remove them anymore, because it probably doesn't find the reference? But why?
foreach (OptionData optionData in options)
dropdown.options.Remove(optionData);
I have implemented Unity Auth System with Username and Password. What is the best way to save the username in the unity dashboard ?
what is order in layer but from the script?
like whats the script name for it
spritesortpoint
ok
wdym by saving the username?
But where is it saved ? Cloud Save ?
Or is it possible to save it in the Player details overview ?
found it, sortingOrder
its stored under the account, but the dashboard is very limited right now. It doesn't show any of that stuf
How do I save it ?
from PlayerInfo ? where do you want to save it
public string PlayerName() { return AuthenticationService.Instance.PlayerInfo.Username.ToString(); }
This is stored in the PlayerInfo but I dont see it in the Dashboard
well you can't change the dashboard , and idk what priority Unity has for that.
sadly, the only solution at the moment is to use your own dashboard of sort
OK, so when I want have it in the Dashboard I have to save it as Cloud Save or ?
the best you can do it is storing it as a file / string value inside Cloud save yeah , its a pain in the ass to do it like that too
not sure why Unity half assed this one
its a fairly easy thing to implement
best we can do is keep submitting feature requests
if they're gonna give us user accounts, they should at least give us something decent not half assed
Actually, I don't need it in the dashboard at the moment. I'll leave it as it is. But thanks for your help.
There is also no email verification. How did you do that ?
honestly. its crazy..
Lootlocker has that... even
mongodb has that
you would think someone at the meetings brought this up, and was probably thrown out the window
xD
no email feature though
So everyone can change password for everyone ?
Or do u have to Sign In to change password ?
the user must be signed in and you must request the user to enter their current password and new password, then call UpdatePasswordAsync. UpdatePasswordAsync keeps the user's authentication status, but all other signed in devices asks the user to sign back in.
its not a password reset feature
just changing current pass
hmm good question , I haven't seen anything about that
it does says User Accounts is Beta so lets hope it get fleshed out soon...
this is more like an Alpha stage
I think the idea rn is that mostly you'd want to use proper login/pass systems like Google n such
so if you need recovery account you're dealing with google and not unity
yes
I have it done with google
But I try to work only with Unity Services
but its kinda hard
agreed. again maybe keep sending feature requests and hope they see interest in it.
its a competitive I assume given the many already established systems like Google or Playfab n such
but it does tie in already with Unity perfectly so they have a major potential , hopefully not wasted.
also Unity Player Accounts is under MIT license which is nice
Code-Link was a nice feature they added though to Auth
@rigid island Do u know is there a way to sign people as admin ?
by admin in what sense ?
Im using ingame Console. And I want that only people who are admin can acess it
what is an easy way ?
Using credentials. You'll either need to use a server to verify or ship the key with the game in some way
hey guys im trying to make stairs that raise the players sprite renderer by a value depending on where they are on the stair but im struggling to figure out the math, can anyone help?
are you using tilemaps?
yes
You can add levels to your tilemap by using the Z coordinate, so things appear behind/infront of the player, if that is your problem
i have a whole fake height system made so im just trying to make it so that if the players is at a certain distance along the platform, the height level is raised by a certain amount based on the steepness of the platform
so if a player was halfway up some stairs, their y value would be increased by 0.5 if the steepness was 1
but if the the steepness was 2, and the player was halfway up some stairs, the players y value would be increased by 1
dont know how i would do that though, thats basically all im asking
the thing im having trouble with is detecting where the player is along the stairs
@spring creek Thx
Does anyone know how the force of the SpringJoint2D is calculated ? I know there is a built in method to get the force but I need to know the math behind it so that I can apply a constant force by changing the frequency depending on the objects mass and distance
im following a tutorial to make 2d game but my hitboxes arent really working, when i stand on top of the target they work fine but other angle this is the closes i can get.
here is the link to my player code:https://hatebin.com/qlfnapwboh
um using the unity spirte editor and i dont know if theres somthing to do with hitboxs in there
Here are my box collider settings:
your objects are incredibly small so you are seeing the normal contact offset
you need to change the Pixels Per Unit setting on your sprites so that they are correctly sized
when i click on a spite to change the ppu there are no setting am i clicking the wrong thing?
select the sprite sheet, not the individual sprites
since it is one texture sliced into multiple sprites the import settings will be on the texture
ah tysm it all works now but my player is very slow now, should i try to change my code or is there something else i should do
i found anther solution
i reverted back to my old settings and added an edge radius
not realy shure what it does but i think it acts as a trigger
hey 👋🏽
why would this only fire for the player but not for the npcs?
It can't find the Manager. collider.GetComponent<EntityManager>()
The collider is fine, i handle damage this way all the time. It's on the same gameobject like the Manager.
The player is checking the OTHER collider, which has EntityManager, whild the NPC is checking the player which I guess doesn't?
It's unclear which object that script is on.
Is it both? Only the player? Not sure
the script you see is attached to this gameobject:
A Rigidbody is required for OnTriggerEnter
actually no
oh most likely it counts the character controller as rigidbody right?
Check the chart at the bottom here
https://docs.unity3d.com/Manual/CollidersOverview.html
Not afaik but maybe?
cheers 🍺
it seems so, it's working on the player.
Fen has tested. OnTrigger runs with a character controller instead of a rigidbody
But NOT OnCollision
Which is replaced with the OnCharacterControllerHit or whatever it's called instead
thanks for clarification, always good here
That's weird
But good to know
Can't believe how poorly documented that stuff is
Yeah, it really suprised me when they said that.
I've been giving the wrong info for a while now 😂
Well TIL
not instead, they both work 👍🏽
What do you mean?
Your comment implies that OnTrigger only works with character controller? Sorry english is not my native language.
Oh. Sorry about that. No, I did not mean that
got ya 😄
It normally works with a Rigidbody. But it CAN work with a CharacterController as well
The former is well known, the latter was a surprise to me
Oh yeah I came upon that at a point and was scratching my head
Hey guys, I just updated from Visual Studio 2019 to Visual Studio 2022.
The autocomplete for Unity methods like Awake, Start and Update is not working. Any ideas?
(I have the Game dev with Unity Visual Studio package installed)
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
go over the steps again
Thanks, just did. No luck
you did all the steps? try regen project files button is in unity preferences where u selected vs
i'm making an inventory system. I have a basic store - equip scripts that work for player and npcs. Now I need the following:
The items process inputs and display huds differently based on type and whether it is equipped by player or enemy.
For example, a pistol equipped by player shoots on button down, but a charged gun shoots after a while on button up. Ammo count is displayed on screen.
Then for enemy, some ai gives similar instructions and item understands what to do. Ammo count is displayed on top of the enemy in the world.
any advice on this?
If you have the types how you want it, I'd assume you'd just want to check the type of the item and what entity is using it when equipping.
and then change the hud accordingly
I think the the cleanest way to achieve that would be to separate the code for input and the code for the weapons themself. In that way the weapon should only contain information about how the weapon functions, like ammo count, projectile type, cooldown and such stuff, but not about input related information like on which button press it shoots. Then the ai and the player can get different scripts which manage the weapons. For the input of the player you may want to write a general controller class which handles every weapon with the help of a third info class which contains stuff like if the weapon is automatic or semi-automatic or if the weapon shoot on button up or down; or you might use a different player controller class for every weapon.
It just would get more tricky with stuff like the charge time, because that would also affect animation of the weapon and in that way should be both present in the weapon for the ai and for the player, so maybe these properties should only be contained in the weapon. Then you might also need different ai controller scripts for different types of weapons.
so enemy equips item, controller class instance is created, ai input related info is passed there, then the controller class calls methods from item class. something like that?
Yeah, the item is in that way comparable to a real world object; in that way in does not do stuff on its own, but can be used by other objects.
okay thanks i'll go try to make this
Alright, wish you luck, here is an example for a potential architecture as well. You could as well do it pretty differently though, so thats just an idea.
Lot could just be stored in the weapon specific SOs. I'd make the firing type the key, and then create a dictionary that maps that key to the specific hud asset for the entity.
Dictionary<FiringType, HudAsset> weaponHudDict;
public EquipWeapon(Weapon weapon)
{
EquipWeaponHud(weaponHudDict[weapon.weaponSO.FiringType]);
}```
could anyone help me please ive been stuck for like 30 mins and i dont understand how this isnt correct:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using System;
using Unity.VisualScripting;
using UnityEditor;
public class MushroomManager : MonoBehaviour
{
public GameObject mush1;
public GameObject mush2;
public GameObject mush3;
public Timer timeScript;
[SerializeField] public AnimationCurve timeCurve;
double[] timesArray = new double[18];
int decayed1 = 0; //mushroom1 (top mushroom) decayed = 0 on start
public void Start()
{
mush1.GetComponent<Animator>().Play("No Decay");
mush2.GetComponent<Animator>().Play("No Decay");
mush3.GetComponent<Animator>().Play("No Decay"); //sets all 3 mushrooms to no decay state
double timeCurvePos = timeCurve.Evaluate(0);
for (int i = 0; i < 18; i ++) // for (numbers 1 to 18)
{
timesArray[i] = timeCurve.Evaluate(i * 10); //timesarray(number) = timecurve.value at number X 10 for example 6 might be 11.4588 seconds
}
}
public void Update()
{
double currentTime = timeScript.currentTime; //currentime = time in double game has been active
float roundedCurrentTime = (float)Math.Round(currentTime); //currentime = time in float game has been active
foreach (double timeArrayValue in timesArray) //for each point (every 10 on x axis)
{
float roundedTimeArrayValue = (float)Math.Round(timeArrayValue);
if (roundedCurrentTime == roundedTimeArrayValue)
{
decayed1++;
break;
}
}
if (decayed1 == 1)
{
mush1.GetComponent<Animator>().Play("Slight Decay");
Debug.Log("mushroom infected");
}
if (decayed1 == 2)
{
mush1.GetComponent<Animator>().Play("Slight Decay");
}
if (decayed1 == 3)
{
mush1.GetComponent<Animator>().Play("Slight Decay");
}
}
}
also im just ignoring mush2/3 for now as i can add those in once mush 1 works
What isnt working, share the error etc.
there is no error message but it is decaying mush1 at around 4 seconds instead of the expected 14/15
i can show animation curve too if u want
What's going on in that bottom section, your if statements all seemingly doing the same thing
yea that is because i havent made the animations yet but i cna easily change that, the problem is it plays teh first one at 4 seconds of time
and ik it is the first as the Debug.Log appears
Add more debugs then to see why your mush1 is decaying before you think it should. You should step through with the debugger because itll show you all values while you go through line by line. I have absolutely no clue what you are doing with that time array thing (and dont have the time to try deciphering it). I will just say, a lot of this is hardcode and doesnt make sense why it's being done like this
not sure how else i could do it other than manually typing them in, so ill porobably just do that
I don't know what you mean, do what, manually type what in
its hard to explain so just pretend i didnt say anything, i dont need help if i use this other method
I guarantee you're gonna be having worse issues in the future if you continue with your current structure
Thanks, I've done that also. Which checkboxes should be selected when doing it?
the game is pretty small so im not too worried aboiut that
The size of the game is not the concern. Its that your code is hardcoded to do exactly 1 thing and you seemingly cant explain what it is you're trying to even do.
I'm not sure where the problem is?
The problem is that you need to configure your code editor so it highlights errors for you first
!vscode
(this step is required to get help here)
you vscode is not configured
You'll have to restart VSC or even your computer for all the changes to apply
I had the extension installed long ago
Configuring it installs the .NET SDK on your computer, which needs at least a reboot to take effect
Ensure the SDK is there by running dotnet --list-sdks in a command prompt
yes it is installed
Have you installed the Visual studio Editor package in Unity?
Have you set VSC as Unity's external code editor?
It installs the required packages on Unity's side, so Unity can generate a valid project file VSC will be able to read
this part of the code is slightly transparent which is giving me errors
No, the errors will be underlined red
These are slightly transparent because they're not used at the moment
You're not using anything from System.Collections right now, down below in your code
Yes but there should be stuff in my code that needs this that is greyed out
The ones underlined blue seems like it's your spell checker going off
These are not errors, your project will still be able to compile
Can somebody help me fix this error?
which one is line 16?
And do you know how camera.main works?
No
!docs
does anyone know if you can detect how far a player is along a collider?
Can you explain a bit further?
hey, i've been looking into how would i make a controller work with my game, now i could use either the old input system (i seriously do not want to, since it has not enough features i need) the new input system (it's overly complicated) or which i do want to use is, since i already have my own input system made, which works basically the same way as unity's old input system, but it doesn't support controllers, is there like a very bare bones something like GetKeyDown() but for controller keys and axes? or maybe i should just use some api's with C# wrappers?
i would recommend learning new input system tbh
new input system is confusing, but it does have all the main features to detect different types of key presses etc and subscribe to them
so say the collider has size 7 on the y axis, if the player is 3.5 units up on the collider, i want it to return 0.5
i asked chatgpt and it said use a raycast (i decided to use a boxcast instead because a raycast might miss the player)
yeah
playerHeight/maxHeight where player height is from 0 to maxHeight
i dont think thats what i want
Do you only want it on the y axis?
well i have a variable that changes which axis it checks on
Okay, so lets say it is on the y axis for now
yeah
so say the collider's center is at 0, 0 and the player's collider's center is at 0, 1 and the colliders size is 10, it should return 0.6
thats what i want
float bottomBound = colliderObject.position.y - colliderBounds.y/2; //Gets the bottom most y-level of the collider (given that the position is at the middle of the collider)
float upperBound = colliderObject.position.y + colliderBounds.y/2;
if(playerPos.y < bottomBound) value = 0; //The player is below the collider
else if(playerPos.y > upperBound) value = 1; //The player is above the collider
else //The player is on the collider
{
float value = (playerPos.y-bottomBound)/colliderBounds.y; //Gets how far up the player is on the collider and puts it onto a scale from 0-1 by dividing it by the maximum
}
btw i should probably say that this is in 2d
Something like this should do the trick I believe
ill try it out ty
If I have a manager script in a hierarchy and I want child gameobjects with their own scripts to listen to certain events from it, what's a good way of referencing the manager in the children's scripts?
It's not a singleton, I know I can just have a public reference in each childs script and manually set them each, or I can search up the hierarchy from the child until I get the manager script and use that. Just wanted to check in case there are any other options which work better
So, since you said it's not a singleton, I guess you don't want a static accessor?
You can check out this site for lots of different reference methods
https://unity.huh.how/programming/references
what does the variable colliderBounds correspond to
The collider type has a bounds property. So I would guess that.
Oh, yep. That's it
ta very much and yeah, they need to be mono as I don't want one manager invoking to trigger every listener: (terrible crude image below)
colliderBounds.y/2
just a bit confused from this line here, because what y value should it be using?