#archived-code-general
1 messages Β· Page 274 of 1
no that was the problem
youre right
that was the default size for the collider i didnt notice that
i fixed it and now it works
somethings wrong with the actual rules but i can figure that out myself probably
i was stuck on that for like half an hour
this is a pretty general question but what is the next most important thing to work on for a game after movement? im thinking an inventory system, or a health system, but im running in circles like does the chicken come before the egg
ive gone a bit into the inventory side, im able to pickup items, and display it in my inventory, with the corresponding data saved with it. but i dont understand it fully.
That depends a lot on the game
Probably health and lives
I like to get stats out if the way early on, and the UI.
im taking it super slow, i made a few games so far all the way through with simple mechanics, but now im making a more robust fps with health and food. kind of like how Green Hell does there system
First step is the paper prototype though. Get the blibs working and make sure it's fun first
yea i got a fps movement system I can use for the rest of my projects now, its really nice
I'm not sure what that is. But I'm definitely a check off the core first kind of person
fps = first person shooter in this case
No, green hell
it's a survival game where you play in the jungle so it has well fleshed out survival mechanics such as health and food
yea super fun game you need to play
im afraid of going through with this tutorial bc if i implement it and something breaks halfway thru id be too confused to fix it
that's why this server exists ^~^
yea i guess loll
how can i make a player only jump once when the spacebar is held?
i should push this to beginner
A lot of tutorials are pretty specific and cant really be extended on much. So its better if you can plan out what you wanna do before following it, so you know which parts need to change
its hard to know what you need, i overthink it
Don't you have some main idea behind the game, a pivotal mechanic or something?
why
you have 3 bugs in there, two of which are helpfully underlined for you to mouse over

not code general
3 bugs down, 1 new bug added
local variable pain
now
nice. Now only code smells remain
reading it with 5 little monkey jumping by the bed song in mind
I dont think the cast (ParticleSystem) is necessary
huh
Hmm you are instantiating the blood itself?
Better use a prefab reference instead, I think
weird design choices
- the casting as mentioned; it looks like it's already a ParticleSystem, but if it's not you should change the field to ParticleSystem
- reusing your serialized field as a runtime field is smelly. I'd have your prefab be separate (bloodPrefab) while _blood is a runtime value
- you might want to use a pool because currently if you spawnblood and there's already blood playing, the first one will disappear
while it might be smelly, I dont think reusing prefab variable will do anyharm
I sometime do that when I just to lazy to write new variable
it doesn't technically do any harm which is why it isn't a bug, but it takes 3 seconds to do it right. If you're lazy about something like that, you're probably being lazy on other design decisions too and you'll be punished eventually
on a second thought, it wont do any harm only if he properly initiate the instantiated prefab.
also if the particle is set to destroy on stop, it will have null reference error
hence, very smelly code 
Just in general it's not a good idea to reuse the variable. Itll be a pain to debug if you ever instantiate a prefab (or so you thought) but it's a game object which has changed in some way
If you're lazy about something like that, you're probably being lazy on other design decisions too and you'll be punished eventually
Well, my motto is : "If it works, it works"
I dont really care on how it's written or what design pattern it use XD
if it has no ||game breaking|| bugs, and it runs butter smooth, then it's good enough for me π
that works in the short term, but as technical debt accumulates it gets harder and harder to add new features. On some future day, you'll solve some esoteric bug due to badly written code by some moron engineer, and when you git blame you'll find out that moron was you 6 months in the past
well, let's hope that the game is shipped before 6 months then
How do I convert viewport position of a portion of my screen to a viewport position of my whole screen without actually changing the position of that point on the whole screen?
something like remap function?
https://rosettacode.org/wiki/Map_range
think so
So your camera's viewport rect does not cover the whole screen?
Its a camera rendering to a render texture, and that render texture doesn't cover the entire screen. So yes
I feel like camera.pixelRect or camera.rect can help when remapping it
Though not sure if it is relevant if you use a rendertexture. Do you display it with a RawImage?
displaying it on a UI toolkit visual element.
I ahve the position I want, just want to be able to display it on my cursor
context is:
I have snapping functionality that I get a world space position on based on the mouse position through the render texture
now I want to convert that world space position to the position of the entire screen so I can display an icon on my cursor and then have it be able to snap onto my that position I want on my render texture. I've gotten as far as to getting the position on that visual element, but of course it isn't the entire screen.
can anyone help me animate my UI, i have animations but it wont recognize it my code is this:
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class HoverOver : MonoBehaviour , IPointerEnterHandler,IPointerExitHandler
{
public GameObject HoverPanel;
public Animator animator;
void Update ()
{
}
public void OnPointerEnter(PointerEventData eventData)
{
animator = GetComponent<Animator>();
animator.SetTrigger("ScaleWhenHover");
}
public void OnPointerExit(PointerEventData eventData)
{
}
}`
animator is cancer for UI
just change the postions through code
its called tweening
how can i do it?
get rect transform of UI
because i managed to the other day but the transition wasn't clean
change anchored position
define clean?
like it doesn't ease?
make an easing function
yeah
idk use lerp or something
i'll look at tutorials cuz i have no idea what that is and so many people keep telling me to
Do you have a camera rendering to the whole screen?
yup
holy shit just looked at a tutorail its solvinmg all of my problems
If you already have a world space coordinate, you can just use camera.WorldToScreenPoint/WorldToViewportPoint on that main camera
been there, done that. When doing that, and set position of the circle, it ends up on the middle of my screen. Even though its supposed to be in the middle of the render texture
maybe you can do something like this using the remap function from above
cursor.x = remap(vpTopLeft.x, vpBottomRight.x, 0, 1);
cursor.y = remap(vpTopLeft.y, vpBottomRight.y, 0, 1);
guys really quick is there a way to mention scale in coding?
like instead of transform.position
transform.scale instead?
transform.localscale?
if you've set up intellisense properly, a suggestion should popup when you tipe 'transform.scale'
i think ik what u mean by intellisense but it doesn't work for me
how do i set it up?
i see it in other tutorails
wait ok
guys can someone help really quick
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LerpScaling : MonoBehaviour
{
private Vector3 endScale = new Vector3(0.9437993, 0.9437993, 0.9437993);
private Vector3 startScale;
private float desiredDuration = 2f;
private float elapsedTime;
// Start is called before the first frame update
void Start()
{
startScale = transform.localscale;
}
// Update is called once per frame
void Update()
{
elapsedTime += Time.deltaTime;
float percentageComplete = elapsedTIme / desiredDuration;
transform.localscale = Vector3.Lerp(startScale, endScale, percentageComplete);
}
}
`
this is the coad
code
First configure the !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
can u help with this as well or?
Yes, after you've configured the IDE
how to add offset so the blood spawns at the center of the prefab enemy?
how would I go about getting the corners of a visual element? nvm I think I got it
i did it i think but i have to go now if i DM u can i message u later?
Get the component of whatever renders your actor, get the bounds, half that and use the height for the offset
Can also use the collider bounds
No, post again here and whoever is available can help
fair enough
actually post to #π»βcode-beginner instead
okok
Ok so I tried it and it aint working, probably implemented remapping wrong. I asked chatgpt to do some viewport remapping and it always yeilds what happens
here ^
Like I'm tryna stop this
Vector2 snapPos = Collider2DHelper.FindClosestPointOnBody(_currentRay.Value.rigidbody, _mousePosition);
Vector2 snapScreenPos = _creationCamera.WorldToScreenPoint(snapPos);
_displayTexture.rectTransform.anchoredPosition = snapScreenPos;
π€ if you want to remap from fullscreen position to viewport position, try reversing the remap
cursor.y = remap(0, 1, vpTopLeft.y, vpBottomRight.y);```
also, if you are using screen position instead of viewport, change from 0 and 1 to 0 and screen.width(or height for y)
here's a remap function I got from google
well, it's actually mgear's XD
https://forum.unity.com/threads/re-map-a-number-from-one-range-to-another.119437/
Will OnTriggerEnter still run physics checks even if there is not a trigger component on the gameobject?
I have an axe item that can lodge into targets. There are colliders and a rigidbody. The item also has a trigger collider that's used to determine if you're close enough to pick it up. I had the item go crazy if the target was also a simulated rb (like a hanging target on some joints), what solves this was rb.detectCollisions = false as soon as the axe is lodged in a target. BUT this stops the ontriggerenter working and the axe can't be picked back up.
It won't be called.
Thanks, I was worried that it was hogging up resources.
I'm trying to have the item have a disablable collisions on it's rb and still keep my triggers for the item pickup, and found advice to make the pickup trigger a child of the item. but now I'm getting this error: MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. no objects are getting destroyed. only re-parented. Is it possible unity recreates the Transform's when the hierarchy is modified?
Are you accessing the parent perhaps?
yes, whenever the player enters the pickup trigger I'm adding the triggers transform.parent.parent to a list of potentially picked up items (and removing on trigger exit). then when the player hits the pick up button an item is grabbed from that list
This seems... fragile. You should ideally only be interacting with the thing you interacted with via physics and that is usually a parent object. Excluding cases of having a GO acting as a wrapper object.
Regardless you need to show code for help with the errors specifically. Or just follow what the error says about it being null
I think I was mistaken and having the trigger as a child has the same issue, as soon as I disable collisions on the item rigidbody, the trigger colliders stop working.
(I read somewhere that the trigger colliders are unrelated to the physics collisions and this approach should work )
Well ya if you disable a collider, you arent gonna get a physics message for it..
not disabling the collider. calling rigidBody.detectCollissions = false
This seems to affect any trigger colliders under that rigidbody in the hierarchy.
Hi guys, have a nice day.
I'd like to ask how to maintain UI position after changing its parent. Known that the UI is heavily nested in the first parent game object and the second parent is more simple.
I have tried using belows but no use.
SetParent(parent, true/false);
---
var pos = transform.position;
SetParent();
transform.position = pos;
---
transform.TransformPoint();
---
OnTransformParentChanged()...
The drag in the inspector works just fine but I have no idea how its code work.
UI works on anchoredPosition
What do you mean?
rect transforms, works on anchoredPosition
and you should modify that instead
- anchoredPosition
- position
The UI I mentioned is heavily nested. AnchoredPosition looks like a local position for UI element to me and yes, I have tried that solution too but no use.
RectTransform is just a derived class from Transform and It does have world position and local position, I believe. But I'm looking for the code/mechanic of the drag to change the parent of a gameobject in the inspector.
you could try grabbing your current transform.location, use Camera.main.WorldToScreenPoint(worldPosition) to get screen coords, and then try the above to calculate your local position with respect to your new parent's rect?
anybody has a handy json convertor which works for AnimationCurves?
that actually sounds like quite a bit of data to serialize with json (guess it depends how much you are evaluating throughout the curve)
what's wrong with grabbing the animations keys and storing those
If it's serializable in Unity, it should be serializable with JsonUtility.
Ah, right they should be serializable. I'm thinking animation clips themselves, but AnimationCurves are very much just a collections of keys.
Yuck, please don't use JsonUtility
Even if it works
Serializing it is actually pretty easy. https://docs.unity3d.com/ScriptReference/AnimationCurve.html
Just take the keys and the wrap mode and you can use these to recreate it
Serializers like Newtonsoft allow for custom serialization based on type so you can make this an automated system on serialization, to avoid mistakes
where can i ask for help with some code
oh so here

Im practicing some GUI editing. im trying some property drawing but for some reason the properties get drawn outside of the box instead of inside?
i dont think its handy to copy paste all my code in this chat so if anyone can help look at it in dms, would be appreciated
Yes, that would definitely help. However, in your particular question #βοΈβeditor-extensions might be better.
yeah i know that unity has an new UI toolkit. but i need to understand all this stuff for a project im joining
weird thing is i had it working a second ago. but i tested some changes and now i cant get it back anymore lol
looked through all the changes i made
Create a thread and use the code sharing guidelines for long code:
!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.
Yeha I ended up doing that @thin aurora @late lion . I had a custom JsonConvertor which worked, but wasn't handling null objects so it was breaking
danke
is there a channel, where I can ask for an error message?
am i allowed to create a thread in this chat?
or somwhere else?
"an error message" ?
I got an error, and dont know how to fix it
an error where , in code?
You're allowed to create a thread in this channel.
yes, in a unity project
I give you my permission
if its code related then post it in code channel, anything else should be in #π»βunity-talk
Properties not drawn in right place
ok, ty
hey guys
public class PlayerHealthSystem : MonoBehaviour
{
// Start is called before the first frame update
private Rigidbody2D rb;
private Animator animator;
public bool pauseotheranims = false;
public bool hurt_play = true;
public float max_health = 100;
public float present_health;
Scene currentscene;
public Text health;
void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
present_health = max_health;
}
// Update is called once per frame
void Update()
{
if (present_health == 0)
{
Debug.Log("0");
}
health.text =present_health.ToString();
currentscene= SceneManager.GetActiveScene();
if (gameObject.transform.position.y <= -8.17f)
{
SceneManager.LoadScene(currentscene.name);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Traps"))
{
hurt();
deathAnim_PLay();
}
}
public void Die()
{
SceneManager.LoadScene(currentscene.name);
rb.bodyType = RigidbodyType2D.Dynamic;
pauseotheranims = false;
}
public void hurt()
{
if(present_health >0&&hurt_play)
{
animator.SetTrigger("Hurt");
present_health -= 10;
}
}
public void deathAnim_PLay()
{
if (present_health <=0)
{
hurt_play = false;
rb.bodyType = RigidbodyType2D.Static;
animator.SetTrigger("Die");
pauseotheranims = true;
}
}
public void FreezePlayer()
{
rb.bodyType = RigidbodyType2D.Static;
}
public void UnfreezePlayer()
{
rb.bodyType = RigidbodyType2D.Dynamic;
}
}
the player lives even when the health is 0 if enemy hits player once more when health is 0 then it dies.
how do i make the player die when it hits 0
if (playerHealth <= 0)
Die();
i used the die function as an event in the death animation so after it finishes the death animation with deathanimplay it calls die through event
the player dosent die when health is 0 if the player gets hit once more then it dies
so to die the player has to get attacked once more even if its 0
you should do it the other way around, call the die function in script, and play the death animation in the die function and use the animation events to reset or something
i see ok
wait so you want for the player to die only when health reaches less then 0? not equal to 0
i want player to die when health reaches 0
I wonder if it has to do with your state transitions.
its not that the animation dosent play player can do all the stuff even when health is 0 like attacking killing collecting jumping
How would you guys go about visualizing a box cast?
I have a Pyhsics.BoxCast, but the result I'm getting is not what I pictured in my mind, and I would like to visualize the exact box cast to see if I messed up in the rotation.
draw a gizmos?
im not sure i never tried
Are you able to confirm whether or not the code is getting into the if statement within deathAnim_PLay?
yes i can log a message
lemme try
That would help us understand where we should look further
the end result is that it dosent output"Player Died" when its 0 but if i get hit once more when 0 then everything runs fine
I know, but I'm having issues rotating it.
i tried something else i changed the death deadline to 10 and it worked
but when its 0 you have to be hit twice
How can I make it write to the console as long as I hold down the button? Normally, when we use a button, it gets triggered when we release it instead of holding it down. However, I don't know how we can determine what happens while the button is being held down.
what's the code you're using at the moment?
I want the gun to fire as long as the button is pressed in the mobile game. I wrote the ignition code, but I couldn't do it because it didn't trigger as the button was kept pressed.
okay, can you please show the current code?
wait
ui
AttackButton.onClick.AddListener(Attack);
I find this project very nice for visualizing the casts: https://github.com/vertxxyz/Vertx.Debugging
Theres a little bit of setup, but you basically add OpenUPM, then you can install the git project from Package Manager and use it just like Physics.XCast (same params) just replace it with the namespace this package uses, it will also show when there is a detection
see the thread that was shared to you. mainly the point about using EventTrigger
I don't understand
thx
I see it now thank you
Thank you, I'll check it out!
I'm trying to get the total types of values of an enum and the answer i found on google doesnt seem to work. Does anyone know how to get it?
System.Enum.GetValues(LootType).Length - 1
The only one on that list that costs money is Rider. Use Visual Studio
!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
typeof(LootType)
not sure why you'd subtract 1 from it unless it has some kind of "none" item
ah your right thats out of habit thanks
trying it now
it works thank you!
Is now a good time for me to put in stuff about my problem?\
Don't want to cover up other peoples' inqueries
Good enough of time as any other I guess:
I've been trying to set up some movement code to get myself back into the swing of things in Unity. The issue is that 1 in every 10 or so jumps is unusually higher than the others. It also seems to differ in the build? The big jumps seem to be default in the editor, but the neutered jumps seem to be the default in the build.
https://paste.ofcode.org/VRLrXyamAXvA6Rew6VpukK
I think the offender might have something to do with the implemented dynamic jump features.
I read online that it has something to do with putting that stuff in Update() but that doesnt seem to apply here. So, idk whats going on.
https://cdn.discordapp.com/attachments/714663066075136031/1208867269506240584/Untitled_video_-_Made_with_Clipchamp.gif?ex=65e4d860&is=65d26360&hm=804360462fcf9d5375c110565a331bb229eaae1593413a5c001197579461b064&
my visual studio isnt autocompleting code
Then configure it using the links provided
it didnt work
Then you have missed a step somewhere
eh there is a thing with some jump codes where if you hit the button twice quickly you can trigger a jump again
but idk if that is your problem
There's a jump cooldown to help deal with that. Also the jump force is set, not added. So, I'm not sure that could cause it.
well even if it is set it resets the amount it had slowed down
could also be you are triggering the jump at the right time to do it before you are fully on the ground
try shrinking your jump detect box, see if it fixes it
The size of the groundCheck is considerably smaller than the jump size difference. I've tried it though, it doesn't work. Also, it just causes other problems with movement.
i have a board game where the board is randomly generated and then copied, mirrored and flipped to so both sides are equal but now when im adding pieces and coding where they are able to go i run into an issue since im using a 2d array to keep track of the placed its able to move to but the cordinate values doesnt go from 10x10 to 0x0 but instead from 10x5 to 0x-5 and giving the array a negative value ofc gives an error. any ideas how i could bypass that? ive tried to offset it but it just moves the issue.
not totally sure what you are asking but I did write some (albiet java) code for mirroring an image
let me grab that for conceptuality
java is basically c# but slightly different so shouldn't be too hard to translate
public static void Mirror(String S){
Picture pict = new Picture(S);
var Pixels = pict.getPixels2D();
var len = pict.getWidth();
var Y = 0;
for (Pixel[] pixels2 : Pixels) {
var Iter = 0;
var HoppedIter = 0;
for (Pixel pixel : pixels2) {
if(Iter > len/2){
pixel.setColor(pict.getPixel(len-Iter, Y).getColor());
}
Iter += 1;
}
Y += 1;
}
pict.show();
}
this was that put it should be relatively translatable
I should make note that this problem only seems to be an issue in the builds. The big jumps are consistent in the editor. Which makes me think its an Update()/FixedUpdate() problem.
im asking how i can work around the fact that arrays only go in positive values and one of my values can be negative
if thats a respond to me
it is
tbh the solution is to not use negative values in a place like this
or something with mathf.abs
You can't have negative indices in arrays. Just provide some kind of offset so you can do:
int myCoord = -5;
int offset = myArray.Length / 2;
myArray[myCoord + offset];```
yeah or that
I was just thinking this. Offset the indices by half of the size of the array
basically let's say the array has 10 elements. You want to consider [-4, 5] instead of [0-9], To achieve that you have to add 4 to the index before using it.
so yes, adding half the size of the array.
i tried that but it pushed the issue just further down but i can implement it and work from there
I mean it's an entirely tractable problem, you just have to give it a little thought
It's a workaround I guess
Also, hi Praetor. Glad to see you're still dishing out helpful coding advice to people
The other option is to use a Dictionary instead of an Array
especially if this is a 2D grid, very easy to make a Dictionary<Vector2Int, Piece> or whatever
im quite new to c# so not too sure what that is
You should go look it up. It's extremely useful and common
i will thanks
every programming language has an associative array of some kind. They're called Dictionaries in C#, Maps in Java, HashTables in a lot of places.
ahh maps im slightly familiar with from js
it's the same thing
in fact every JS object is essentially a Dictionary<string, object>
but still very little clue on how they work tbh
meanwhile, html:
so in that example just have the coordinates as the first values then true/false as the last one for example
not sure what you mean by first and last values
I don't really know how your game works. Let me use chess an example. In Chess you might have a Dictionary<Vector2Int, Piece>. The Vector2Int is the coordinates. The Piece can be any chess piece, e.g. Knight, Rook, Bishop and its color for example
or null in the chess case
I mean you could have it be null or you could just not have that coordinate in the dictionary, which would be cleaner
HTML isn't a programming language
touche
fair enough, what i want with that code is to display every place that piece can go to (any spot within a range)
well I presume that spaces that don't have a piece on them would just have the piece be null instead of removed from the dict
It would be cleaner to just remove it.
that would be weird to use null
because then you'd have some entires that are null and some that don't exist
and both of those things would mean no piece is there
its not to track where each piece is but rather where they can go
and if you are going to go throught the trouble of populating all the spaces with null you might as well just use a 2D array
oh yeah I guess heh
If you just want a set of legal places for the piece to go just use a HashSet<Vector2Int>
if the space is in the set, it's legal, otherwise it's not legal
infinite grids usually are dictionaries, but if you got like a chess size board I'd just make the 2D array
i got a 10x10 grid but since its a copy paste the board cordinates goes from 10x5 to 0x-5 instead of 10x10 to 0x0
well yes chess is typically an array but chess was an example for illustration, they're not making chess
is this the place i can get help with code
its an very advanced version of chess tbf
Just do something like this:
public struct Coordinate {
public const int boardSize = 10;
public const int halfSize = boardSize / 2;
public int x;
public int y;
public Vector2Int ArrayCoords => new Vector2Int(x - halfSize, y - halfSize);
}```
then you can use your Coordinate struct however you want in your code, and when you want to access the array you use the ArrayCoords property.
chess 2.0
thanks ill see if i can figgure it out
machine strike from horizon forbidden west to be exact
tbh I don't really see why you need the negative coordinates.
In all your code you should deal with positive coords
if you want to display them on the map as negative, that's just a display thing
i wish so too
that happens at the very end when displaying to the user
it shouldn't be part of your code logic
it's like in chess the coordinates are a1, b7, etc..
internally in any chess engine it's just two numbers, both zero indexed
the letters and the 1-indexed number are a last second display translation for the User's benefit
in fact in many chess engines it's just a single number 0-63 to indicate the board space. The internal representation doesn't have to match what the player sees.
ill have to look at the code i made to define the cordinates to see if i can adjust that
Yes
Oh, I see you asked about networking in the other server though. So #archived-networking would be better if it's the same question
that worked, why did i not think of that before
I'm trying to get some realistic camera bobbing, but I don't just want some sine waves going up and down, I can't figure out how I would do this since I'm not that good at math, and there are no videos of realistic camera bobbing online, anyone willing to help?
use an animation curve
I have no idea what that is yet, I haven't dived much into animations.
Hello I have a problem on my TMP_Dropdown! When I have my dropdown menu 8 has the value of 0 and zero the value of 8! whats the problem here ?
Well it's clear here that the option "number 8" is at the first position in the options list, so it has index 0 in said list
And the last one, the "number 1" is at index 7
Where is my mistake ? In the dropdown component ?
No, probably in the code that handles it
if I use OPTION = 8 i want that it has the value of 8 in the code
public TMP_Dropdown MyPlayerCountDropDown
{
get { return m_PlayerCountDropDown; }
}
m_uILobbies.MyPlayerCountDropDown.value
Yeah the On Value Changed event will pass the index, not the option text to your function
but when I change the dropdown menu in the inspector when I pick 6 it has the value of 2 (look on the pictures above)
Yes that's normal!
Because the option with the text "6" is third in the list, so at index 2
ok i got it
what is the best to get the int from the dropdown ?
I use it to create a lobby and I want use it for 1-8 players
Lobby lobby = await Lobbies.Instance.CreateLobbyAsync("My Lobby", m_uILobbies.MyPlayerCountDropDown.value, lobbyOptions);
That would be the text of the selected option, and you will get it as a string.
how do I get the text of the selected field ?
is there a way to get it as int ?
Not directly, you need to convert it, like with int.Parse()
thanks a lot
@zealous crane don't crosspost
okey
this did work for me:
int selectedValue = int.Parse(m_uILobbies.MyPlayerCountDropDown.options[m_uILobbies.MyPlayerCountDropDown.value].text);
Fixing Jump Inconsistency
[Package Manager Window] Error adding package: https://github.com/srcnalt/OpenAI-Unity.git.
Unable to add package [https://github.com/srcnalt/OpenAI-Unity.git]:
No 'git' executable was found. Please install Git on your system then restart Unity and Unity Hub
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
keep getting this error while use giturl in UPM.
i have several repos that i access using source tree dont know what is leading to this error any idea?
No 'git' executable was found. Please install Git on your system then restart Unity and Unity Hub
Is Git installed on your system?
Try inputting git in a command line terminal, and make sure the command is recognized.
wee, it doesnt exist 
Install it and try again. You'll need to restart your computer (or log out -> log in) so the changes are applied
I think these have the library bundled into them, so they're fast and easy to install and set up
worked!
i have a question for c++ interperatation
cus im working on a game that wants to utilize c++ code
and c# as well
then ask in a C++ server
ok, but i need help with also adding game objects to a scene while using c++
idk if they could provide that
sounds like modding which is not allowed here
ok
Im trying to make an enemy that travels around terrain. Like the little bugs from hollow knight. Any way i can simply make an enemy crawl around a collider?
currently doing this, which makes it freak out at a turn because rotating it does not imply correct position after turning. So the collision checks fail when rotated once
I got a navmesh surface and agents and they chase the player but it doesn't jump at all and if it cant reach the player it just stops. How can I fix this?
I'd recommend using Unity's pathfinding. Coding that on your own will require a lot of work and a lot of code.
https://learn.unity.com/project/beginner-ai-pathfinding
its a 2d platformer game so i dont think thats what i should go for right?
I haven't worked much with 2D but I heard this is good pathfinding tool: https://learn.unity.com/project/a-36369ng
In this tutorial you will learn about the fundamental concepts used in the creation of Behaviour Trees. You will also take this knowledge and apply it in Unity by building a simple simulation scenario where a behaviour tree is used to define action sequences of a thief stealing a diamond from a gallery.
For my VR Game it says that it cannot find Photon3Unity3D.dll even though i have it does anyone know the solution
Does anyone know why my character is clipping into the wall? The video shows what is occurring and what the properties are for the player and the wall.
private void FixedUpdate()
{
if(movementInput != null)
playerRigidBody.MovePosition(transform.position + (Vector3.right * movementInput.x * Time.fixedDeltaTime * movementSpeed));
}
anyone know why I am using a singleton and I am settings a TMP Text in a property called text. Then in a funcion called changeText I am changed the text of the TMP text I set in the inspector but it turns me this error Idk why.
what is line 40 or PersistentManager.cs
this.Text.text = "test"
then you are likely calling that method before the Text variable has been assigned or on an instance where it has not been assigned
Mmm there is a delay of 2 seconds before calling the function which change the text
One possible reason could be that all the container where the text resides is disabled but I active it before changing the text
that does not mean that either of the things i said is not true. in fact, one of the two things i suggested has to be true
you've shown a single line of code so i can only guess at what it is. consider showing more code
Mmm know I can't show more as I send the error and disconnect I have been coding for hours. How I can see if the variable has been assigned?
It could be that the persistent manager is created before the text component was created?
Does your singleton implementation have the ability to create itself if it doesn't exist? I have a feeling you're about to find out why singletons are a controversial design anti-pattern
hey uhm, why can i see the red gameobject in the scene but not when i look in the game viewer
oh wait, nvm i realized why. it was behind the camera lmao
https://i.imgur.com/c7qBYwS.gif
why might this code, which spawns a raycast from a gray cube and shoots downward, be failing to instantiate the red cube prefabs on the box below it?
instead, the raycast does not detect the box below it-- only the floor-- so the red cube prefabs get spawned on the floor instead of the box
The box has collider active. (Pic attached of box inspector properties)
It just looks like it's probably not over the edge enough
that.. may actually be it, it looks like if i move Z by 0.01 then it works, okay that revealed another problem lol that i can finally fix thanks!
Anyone know how to test different system languages in unity without actually changing my system language?
I even changed my windows display language but apparently that's not enough lol
Localization package ?
is there an already made string-like class for strings that are multi-language? wouldnβt be too hard to code, but I am wondering if someone already made one
2 localization questions back to back , nice
his question reminded me that it was a thing Iβve been meaning to ask for a while
i was thinking something like class InternationalString with public enum Language {β¦}, public static Language currentLanguage, and public override string ToString() => strings[(int)currentLanguage]; or something
or something like that. but i feel like iβd be reinventing the wheel, when there is definitely a tool out there for this
There's an entire localization package
I have my own i18n done with code gen for compile time type safety, but I imagine that's not a common requirement for most games.
yeahβ¦ Iβm trying to avoid reinventing the wheel as much as possible.
how would you rate the unity localization package, between [not worth using] and [very worth learning]
I have barely touched it

I've downloaded the unity localization package but I'm having trouble getting it to actually use a different language from English.
I have not gotten around to learning / using it yet.
Wish could be more help on this, Sorry.
its serviceable
certainly beats rolling your own. It feels a bit overengineered at first glance, but it actually just gives you all the tools right from the start that you'd need eventually anyway, but just don't know yet. In some simple cases you'd ofc be done quicker with a DIY solution; Those would be ones without a team or any need for mixing editor & code based workflows.
Hi, why does using using this code make my Wirecube disappear in the Scene view?
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(transform.position + Vector3.up, new Vector3(1f,2f,1f));
I'm just trying to make the Wirecube gizmo rotate along with te rotation of the Transform
Presumably because you're drawing it at its position but locally to itself, so you've translated it doubly
localToWorldMatrix already includes the position, don't additionally use transform.position to offset it
Ahh, thank you
also make sure this is in OnGizmosDrawβ¦Selected etc
Thank you for the suggestion!
hey everyone, i am having an issue with a struct that i created and it has an initializing function attatched to it but it is not working.
I have an array of struct that i loop through in the awake function and calling init on every one of them but it is not populating.
here is the struct:
[System.Serializable]
struct RectInstruction
{
public bool isHorizontal;
public RectTransform[] upOrRight, downOrLeft;
public float[] upOrRightDefaults, DownOrLeftDefaults;
public void Init()
{
this.upOrRightDefaults = new float[upOrRight.Length];
this.DownOrLeftDefaults = new float[downOrLeft.Length];
for (int i = 0; i < upOrRight.Length; i++)
{
upOrRightDefaults[i] = isHorizontal ? upOrRight[i].anchoredPosition.x : upOrRight[i].anchoredPosition.y;
}
for (int j = 0; j < downOrLeft.Length; j++)
{
DownOrLeftDefaults[j] = isHorizontal ? downOrLeft[j].anchoredPosition.x : downOrLeft[j].anchoredPosition.y;
}
}
public void ChangeAll(float addedValue)
{
for (int i = 0; i < upOrRight.Length; i++)
{
ChangeRect(upOrRight[i], upOrRightDefaults[i], addedValue, true);
}
for (int i = 0; i < downOrLeft.Length; i++)
{
ChangeRect(downOrLeft[i], DownOrLeftDefaults[i], addedValue, false);
}
}
private void ChangeRect(RectTransform rect, float defaultValue, float addedValue, bool isDefault)
{
Vector2 sizeDelta = rect.sizeDelta;
float newValue = defaultValue + addedValue * (isDefault ? 1 : -1);
if (isHorizontal)
{
sizeDelta.x = newValue;
}
else
{
sizeDelta.y = newValue;
}
rect.sizeDelta = sizeDelta;
}
}
The other functions work but not "Init()".
some things to keep in mind;
The rectTransform[]'s are populated in the inspector before runtime with a length on 1 for each.
The float[]'s are not populated in the inspector, I want to automate it using the init function.
Ive tried awake and start;
private void Start()
{
foreach (var item in instruct)
{
item.Init();
}
}
do i need an OG forLoop?
What is instruct, array or list
Then use forloop and use indexer call directly
I think you'll be accessing a copy in any case. You'll need to copy the initialized struct back into the array.
like
intruct[i].init();
??
I think that's gonna be a copy too.
hmm. this is weird i don't understand why
Array indexer not indexer, it actually dereferencing the address
Not returning the copy
would a list be different? should i use that?
Indexer of list is returning the copy
Because structs are value types, but Tina is probably correct.
so yes? a list does work?
If you want to avoid all that headache, just use a class. I'm sure struct isn't even a justified use case in your situation.
will do!
wait but can i make an array or classes and have them serializable in in the einspector?
Yes
ok β€οΈ
public class HelloWorld{
public struct A{
public int a;
public void set_a(int num){
a=num;
}
}
public static void Main(string[] args){
A[] a0=new A[1];
a0[0].set_a(10);
Console.WriteLine(a0[0].a);//10
List<A> a1=new();
a1.Add(new A());
a1[0].set_a(100);
Console.WriteLine(a1[0].a);//0
}
}
sometimes in my scene, I have to enable and disable a chunk of objects....this results in a lag...to be more clear, in my phone when i enable those objects, for a very small amount of time, the screen freezes...although it isn't much noticeable at first, it becomes clearly noticeable when I am doing it repeatedly...any solution to this??
What's the use case?
@lean sail i turned a huge terrain with trees and other stuffs into a gameobject and then cut into pieces...i have to enable and disable those according to the player's position...
You can just do the trees yourself and disable them independently, but disabling a whole terrain may have some overhead.
i have tried it...i have almost 4000+ objects in that chunk including only the trees and the crates and other stuffs...when i enable and disable those, the screen freezes for a bit...
Yea not really much to do there if you really need to disable all those objects at once. Maybe split it up even smaller and try to do the work over a few frames instead
how do i do that over a few frames?
is there anything like enabling objects asynchronously?
Coroutine
With a coroutine but try splitting this up into smaller chunks first. I think that would be better
The terrain itself chunks sections and is overall pretty optimized for not being touched in over a decade. Perhaps just disabling the collider could be a solution and profiling that.
how should i do it? using the waitforframes?
that terrain is now a gameobject...i am just enabling and disabling those splitted gameobjects having all the trees and other stuffs as its child object
I dont recall that being a thing specifically, yield return null will basically wait a frame though
why isn't it working?
thanks, i'll try this out
have you called the function anwhere?
Haven't you posted enough here to know that you need to give some context of what isn't working?
when i instantiate the blood it rotates properly but otherwise it doesn't
Baffling how anyone was supposed to gather that was the issue lol π€
a screenshot would be great to understand your issue
ill post a vid wait
bug 1) player.transform.rotation.y is a quaternion component, not an angle. You probably want to use eulerAngles instead
bug 2) capsulecollidercenter is probably not what you want; it's a world-space position, so if your transform ever moves it's going to be in the wrong place
doesn't work either
I'm going to guess this is a logic error and that while your code says "rotate the blood around +y axis", what you want is "make the blood fly in the direction the player is facing" right? If it's "working on instantiate" why don't you just reuse that same rotation? Otherwise you probably want something like Quaternion.LookDirection(player.transform.forward); as your rotation
this one worked but i swear i wrote it like this last time and it gave me an error π
something abount rotation not being a variable
maybe cause i added euler last time
I am struggling HARD with this code. No matter how much I add or change trying to get my snap grid to work, it refuses to let my pieces snap to the grid.
https://pastebin.com/RSRLvxwN
https://pastebin.com/4eWSFftD
https://pastebin.com/e6viKT4M
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Should probably start from clarifying/demonstrating the issue. A video could be useful for that.
True
i tried it...but lemme explain...i have two gameobjects...each gameobject has 4000+ gameobjects under it...when i am waiting for the frame after one chunk of gameobject is enabled, the whole process is taking only two frames...which is still creating heavy operation on those two frames resulting in screen freeze...and when i am waiting for a frame after each child objects is being active...it is taking way longer....what can i do now?
Dont know terrain, but the how many objs you have not affect your strategy (split them up and disable partial of them each frame)
Yes it has
I want to quit from singletons but I have a ws connection so I think that I'll need one of them for the connection
I don't know if I can create a non-singleton in a class and call a function from that class without being a singleton as I don't have any instance of it. Only the behavior
if your singleton can be created on-demand, then you have two potential issues:
- if it has any serialized fields, the one created on-demand won't have them set. And then when the one you set up is created, it kills itself
- if it has any serialized fields, they have to have the same life cycle (i.e., if your singleton survives scene loads via DontDestroyOnLoad, anything it references has to as well or they'll be lost on next scene load because they're dead
π€·ββοΈ splitting it across 2 frames is likely gonna have no real difference. you might need to do this across a lot of frames. This is basically gonna be the same as making those 2 objects into way smaller chunks. The problem is just flawed from the start, you arent gonna get good performance toggling 4000 objects on mobile
i guess i have to sort those objects and split it more efficiently...anyway thanks for the help
In my case my singleton (I don't know why I have created it as a singleton) is only in one scene because I don't know if in unity you can call a function from a mono behavior if you haven't set it to any game object
you might need to provide more context about what you're trying to achieve because I don't know how the second part is relevant
If there is no instance of the class (whether it inherits from MonoBehaviour or not) then no, you cannot call a function from it
Just to clarify for the second part
I am trying to set a tmp text when I receive a specific message from my websocket. But as the text is disabled I don't know how I can get it. I could make it to be enabled when the message is received but when I set it to active and I try to change the text it turns me the error. I am executing a function from the ws singleton to another singleton that is invoking an event to make it active.
Oh thanks.
Hey everyone, quick question.. my game is little by little slowing down exponetially and i think it may be this code..
void RenderSprites()
{
RenderTexture targetTexture = cam.targetTexture;
Texture2D tex = new Texture2D(targetTexture.width, targetTexture.height, TextureFormat.RGB24, false);
RenderTexture.active = targetTexture;
tex.ReadPixels(new Rect(0, 0, targetTexture.width, targetTexture.height), 0, 0);
tex.Apply();
Sprite convertedSprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0, 0));
if (spriteRenderer != null)
{
spriteRenderer.sprite = convertedSprite;
}
gridManager.SetSprites(SliceSprite(convertedSprite, gridManager.gridResolution.x, gridManager.gridResolution.y));
}
private Sprite[,] SliceSprite(Sprite sprite, int rows, int columns)
{
Sprite[,] sprites = new Sprite[rows, columns];
float sliceWidth = sprite.rect.width / columns;
float sliceHeight = sprite.rect.height / rows;
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
float xPos = sprite.rect.x + x * sliceWidth;
float yPos = sprite.rect.y + y * sliceHeight;
Sprite slice = Sprite.Create(sprite.texture, new Rect(xPos, yPos, sliceWidth, sliceHeight), new Vector2(0f, 0f));
slice.name = string.Format("[{0},{1}]", x, y);
sprites[x, y] = slice;
}
}
return sprites;
}
every frame in update is running this code, and i have reason to beleive that when i create a sprite i must delete it afterwards? i think this is a memory leak possibly? lmk what you think
soloution
Don't cross post...
is this your server?
It's in the server rules.
ohk sry
You are creating a new Texture2D every time you call RenderSprites.
Texture2D, like other objects inheriting from UnityEngine.Object, need to be destroyed manually or you get a memory leak, which explains the slowing down over time
so where and how should i delete it?
You use Destroy to destroy a UnityEngine.Object
Destroy it when you no longer need it, or create just one texture and reuse it
Not sure how you are using it, but from what I see, you probably should just reuse one texture
Oh, and I think the same goes with the Sprite that you are creating. That's also a Unity object
can i use this ? or does this not destroy it?
tex.hideFlags = HideFlags.HideAndDontSave;
Sprites too ^
To be clear, don't replace the object reference. Use the same object
Finally, Silksong.
so would this work?
private Texture2D tex;
^^^ global
if (tex == null)
{
Texture2D tex = new Texture2D(targetTexture.width, targetTexture.height, TextureFormat.RGB24, false);
}
no that is not working...
Instead of Texture2D tex = ... you should do tex = ...
Otherwise you are creating a separate local variable with the same name, tex
Also ofc that if-statement needs to be inside a method
I have maps (type of Tilemap). When OnBecameInvisible I want to signal a MapManager that map is outside a screen.
When the map is instantiated by the MapManager should I:
- Make a reference to the MapManager and call a method from it;
- Make an event on a map and subscribe MapManager's method to the event. Notice I have 200 maps instantiated at the start so that is 200 subscriptions.
- Other options or patterns I should use in this situation. Performance has more priority.
so doing,
tex = new Texture2D(targetTexture.width, targetTexture.height, TextureFormat.RGB24, false);
with a global reference will delete overwrite the current texture if it already exist, and will create one if it is null?
Nothing here is 'global'
You probably mean member/class variable
If you do that and the texture already exists, the old texture will still remain in memory and you get a memory leak
Which is why you should only create a new one if it is null
Just do this but remove the Texture2D as I instructed
@hexed pecan
ok so does this make sence for the array or sprites im creating?
old way
Sprite[] sprites = new Sprite[rows, columns];
Sprite slice = Sprite.Create(sprite.texture, new Rect(xPos, yPos, sliceWidth, sliceHeight), new Vector2(0f, 0f));
slice.name = string.Format("[{0},{1}]", x, y);
// Store the reference to the slice in the array
sprites[x, y] = slice;
new way
if (sprites == null)
{
sprites = new Sprite[rows, columns];
}
if (sprites[x, y] == null)
{
Sprite slice = Sprite.Create(sprite.texture, new Rect(xPos, yPos, sliceWidth, sliceHeight), new Vector2(0f, 0f));
slice.name = string.Format("[{0},{1}]", x, y);
// Store the reference to the slice in the array
sprites[x, y] = slice;
}
else
{
sprites[x, y] = Sprite.Create(sprite.texture, new Rect(xPos, yPos, sliceWidth, sliceHeight), new Vector2(0f, 0f));
}
In the else you are still creating a new Sprite, which will, again, cause a memory leak
I don't really work with sprites but if you can change the existing sprite's rect and texture, do that.
If not, Destroy the old sprite before creating a new one
i do not know how to destroy a sprite. only gameobjects. i dont understand how to
Destroy takes a UnityEngine.Object as an argument
GameObject, Sprite, Texture2D all inherit from UnityEngine.Object
so like this will work?
else
{
Destroy(sprites[x, y]);
sprites[x, y] = Sprite.Create(sprite.texture, new Rect(xPos, yPos, sliceWidth, sliceHeight), new Vector2(0f, 0f));
}
Looks ok
What are you making though? There might be a more optimized way of doing it
Instead of creating and destroying objects every frame
what is the bool operation name that returns true if both statements are false
this
if (!statement1 && !statement){
}
Yes, that
im asking about the name
like "or", "and", "nand", "xor"...
if it exists for that
Oh
&& is conditional and
|| is conditional or
sounds like there is no "name" for what i am looking for
There's no special name for that. It's an AND operation of two negations.
what about NOR? π
if(!(statement1 || statement2))
Pretty sure it's called NAND in electronics and stuff.
You don't see the term in software engineering much.
NAND would be !(statement1 && statement2)
Ah, right
oh ty, i swear i looked at it before asking
(!statement1 && !statement2) has the same result as NOR but nobody would ever describe that code saying that it's NOR
I am making a jigsaw like puzzle game, where the "completed jigsaw image" is animated using the camera to project UI component animations into the jigsaw pieces using sprites (so rentertex to tex2d to sprite multimode). the game basically relies on motion within the jiggies to solve, otherwise would be kinda impossible.
hey guys. i have 2 scripts. 1 is PlayerController and 2 is MouseLook. i use rigidbody to controll the player (move) so it causes slight jitter while also moving mouse/looking around (environment objects jitter). this of course doesnt happen when i switch to transform based movement on my PlayerController. any ideas how i can have rigidbody movement based PlayerController and MouseLook but fix the jitter? thanks.
Enable interpolation on the rb.
didn't fix it
is mouselook using lateupdate?
what mouselook?
Doesn't matter update type, still jittery
How are you moving the camera? It might be camera jitter, not player
Make sure the RB movement is in FixedUpdate too
delete from here, this is a code channel and ask in #β¨βvfx-and-particles
is there a callback for when IAP initiate purchase is completed, i need to a loading screen when i clicked the item in UI, then i will disable it when purchase screen is loaded
Yes there is
would you tell me what is it name or link me the docs?
My camera script works in update and playercontroller in fixedupdate because it uses rigidbody
I think thats the reason because i use fixedupdate for my rigidbody. But there's no other choice
change the camera update to be FixedUpdate or LateUpdate
I've been looking up for almost half an hour and yet not found anything
i dont use iap button and what i want is not when the purhcase is completed or failed
i need a loading screen that lives until purchasing screen is live
No crossposting
where can i ask for help?
You just did in #π»βcode-beginner
but they say it s not a coding problem
Then why tf did you post to another coding channel
i posted on both at the same time
i just want some help
You've had help
what help? u said it s a git folder pointing to nothing. how can i repair that?
Arguing is pointless, you've been pointed to a different channel because this is not code related, and I suggested you check for any git folders your project might have #πβfind-a-channel
i m not arguing π¦ i m just trying to find a solution to my problem
thx anyway
Hello, I have a question. I have a prototype I want to test on my phone so I started android build. I have a pretty powerful pc but I have never had build take this long. The project is fairly small so It makes no sense to me why it is taking so long. It is the first build of this project but still. Any ideas? Unity is 2021.3.0
what's your alternative
right, that's called object pooling and that's a concept you'd probably want to get familiar with
somewhere along the line you need to instantiate your objects into the scene, but it's not just the overhead of instantiation that's the problem but if you're actively destroying objects and re-instantiating then you may run into issues of performance hiccups at runtime
for a few objects it's probably not that big of a deal, but for example you've got a gun that's instantiating hundreds of physical bullets a minute, then that's something to consider pooling
if you're going to be reusing the object a lot, then you'd probably be best off just disabling it than outright destroying.
yep, sounds fine
I wouldn't worry too much until you do run into performance problem
When you pick items up, they dissapear from the floor and appear in the hand?
if yes, then just move them there
set their parent as the hand and position at the correct position on the hand
no need for spawning or enabling/disabling the objects
you can make a positioner object in the hand and set parent to it with position and rotations to Vector3.zero
Not sure for mp, but I dont see the reason it wouldnt work. If the object can be interacted with by every player, it shouldnt be a problem, but maybe ask in the networking channel
What are some good resources for a turn base jrpg combat system?
keeping stuff instantiated on the client is fine and hiding it
the internet
how to refer to child object of instantiated prefab?
Is Destroy called at the end of the frame or directly ?
end of frame iirc
neither, after Update
i missread with OnDestroy mb
so after the frame end?
basically
Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.
hmm
when i do that lateUpdate gives same result as Update. and fixedUpdate gives a little different result. it jitters as i move and also when i stand and look around, it feels laggy.
my object falls through ground then i add force to it even tho it has a box colider and rigidbody
Good for you
idk why the geo falls through the ground
ok
anyone write xml comments for doxygen etc? The xml 3 line minimum seems a bit space-taking! I realised you can do a single line 3 slash /// comment instead, I think can not be // but //! or ///
this is a code channel and that's not a code issue
my editor just auto builds out the string when i hit /// including the ones for params, but it does both open and closing tags inline for those with just summary on 3 lines
dont really think the spaces it takes is a huge deal, since am really only putting it on public and sometimes protected methods anyways
yeah mine too, though can toggle. But the text gets really spread out for say an interface if you add 3 line comments imho
still if its standard...
When using unity ruletile, is the right approach to seperate my grass (walkground) from my ground (walls and roofs) for example?
or can i just throw it all together, even if my tilemap is big
i switched from ontriggerenter to oncollisionenter and now it dont work
write
``` above the if statement. To see if the collision is detected at all. If there is no collision, objects are not set up correclty
oh i bet its caused by the skin width of the character controller again
-_-
for collisions both objects need a collider and one of them needs rigidbody
non-kinematic rb
how to get around that
its already non kinematic tho
is there a way to make ruletiles only interact with themselves? so if i place another tile above it which is not a ruletile it should not change
hey, can someone help me clamp my fps camera to -90 and 90?
Vector3 newCameraRotation = camHolder.localRotation.eulerAngles;
newCameraRotation += (Vector3.right * -inputView.y);
newCameraRotation.x = Mathf.Clamp(newCameraRotation.x, 0, 90);
newCameraRotation.x = Mathf.Clamp(newCameraRotation.x,0, 270);
camHolder.localEulerAngles = newCameraRotation;
transform.Rotate(Vector3.up, inputView.x);```
problem im having is that looking straight up is 270 on the X euler
and looking straight down is -90
so its kinda hard to get a clamp that does both if that makes sense
newCameraRotation.x = Mathf.Clamp(newCameraRotation.x, 0, 90);
newCameraRotation.x = Mathf.Clamp(newCameraRotation.x,0, 270);
you know that the 1st line
does completely nothing
as you are overriding it in the nexxt line
yes
ok
i know it doesnt work
Instead of relying on the Transform to store the current rotation, it's best to store the two angles yourself and then create the rotation from scratch with those angles and overwrite the transform's rotation with the newly created rotation. That way, your angles can be negative and you can clamp them before you create the rotation.
For example:
private Vector2 cameraAngles;
private void Update()
{
cameraAngles += inputView; // assuming inputView is where you get your camera look input.
// Clamp the y (vertical) angle
cameraAngles.y = Mathf.Clamp(cameraAngles.y, -90, 90);
Quaternion rotation = Quaternion.Euler(cameraAngles.y, cameraAngles.x, 0);
camHolder.localRotation = rotation;
}
makes sense, thanks. since my Y rotation is being done on the whole player and the X is on just the camera, how would i go about just changing one rotation axis of each object? is localEulerAngles.Set() alright for doing that?
or would i have to turn it into 2 vector3s and just do it like that
or i guess i can turn them into quaternions
Then you only need to worry about the X angle. The example becomes:
private float cameraAngle;
private void Update()
{
cameraAngle += inputView.y; // assuming inputView is where you get your camera look input.
// Clamp the angle
cameraAngle = Mathf.Clamp(cameraAngle, -90, 90);
Quaternion rotation = Quaternion.AngleAxis(cameraAngle, Vector3.right);
camHolder.localRotation = rotation;
}
I opted to use Quaternion.AngleAxis instead of Quaternion.Euler to create the rotation here. Both would give you the same rotation, AngleAxis is just a simpler method that works here because we only care about one axis.
https://discord.com/channels/489222168727519232/1209221022767652994
I'd like to bump this thread, since it has been a bit.
For some reason whenever I test jumps in the build of my game, it seems like only 1 in every 10 jumps is the proper height. The others seems much shorter than the jumps in the editor.
I put the most recent version of the player's movement code in there
hey y'all, who's familiar with Behaviour Tree, Behaviour designer in unity, i need help
i need a lil help
my health bar fills with a delay any1 has any idea why
like im setting the bar to max on an input but it doesnt fill it until i sprint again
In need of help in fixing a movement issue
Idk why but for some reason I'm locked to moving left and right and when I try moving backwards it suddenly starts going extremly high up and when I try going forward it causes me to start going down
I think it's due to MovePlayer() but I'm not sure what exactly is the issue with it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public Transform camera;
[Tooltip("Speed")]
[SerializeField]
private float speed = 5;
float hInput;
float vInput;
Vector3 moveDirection;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
hInput = 0;
vInput = 0;
if (Input.GetKey(KeyCode.W))
{
PlayerInput();
}
else if (Input.GetKey(KeyCode.S))
{
PlayerInput();
}
if (Input.GetKey(KeyCode.D))
{
PlayerInput();
}
else if (Input.GetKey(KeyCode.A))
{
PlayerInput();
}
}
private void FixedUpdate()
{
MovePlayer();
}
private void PlayerInput()
{
hInput = Input.GetAxisRaw("Horizontal");
vInput = Input.GetAxisRaw("Vertical");
}
private void MovePlayer()
{
moveDirection = camera.forward * vInput + camera.right * hInput;
rb.AddForce(moveDirection.normalized * speed, ForceMode.Force);
}
}
FixedUpdate can happen more than one time per frame. You're also setting hinput/vinput to 0 every update - you should just set them whenver input changes (or every update loop is fine)
also, use !code please
π 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.
My user can spawn objects into a simulation and save the current scenario as a preset that can be loaded later. When they go to the load preset menu, I want the list of presets to have an image beside each one showing what it looks like. This would involve screenshotting the simulation when it is saved, but I donβt really know how to implement this, nor how to use that screenshot after it is taken during runtime.
you can use ScreenCapture.CaptureScreenshot() to get an actual screenshot, but that's gonna get everything, and it's hard to know when you want to take the shot. You could also grab it from a camera in the scene.
Once you've got it, you'll have to make it available to the app - not sure of the best way to do this but I'd (personally) write it out to a file and load it into a texture in the preset menu. This might not be the best approach, I'm not aware of what unity has out of the box for stuff like this
Oh the camera to screenshot a section is a good idea
Does it have the option to screenshot from the camera instead of the whole screen
Rather, how
no - that's just generally for "entire-screen" captures
you wanna dig into "render textures from cameras"
depending on the size and nature of your presets you could have a .. box? with the stuff in them, and a camera pointed at the stuff in the box, and be rendering the camera's output directly to a texture that you show in the preset menu
ie - the textures would be "animated" and showing movement and stuff
that might be overkill but .. it's possible
if the list had 2 presets with 2 different scenarios but the camera would only be able to look at 1 simulation at a time
you'd have a camera for each
So Iβd have to run multiple simulations?
yeah
Unless Unity has superposition
i dunno what these are, but... imagine they're levels? or something, like I'm thinking mario maker - you'd spawn the level somewhere off screen, including a camera and a bot to "play" the level, and then on the preset menu, show a UI that's showing a render texture from that camera
and you'd do that for all of your simulations
hm, probably complex cpu-wise
so in any case, when you're in level design, you'll have some camera in the scene, snap a render texture and write it out to a file, then use that texture later in your preset menu
btw dont hesitate to ask me questions, youd probably not want to read through a big thread to understand the code situation
i think the key methods/apis you want to dig into are render textures, LoadImage(byte[]), and finding a place to stuff this byte[] data - I typically just throw stuff in the player folder and use File.WriteAllBytes() and File.ReadAllBytes() but your usecase might be different
if (Input.GetKeyDown(KeyCode.R)) { stamina = maxStamina;}
im using this in update function and it seems to update it after i sprint again yall know how to fix it?
If that is in update, then every frame that you press R you will set Stamina to max stamina
i am getting this issue
When do you update the bar
on pressing R
That updates the stamina variable. What updates the bar
staminaBar.fillAmount = stamina / maxStamina;
if (run == true)
{
stamina -= dValue*Time.deltaTime;
if(stamina < 0) stamina = 0;
staminaBar.fillAmount = stamina / maxStamina;
}
How about just show the full !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.
HEY GUIS SHOULD PHYSICS CODES GO IN UPDATEZ OR FIXEDUPDATEZ
Using Microsoft Speech SDK, when i stop playing i get an error: "Cannot dispose a recognizer while async recognition is running. Await async recognitions to avoid unexpected disposals." Problem is that the natural place to do this disposal is in OnDestroy ? making my Dispose function async won`t be ideal if in OnDestroy?, so kinda lost on this one.
So, the bar only updates while you're running. If you press R while you are not running, your stamina is refilled but you never tell the bar to update
You should update the bar if you refill it as well
Also your Recharge coroutine does nothing but you also aren't using it anywhere so I'm guessing it's just unfinished
yes the recharge is not finished tks alot
Do not bring beef from a thread to instigate drama on this server.
You know what you did. Stop it.
Also don't use all caps
no
Idk what his deal is
no need to get so emotional ladies
We all make choices in life. If you choose to act like a child, then I will choose to grab the moderators.
we can do this the easy way, or we can do this the hard way. the choice is yours.
AddForce should probably go in FixedUpdate, if it's using a time-dependent ForceMode. Velocity changes are probably fine to do in Update, since those are usually fairly constant
i know, it was sarcasm -- i was pointing out the obvious
@shrewd hornet Can you stop being annoying, thanks.
certainly
I know it was sarcasm I was using your tantrum to provide actual useful information in case anyone was reading this
very proactive of you - also 'tantrum' is a bit strong
pretty apt considering the circumstances
I guess you CAN'T stop being annoying...
anyways ima stop chatting here, this is a help channel
stop feeding the troll. block him and move on with your life
you are all wrong, considering UPDATEZ and FIXEDUPDATEZ don't exist. The correct answer is neither
Omfg I think I just realized what the issue with my code is
The reason why the forward and backward wasn't working was it's wasn't moving on the x and z axis but the x and y axis which was why it kept going up and down so high
Now I just need to figure out how to make that change to it
https://gdl.space/upidaxucoz.cs
my camera is following my rigidbody character. camera view was jittery due to rigidbody movement script using fixedUpdate and camera script using Update. after i lowered fixed timestep value it fixed the jitter. i was wondering how this will affect my project. is this a valid fix?
I have a blend tree with 8 directions referring to 8 different animations, but it's triggering the Event call in those animations 8 different times is this intended and I only need the event call in one of the animations? or is this a bug?
Before just switching to cinemachine to save a bit of time, I used to use Lerp on my camera to smoothen it out
but I still had FixedUpdate() jitter problems I think
you could use a statemachinebehaviour to trigger it instead of animation events (assuming that is what/how you're doing it, in the first place)
I didn't set up the character, I'm just the one working on fixing bugs with it now that the guy who did is no longer here, so... if there is a more standard way of doing it then I'm all ears, this seems very much like un-intended behavior
yeye, that shows one event trigger out of 8, set on that individual graph node..
..but you could have a state machine behaviour, at the 'higher level' that sits on the actual graph itself and looks at overall progress and then fires an event.
i believe, but then, i'll be honest ive never tried to mix and match animation triggers like that, and i have found that weird things happens when you start blending things with triggers and triggers contained within 'transition periods' of the animations
I've had issues with transition periods too, that was a thing I checked already, there isn't any transition period on this one at least so I ruled that out
Okay I was able to fix the flying issue now I'm just stuck with the issue where the player is stuck to moving only on the x axis
How do I fix this code to allow it to move on both the x and z axis?
https://gdl.space/pirufubedo.cs
This should be in #πβanimation
There are folks in there that will be able to help more
Hello, in my project I use Cinemachine camera. I Discovered something weird. I have kinda jittering effect when moving the camera. There is stable 60fps in build. Players complains about motion sickness with this. This effect I can see even just rotating around the camera without players movement.
I tried many things from google like:
-changing cinemachine to works on lateupdate/fixedupdate
-rigidbody's has interpolate/extrapolate
-updating cinemachine, unity
-vsync on/off
-disable any post proces effect like blur
-forcing cinemachine to follow a separate gameobject with rigidbody, and that gameobject force to follow the players eye
nothing of this change anything. This problem happens in editor and build
Is anyone here have other solutions?
Unity: 2022.3.16f1 with HDRP
show video
CM brain needs to use the same Update method that your movement is using
Update turns I was just an idiot who didn't realize that at somepoint I locked my z position
no wonder I was only able to move on one axis
How can I make a bool that becomes true for a little while after IsGrounded() = false?
When it becomes IsGrounded = false, start a timer.
Now I tried to set an string property to a singleton and then adding an script to the tmp text that updates the text every frame with the text in the singleton but the same error is thrown when trying to set the string variable inside the singleton
Using a coroutine?
I wouldn't, I would just track it in Update so it can be interrupted easily.
how long should the timer be?
How long do you want it to be π€
idk, I just need a way to set a variable true for a short amount of time, when another variable becomes false. So, idk, 0.5 seconds?
My current issue is the way I'm thinking of doing it, the timer would restart every frame that IsGrounded() = false how can I know when IsGrounded() just became false?
i do not have timers. I log timestamps.
You will need to cache the previous state of IsGrounded such that when it becomes false, you can check the previous one for if it was true. If so, you can handle what to do.
The timestamp method is really good for this in player movement. Specifically timestamps for: when jump button pressed, when jump button last released, and when last was grounded
Then check if you still count as grounded/jumping etc by comparing timestamp of when that event just occurred to Time.time, with some buffer window
private const float JUMP_BUFFER_TIME = 0.1f;
private bool JumpInputActive => timeLastJumpInput + JUMP_BUFFER_TIME < Time.time;```
like this
this makes it extremely easy to implement buffered jump input, coyote time, and controlled jumps (aka jump cut aka short hop)
and because you arenβt juggling bools turning them on/off, it is a lot easier to keep track of your player state. I canβt recommend this method enough
repeat for time last grounded, and again for time you last let go of the jump button
And you're just using the current system time for that?
Currently when the player goes onto a downward slope they get pushed up about 1 unit off of it? Here is my script: https://hastebin.com/share/oholojahaw.csharp. Here is a video: https://streamable.com/eb8f7d
@dense estuary this may be of interest: https://catlikecoding.com/unity/tutorials/movement/surface-contact/
It isnt flying upwards do to physics, I'm using CharacterController, it is floating exactly 1 meter off the ground.
and it also isnt sticking to the ground
Does it matter if you move the gravity function above the snap to ground in update? have you tried that?
maybe i'm wrong but my intuition is that you should do all movement first then do snaping. the cam function can be placed anywhere but if it follows the player it should come after
The page Carwash linked is not specific to rigidbody, if thats what you mean. Pretty sure you can apply it to CC movement too
The gravity function just sets the variable for gravity, currently it isnt being applied.
I'm looking into it rn
hmm ok, also i think this script is much too complicated for what you are trying to acheive.. anyone have thoughts on that? (it's not complicated, just could be alot simpler)
Yeah, it kinda hurts to look at, all I'm trying to do is make a character that can walk on or off slopes and jump. But everything I try I get a bunch of issues.
yes, if thats all you are trying to do, this is wayy over complicated.. let me think of approches to simplify
ingame time
Good tutorial in yt for Unitys particle system to learn basics?
it' there any way to create a ws connection which perdure between scenes without doing a singleton?
@dense estuary why arnt you using a rigidbody to handle this stuff?
I am trying to make an object shrink in size when ever this specific script is called, how do I do so?
thats what I have done but it doesnt seem to work, please help me
maybe because localScale is a Vector3 and you are subtracting an int
oh so what should I do instead?
https://docs.unity3d.com/ScriptReference/Transform-localScale.html have you bothered rtfm?
well, what do you think would make a Vector3 value smaller?
well that is for the 3d version...
this is unity 2d
the same
Because when I used a rigidbody the movement was super buggy and I could never figure out why. Also, I want to be able to stick to platforms going down.
Unity is a 3D engine, anything that applies to 2D applies to 3D
the only thing that changes is the Physics engine in the backend
why doesnt this work tho? @knotty sun @rigid island
because structs and properties
so how would i fix this?
what does error say
that aint it
also, because you need a vector3
thats the one
it's both, no?
you need to read your error messages
nah the -= is valid since its subs from another v3
they're using v2 but the original prop is v3
right, right, me being slow-brained today π
wait, if i want my script to change the sprite of the object to a different sprite from a spritesheet?
What's the question here?
how to change a sprite?
mySpriteRenderer.sprite = whateverSprite;
okay so basically i have this spritesheet and i want it to circle through the different dice in the sheet
for which of course you need references to the sprite and to the renderer
put them in array
just do [] and now you have array
well ik that far
eg public Sprite[]
so pick one from the array when you need it, its easy that dice face 1 will be at position 0 and so on
I have a script which creates shadow casters from a tilemap collider,
I want to modify the shadow casters to look something like this, how could I even aproach this, any ideas?
option 1: Make an animation with the sprites, which allows it to be handled via animator on a gameobject.
option 2: Turn them into an animated tile, which can be managed on a tilemap.
option 3: Individually reference each value separately by serializing an array in a monobehaviour or scriptableobject, and assigning each sprite into that array.
You probably want option 3, so you can more cleanly reference specific values.
From docs:
If nonzero, this number will be compared to the checksum of the downloaded asset bundle data. If the CRCs do not match, an error will be logged and the asset bundle will not be loaded. If set to zero, CRC checking will be skipped.
It's like a hash, for data integrity checking. At a low level, networking packets use some kind of CRC so the receiver can see if it got altered during transport, to request a resend
Checking if the asset on disk is up to date with what's online is done with the hash argument, not the CRC. The latter is purely for download integrity checking
Hi. I have one singleton (WebSocketManager) which calls the function SpawnQuestion of another singleton which contains in its properties a TMP_Text field. I set the field before runtime in the start method it's logged with a log but when I call the function spawn question and I set the text it turns me an error: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference
I don't know why. It has been occurring to me since yesterday. I tried to quit from singletones but I can't as I switch between scenes and I want to mantain ws connection open.
I need help.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
The usage of dynamic is probably the cause. Have you modified your JSON structure since the last time it worked fine? Dynamic resolves and binds the values you access at run-time (which makes it extremely slow), so it might just be a NullReferenceException in disguise. Maybe on line 145 data.metadata is null, and trying to access .type on it throws that exception?
Honestly I'd drop the dynamic stuff altogether, it removes one of the core features of the language: type safety
And rethink how the data is transmitted
you won't be able to use dynamic in IL2CPP btw
I am sending in the proper way but I'll double check it. I am using dynamics as I am not used to working with such complex types I need for my protect. I think the typing between typescript and c# id different so I don't know how to make generic types as in ts.
Json.NET has alternative approaches that don't use dynamic. Switch to those
what unity library uses StartCoroutine(); ?
The base message could be something like this:
class Message
{
public MessageType Type { get; }
public string Payload { get; }
}
And you do your if statement on the Type, and the Payload contains a JSON string you'll deserialize to another class. No need to make it complicated
For example I want to make the JSON having the metadata object the same in all the messages but having different payloads
So ```cs
class Message {
public metadata //metadata obj
public payload
}```
dfferent payload values are possible. Having made the clases for the different payloads how to set them as a type
@leaden ice Oh is only MonoBehaviour?
Yes StartCoroutine is a method on MonoBehaviour
if (message.Type == MessageType.Whatever)
value = JsonConvert.DeserializeObject<WhateverThing>(message.Payload);
if (message.Type == MessageType.SomethingElse)
value = JsonConvert.DeserializeObject<SomethingElseThing>(message.Payload);
Something like that?
You basicallyhave two deserializations. One for the whole message, and one for each specific message type
are coroutines kind of like context switching?
or like waiting for a child process before continuing
Neither
They're iterators, functions that return different values when you call them multiple times. Unity hijacks that feature to get the return value, and delay the next call to the iterator
It does not run in parallel, nor in a different thread
Well context switching isn't parallel nor a different thread either but I get your point
I thought it was storing the state of the program so it's recalled whenever another task has completed
Looks like Wikipedia has that definition too
oh sorry I kept forgetting that there's two types of parallelism, I was thinking of the hardware one that's mb
You could say it stores state though, as the iterator is compiled into a full class so it knows where the execution is, and what to execute at the next call
Mhmm
I was reading the example provided on the official documentation and had a few questions
If I have a for loop that yield return new WaitForFixedUpdate() every loop, do I have to explicitly stopCoroutine() or something like that
Also by this description, it seems to me that Unity hijacks the execution process where you write the yield... and waits for the condition to fulfill itself before it continues execution, is that right? Like an interrupt that continues only after you handle it
It's like the foreach loop, it generates a MoveNext() function and a Current property to advance through the iterator. Unity uses that at some point to know whether the coroutine has ended, and what (and how long) to wait for, respectively
maybe this very old post helps https://jahej.com/alt/2011_07_07_unity3d-coroutines-in-detail.html
Yeah the internals of coroutine handling might be done on the C++ backend, so most likely closed-source
thanks regardless, very informing!
If said loop is infinite, and you want to stop it at some point, then yes. Otherwise it'll keep running for as long as the Game Object the coroutine has been started on is alive and enabled
an important part of understanding Coroutines is the Unity message loop: https://docs.unity3d.com/Manual/ExecutionOrder.html
it's easy to think it's black magic how Unity "comes back" to the Coroutine, but it's all running on the internal message loop in a very similar way to Update() - this is where calling Next on the iterator happens
Wondering If anyone can give me some feedback, had a call/meeting today and towards the end i feel like I humiliated/embaressed myself,
But I was asked if i understood how to use the Profiler, and i said I'd "Never actually used it on a build, and don't have an in-depth understanding of it, but I do use it on a basic level to check texture memory, CPU spikes," that kind of thing.
And I was asked I think "How would I go about debugging a 100% reproducible 'Out Of Memory' " bug on a device, or even in the Editor,
My answer was to "check any logs that got generated," and then take a look at "what was happening in the scene" when the crash happens, and narow it down from there.
Shortly after everyone had to leave the call, and maybe it was just bad timing but it felt like maybe I'd missed some super beginner answer that I just shouldv'e known, depsite mentioning I don't have too much profiler experience,
Anyways, was wondering if anything stands out to any of you as an obvious response.
I also think I said "If there's a specific way to go about that, I don't think I'm familiar with it." This feels like something I shouldnt have said/was the dealbreaker
maybe more suited to a different channel, but Unity has a memoryprofiler package specifically for analysing a snapshot of memory where the profiler is more useful for performance profiling (though at a glance shows allocations & a rough idea of memory use)
They probably expected you to answer that you'd use the profiler to see what consumes most of the memory.
You can analyze the memory with the "classic" profiler btw, it's just more convenient with the new one(memory profiler package), since features like comparing snapshots are added, and overall it's a bit more precise and reliable.
@cosmic rain I guess I assumed it'd go without saying that I'd troubleshoot it with the profiler open as well, but coming in knowing "this person doesn't have too much experience with the profiler," would not knowing about using Snapshots be something just too amateur?
Typically, whatever engine you're using would have tools for debugging and profiling common issues, like performance, memory leaks, etc... I guess they expected you to know that.
That's how I'd do it: filter the graph to only show memory usage, notice that it's going up over time, select the time frame where there's the buildup (so it filters the hierarchy below), search the list for what takes/allocates the most, and drill down until you pinpoint the exact method that's allocating too much memory
You saying stuff about checking the logs and looking at the scene did sound like you don't k ow how to solve such issues,which was probably important to them.π€·ββοΈ
@simple egret so thats exactly what i do now- thats kinda i guess what I'm asking, thats the process i gave them,
and im wondering if they were expecting a specific answer
but if thats what stands out, then maybe I'm just overthinking it
Just to clarify, SPR is talking about the workflow with the profiler. Not the hierarchy in the scene.
If they didn't give you a specific project, or at least a profiling session file you could replay (if that's even possible), then no you cannot be more specific than this
@cosmic rain inm not talking about the hierarchy in the scene. im talking about the profiler
@simple egret okay thanks. I just basically said "I'd check any error logs, then go back and check what was going on in the scene (within the profiler) at the time of the crash"
The issue is that doesn't mention using the profiler at all
Out of memory will likely hard crash the game, producing very little to no logs
We can't know what they expected but that doesn't sound like the sort of thing worth ending an interview over, so you're probably overthinking it and/or there were places you weren't a good fit. If I were asking that question, I'd want an answer like "Well what's our hunch about what's causing the leak? Did I work on the project and so have an idea, or is there someone I should ask who worked on that part and would know?" If it's 100% reproducible, presumably we know most of what's causing it already and the important part is getting that context, not 'use the profiler to profile' (which seems too obvious to be worth asking about to me).
Well to be honest I can't really remember what I said, if I reiterated that I would be checking in the profiler whats eating the memory, CPU etc,
But I guess I thought It went without saying, If I'm familiar with the profiler and how it measures CPU usage and memory, that I would be using that as I went back to "check whats goin on in the scene."
But I don't know. Could be overthinking it.
thanks tho everyone for the help
And the call was more about my larger skills as a whole, just a brief touch on the profiler at the end
I'll look into it thanks
.net 4.0 seems not support BitShift function in BitArray Class. Is there any alternative to do bit shift for BitArray?
what are you trying to accomplish with bitshifting on a BitArray
A memoryBitStream system to read and write pack from the packect. I take the reference from the code in a C++ project. Actually it's a C++ server and C++ client. I want to move some client basic part to C# and dev game with unity. Do I have to move the bitstream system? Or there's some built-in function? Idk...
@somber nacelle
You need to work in bit level in cpp?
Yup.But the tutorial project say it's necessary but didn't tell me why⦠maybe for security I guess? I wonder which case should write some several bits instead of a byte(8bits) ?
You must add a byte since it is smallest unit cpu can deal with, afaik the only use case in writing (attach/remove bit from bit vector) in bit level is big integer
Do u mean the case like the interger is greater than the max largest range of int could represents?
I didn't understand add a byte?where do I add? Do u mean bit shift to byte instead of bits?
You can copy the source code online if you need it
SystemInfo.graphicsMemorySize shows me 3072MB of VRAM on a Windows desktop system with an 4070Ti 16GB. I was expecting to see 16GB, not 3GB. SystemInfo.graphicsDeviceName correctly shows me "NVIDIA GeForce RTX 4070 Ti SUPER".
SystemInfo.systemMemorySize shows me what I expect.
Any idea what's going on or what I'm missing?
The former is maybe reading your integrated CPU GPU?
Oh dear, that would be concerning if it wasn't reading the graphics size from the same GPU?
The machine has a Ryzen7800X3D, I wasn't able to easily find if 3GB is the right VRAM for that iGPU to see if that confirms it
But. Howw I can access message type without deserialize
I receive the type inside metadata.type
So what I thought it would work but I don't know if I can do it in c# is to set a type that could be all the payloads. And set it on the payload property
As the metadata property is always the same over messages
As I said I'm used to typescript and so in typescript I would only do Payload | Payload1 | Payload2 but I don't know how to do it in c#
you would write a custom JsonConverter for this in json.NET
is there a way to serialize not auto-implemented properties?
There are tons of ways to serialize properties
are you asking about some specific serializer though?
like, exposing it to the inspector
I.e. JsonUtility?
With Unity's built in serializer, you cannot serialize properties at all
only fields
:((
even with propertydrawers?
if you want to expose properties to the inspector
PropertyDrawer customizes how a serialized field is drawn
it cannot make non-serialized properties get drawn
thanks
And how I can do it
I am not used to do such complex thing in c#.
Wait, but in c# there is nothing to set a multi type property?
You can use generics
interfaces, abstract types, etc, yes.
There are no Unions though
You need to study it yourself, or see in Unity Asset store if you can find the thing youβre searching
But I want to set the returning type on NewtonsSoft deserialize as a message which contains all the payload types on its payload property and not a fixed payload.
So how I can make something which might work as an union
you can't
C# doesn't support unions
I don't see why you need one
use an interface or parent class
Because for each different message type a different payloads is sent
you either use an interface or parent class, or use multiple fields
So instead of setting a payload field I set all the field spread through the object and set them as no required (I don't know if I can in c#)
Not what I said
Or set the different payloads on different properties and set them as non required so I will have all the payloads
But what I said would fit in?
That's gonna be a waste and simply a bade design decision. Just define several classes for each message type.
C++ unions are basically a lazy way of doing just that(excluding some complex cases that require memory alignment and stuff)
just make the payload as json string then you can parse the payload however you like π
not a best practice though
You can create union by struct layout
Is implementing a singleton pattern necessary to create an effecient way to calculate score? I feel like id be able to do it without
But then id need a reference to the score script indtance in every single projectile (since score is based on projectiles dodged in my game)
Im still unsure how this works exactly even after a few tutorials
How would singleton pattern exactly help me in this situation?
No. Singleton is never a necessity and rarely recommended at all.
why is it rarely recommended?
Because it's sort of an anti pattern.
I recommend singletons all the time...
they make things quite simple for simple projects
It promotes undesirable coupling, makes testing and refactoring more difficult. In multithreaded context can create all sorts of issues due to accessing from several threads.
All of which are non issues in most simple projects
I do agree that there is a place for them. I just say that it's generally not the preferred way if there is an alternative
there is a solution for multithreaded situations
idk how it was but it wasnt a lot of code
what's the alternative? scriptableobjects?
There is a solution for any situation. The question is viability.
Pass your dependencies on construction, initialization.
i dont remember the code, it was all new stuff to me but it didnt seem to be too diffuclt
you would use something called Lock? idk
SOs can be fine. It's basically unity injecting the dependency for you.
Yes, you'd use some sort of lock or mutex. That brings other potential issues though.
oh i see
for every component? what if there is a soundmanager which we have to access from lots of places?
how do you guys suggest i approach my score system?
I am planning to, OnDestroy, check if a projectile has interacted with the player, if it hasnt, the player gets more score, which then the total score would be displayed at the top. Currently i have an empty object called Game Manager that holds the score script. For my solution to work, every projectile would need a reference to the Game Manager to then increment the score in it. But i will be only having one instance of the class score, so maybe there is a better way to approach this?
Don't access it from lots of places.π€·ββοΈ
Raise an event in something that is not directly related to sound and handle it somewhere on higher level.
you could maybe be using events to get rid of the reference
maybe
There might be situations, when a singleton would be viable. Depending on the context, Sound manager might be such a case. But there are some people who wouldn't use it in this case either.
Maybe use events?
Raise an event OnDestroyed or something and subscribe from wherever you spawn it.
hi, i'm developing an online game and users can freely change their profile picture & account data. everything in account menu displays information from account data (account data is a static class that has a class called accountinfo inside, which json deserializes into). i'm currently updating the information by using a simple notifier for my profile picture but users may change lots of things (their nickname, etc.) in the future or there might be a modal that needs to display live information for a short time and i don't want to fill my account class with notifier methods. here comes the my question:
what do people do in this situation? should i use unirx for this or is it an overkill?
(moved from #π»βunity-talk)
currenly looking into it π
but i do have a question, how would a static method work in this situation? and if it wouldnt work, why not?
cuz an event seems to be just like an if statement with a static method inside
It's fine if all the logic is static, but otherwise, you'd need an access to an instance somewhere.
Hard to say without seeing the code that you have in mind.
hover over it and see the error message
I found out π
I forgot an ;
this is my second time using C#
Good, then get used to reading all error messages
Also, in the future use !code and don't trim parts of it (such as here where you trimmed everything above line 8)
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Oh ye. I cut out the problem from the picture
Hey everyone, currently trying to code an attribute system for my items, but I'm having trouble doing so in a flexible and neat way. This is my code so far:
using System.Collections;
using System.Collections.Generic;
using NaughtyAttributes;
using UnityEngine;
[System.Serializable]
public class ItemAttribute
{
public ItemAttributeType type;
public ItemAttributeValueType valueType;
[EnableIf("valueType", ItemAttributeValueType.Float)] [AllowNesting] public float floatValue;
[EnableIf("valueType", ItemAttributeValueType.String)] [AllowNesting] public string stringValue;
[EnableIf("valueType", ItemAttributeValueType.Color)] [AllowNesting] public Color colorValue;
[EnableIf("valueType", ItemAttributeValueType.Vector2)] [AllowNesting] public Vector2 vector2Value;
[EnableIf("valueType", ItemAttributeValueType.Vector3)] [AllowNesting] public Vector3 vector3Value;
public bool display;
}
public enum ItemAttributeType
{
durability,
containerSize,
gun_firemode,
gun_magmode,
gun_damagepershot,
gun_bulletspershot,
gun_ammo
}
public enum ItemAttributeValueType
{
Float,
String,
Color,
Vector2,
Vector3
}
There are a couple of problems I'd like to solve, but don't know how.
- The value of the ItemAttribute class should ideally only be one variable, instead of 5 different ones that I have to choose between.
- The ItemAttributeType should have a key and a value, sort of like in a dictionary. For example "gun_magmode" should be key: gun, value: magmode.
I'm also open to suggestions on how to improve this in ways I haven't described here.
Thanks in advance for any help!
you do kow that C# has an object type, yes?
I know but how I can deserialize the JSON because it could be any type of message. Despite I design all the classes then I have to put one type only in the generic of the deserialize function
But how I can identify which payload is it I make it as JSON string but I can't know the type of message before I deserialize as I can't access metadata
Example:
{
"metadata" :{
"type": "any type"
},
"payload" : any payload
}
I can't identify the type if I don't deserialize it
I can check it with the string but it wouldn't be a nice way to do it
ah, the joys of JSON, solution: don't use json

