#archived-code-general

1 messages Β· Page 274 of 1

cosmic rain
#

"yeah" doesn't exactly answer my question...

daring hull
#

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

outer otter
#

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.

west sparrow
#

Probably health and lives

#

I like to get stats out if the way early on, and the UI.

outer otter
#

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

west sparrow
#

First step is the paper prototype though. Get the blibs working and make sure it's fun first

outer otter
#

yea i got a fps movement system I can use for the rest of my projects now, its really nice

west sparrow
#

I'm not sure what that is. But I'm definitely a check off the core first kind of person

frosty siren
west sparrow
#

No, green hell

frosty siren
# west sparrow 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

outer otter
#

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

frosty siren
outer otter
#

yea i guess loll

#

how can i make a player only jump once when the spacebar is held?

#

i should push this to beginner

lean sail
outer otter
#

its hard to know what you need, i overthink it

cosmic rain
#

Don't you have some main idea behind the game, a pivotal mechanic or something?

orchid abyss
mossy snow
#

you have 3 bugs in there, two of which are helpfully underlined for you to mouse over

orchid abyss
fervent furnace
#

not code general

orchid abyss
mossy snow
#

3 bugs down, 1 new bug added

frosty siren
#

local variable pain

orchid abyss
mossy snow
#

nice. Now only code smells remain

mild coyote
hexed pecan
#

I dont think the cast (ParticleSystem) is necessary

orchid abyss
hexed pecan
#

Hmm you are instantiating the blood itself?

#

Better use a prefab reference instead, I think

mossy snow
# orchid abyss huh

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
mild coyote
#

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

mossy snow
#

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

mild coyote
#

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

mossy snow
#

hence, very smelly code thinksmart

lean sail
#

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

mild coyote
#

if it has no ||game breaking|| bugs, and it runs butter smooth, then it's good enough for me πŸ˜…

mossy snow
#

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

mild coyote
#

well, let's hope that the game is shipped before 6 months then

frigid glen
#

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?

hexed pecan
frigid glen
#

Its a camera rendering to a render texture, and that render texture doesn't cover the entire screen. So yes

hexed pecan
#

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?

frigid glen
#

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.

modest brook
#

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)
{
   
}

}`

frigid glen
#

animator is cancer for UI

#

just change the postions through code

#

its called tweening

modest brook
#

how can i do it?

frigid glen
#

get rect transform of UI

modest brook
#

because i managed to the other day but the transition wasn't clean

frigid glen
#

change anchored position

#

define clean?

#

like it doesn't ease?

#

make an easing function

modest brook
frigid glen
#

idk use lerp or something

modest brook
hexed pecan
modest brook
#

holy shit just looked at a tutorail its solvinmg all of my problems

hexed pecan
# frigid glen yup

If you already have a world space coordinate, you can just use camera.WorldToScreenPoint/WorldToViewportPoint on that main camera

frigid glen
mild coyote
#

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);
modest brook
#

guys really quick is there a way to mention scale in coding?

#

like instead of transform.position

#

transform.scale instead?

mild coyote
#

transform.localscale?
if you've set up intellisense properly, a suggestion should popup when you tipe 'transform.scale'

modest brook
#

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

mellow sigil
#

First configure the !ide πŸ‘‡

tawny elkBOT
modest brook
mellow sigil
#

Yes, after you've configured the IDE

modest brook
#

its downloading

#

thank u so much

#

πŸ₯Ί

orchid abyss
frigid glen
modest brook
thin aurora
#

Can also use the collider bounds

mellow sigil
modest brook
frigid glen
frigid glen
#
Vector2 snapPos = Collider2DHelper.FindClosestPointOnBody(_currentRay.Value.rigidbody, _mousePosition);
Vector2 snapScreenPos = _creationCamera.WorldToScreenPoint(snapPos);
_displayTexture.rectTransform.anchoredPosition = snapScreenPos;
mild coyote
#

also, if you are using screen position instead of viewport, change from 0 and 1 to 0 and screen.width(or height for y)

nimble cairn
#

Will OnTriggerEnter still run physics checks even if there is not a trigger component on the gameobject?

tawdry jasper
#

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.

nimble cairn
#

Thanks, I was worried that it was hogging up resources.

tawdry jasper
#

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?

cosmic rain
tawdry jasper
# cosmic rain 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

lean sail
#

Regardless you need to show code for help with the errors specifically. Or just follow what the error says about it being null

tawdry jasper
#

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 )

lean sail
#

Well ya if you disable a collider, you arent gonna get a physics message for it..

tawdry jasper
#

not disabling the collider. calling rigidBody.detectCollissions = false

#

This seems to affect any trigger colliders under that rigidbody in the hierarchy.

old nymph
#

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.

deft timber
old nymph
deft timber
#

rect transforms, works on anchoredPosition

#

and you should modify that instead

#
  • anchoredPosition
#
  • position
old nymph
#

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.

deft timber
#

there is no local/world position for the UI elements

#

it's jsut anchoredPosition

old nymph
#

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.

tawdry jasper
#

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?

narrow summit
#

anybody has a handy json convertor which works for AnimationCurves?

latent latch
#

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

late lion
latent latch
#

Ah, right they should be serializable. I'm thinking animation clips themselves, but AnimationCurves are very much just a collections of keys.

thin aurora
#

Even if it works

thin aurora
#

Serializers like Newtonsoft allow for custom serialization based on type so you can make this an automated system on serialization, to avoid mistakes

violet cipher
#

where can i ask for help with some code

violet cipher
#

oh so here

thin aurora
violet cipher
#

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

thin aurora
violet cipher
#

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

cosmic rain
tawny elkBOT
narrow summit
#

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

near oyster
#

is there a channel, where I can ask for an error message?

violet cipher
#

or somwhere else?

rigid island
near oyster
rigid island
cosmic rain
near oyster
cosmic rain
#

I give you my permission

rigid island
violet cipher
#

Properties not drawn in right place

near oyster
#

ok, ty

mellow forge
#

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

vapid condor
mellow forge
#

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

vapid condor
#

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

mellow forge
#

i see ok

vapid condor
#

wait so you want for the player to die only when health reaches less then 0? not equal to 0

mellow forge
sudden relic
#

I wonder if it has to do with your state transitions.

mellow forge
grand compass
#

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.

mellow forge
#

im not sure i never tried

sudden relic
#

Are you able to confirm whether or not the code is getting into the if statement within deathAnim_PLay?

mellow forge
#

lemme try

sudden relic
#

That would help us understand where we should look further

mellow forge
#

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

grand compass
mellow forge
#

i tried something else i changed the death deadline to 10 and it worked

#

but when its 0 you have to be hit twice

swift falcon
#

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.

prime sinew
swift falcon
prime sinew
#

okay, can you please show the current code?

swift falcon
#

wait

fervent furnace
prime sinew
#

so button as in UI button?

#

or keyboard key press?

swift falcon
#

AttackButton.onClick.AddListener(Attack);

soft shard
# grand compass How would you guys go about visualizing a box cast? I have a Pyhsics.BoxCast, b...

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

GitHub

Debugging Utilities for Unity. Contribute to vertxxyz/Vertx.Debugging development by creating an account on GitHub.

prime sinew
# swift falcon ui

see the thread that was shared to you. mainly the point about using EventTrigger

grand compass
modest brook
# tawny elk

i have been trying to get him but its not free

#

is IDE free anyone?

jagged snow
#

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

naive swallow
tawny elkBOT
mellow sigil
#

not sure why you'd subtract 1 from it unless it has some kind of "none" item

jagged snow
#

trying it now

#

it works thank you!

bright maple
#

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&

modest brook
naive swallow
modest brook
#

it didnt work

naive swallow
static matrix
#

but idk if that is your problem

bright maple
#

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.

static matrix
#

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

bright maple
#

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.

jade latch
#

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.

static matrix
#

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

bright maple
jade latch
#

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

static matrix
#

it is

#

tbh the solution is to not use negative values in a place like this

#

or something with mathf.abs

leaden ice
static matrix
#

yeah or that

bright maple
leaden ice
#

so yes, adding half the size of the array.

jade latch
#

i tried that but it pushed the issue just further down but i can implement it and work from there

leaden ice
#

I mean it's an entirely tractable problem, you just have to give it a little thought

bright maple
#

It's a workaround I guess
Also, hi Praetor. Glad to see you're still dishing out helpful coding advice to people

leaden ice
#

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

jade latch
#

im quite new to c# so not too sure what that is

leaden ice
#

You should go look it up. It's extremely useful and common

jade latch
#

i will thanks

leaden ice
#

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.

jade latch
#

ahh maps im slightly familiar with from js

leaden ice
#

it's the same thing

#

in fact every JS object is essentially a Dictionary<string, object>

jade latch
#

but still very little clue on how they work tbh

jade latch
leaden ice
#

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

static matrix
#

or null in the chess case

leaden ice
#

I mean you could have it be null or you could just not have that coordinate in the dictionary, which would be cleaner

naive swallow
frosty siren
#

touche

jade latch
#

fair enough, what i want with that code is to display every place that piece can go to (any spot within a range)

static matrix
leaden ice
#

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

jade latch
#

its not to track where each piece is but rather where they can go

leaden ice
#

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

static matrix
#

oh yeah I guess heh

leaden ice
#

if the space is in the set, it's legal, otherwise it's not legal

latent latch
#

infinite grids usually are dictionaries, but if you got like a chess size board I'd just make the 2D array

jade latch
#

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

leaden ice
#

well yes chess is typically an array but chess was an example for illustration, they're not making chess

mystic pollen
#

is this the place i can get help with code

jade latch
#

its an very advanced version of chess tbf

leaden ice
#

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.

latent latch
#

chess 2.0

jade latch
jade latch
leaden ice
#

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

jade latch
#

i wish so too

leaden ice
#

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.

jade latch
#

ill have to look at the code i made to define the cordinates to see if i can adjust that

spring creek
jade latch
#

that worked, why did i not think of that before

royal wigeon
#

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?

latent latch
#

use an animation curve

royal wigeon
#

I have no idea what that is yet, I haven't dived much into animations.

main coral
#

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 ?

simple egret
#

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

main coral
#

Where is my mistake ? In the dropdown component ?

simple egret
#

No, probably in the code that handles it

main coral
#

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

simple egret
#

Yeah the On Value Changed event will pass the index, not the option text to your function

main coral
#

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)

simple egret
#

Yes that's normal!

#

Because the option with the text "6" is third in the list, so at index 2

main coral
#

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);

simple egret
#

That would be the text of the selected option, and you will get it as a string.

main coral
#

how do I get the text of the selected field ?

simple egret
#

dropdown.options[dropdown.value].text

#

If I remember correctly

main coral
#

is there a way to get it as int ?

simple egret
#

Not directly, you need to convert it, like with int.Parse()

main coral
#

thanks a lot

vagrant blade
#

@zealous crane don't crosspost

zealous crane
main coral
#

this did work for me:
int selectedValue = int.Parse(m_uILobbies.MyPlayerCountDropDown.options[m_uILobbies.MyPlayerCountDropDown.value].text);

bright maple
#

Fixing Jump Inconsistency

sullen crown
#

[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?

simple egret
#

Try inputting git in a command line terminal, and make sure the command is recognized.

sullen crown
#

wee, it doesnt exist notlikethis

simple egret
#

Install it and try again. You'll need to restart your computer (or log out -> log in) so the changes are applied

sullen crown
#

yea, doing tht

#

i am wondering how is source tree and github client working

simple egret
#

I think these have the library bundled into them, so they're fast and easy to install and set up

sullen crown
#

probably .. ty

#

i will check out after restarting

swift falcon
#

i have a question for c++ interperatation

#

cus im working on a game that wants to utilize c++ code

#

and c# as well

knotty sun
swift falcon
#

ok, but i need help with also adding game objects to a scene while using c++

#

idk if they could provide that

knotty sun
#

sounds like modding which is not allowed here

swift falcon
#

ok

lavish frigate
#

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

swift falcon
#

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?

charred ruin
lavish frigate
charred ruin
#

I haven't worked much with 2D but I heard this is good pathfinding tool: https://learn.unity.com/project/a-36369ng

Unity Learn

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.

finite otter
#

For my VR Game it says that it cannot find Photon3Unity3D.dll even though i have it does anyone know the solution

charred ruin
#

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));
    }
marble mauve
#

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.

somber nacelle
#

what is line 40 or PersistentManager.cs

marble mauve
#
this.Text.text = "test"
somber nacelle
#

then you are likely calling that method before the Text variable has been assigned or on an instance where it has not been assigned

marble mauve
#

One possible reason could be that all the container where the text resides is disabled but I active it before changing the text

somber nacelle
#

you've shown a single line of code so i can only guess at what it is. consider showing more code

marble mauve
#

It could be that the persistent manager is created before the text component was created?

mossy snow
frosty sequoia
#

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

tight ice
#

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)

quartz folio
#

It just looks like it's probably not over the edge enough

tight ice
deep oyster
#

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

hard viper
#

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

rigid island
#

2 localization questions back to back , nice

hard viper
#

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

quartz folio
#

There's an entire localization package

chilly surge
#

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.

hard viper
#

yeah… I’m trying to avoid reinventing the wheel as much as possible.

hard viper
quartz folio
#

I have barely touched it

hard viper
deep oyster
rigid island
cold parrot
#

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.

crisp bronze
#

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

quartz folio
#

localToWorldMatrix already includes the position, don't additionally use transform.position to offset it

hard viper
#

also make sure this is in OnGizmosDraw…Selected etc

faint hornet
#

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.

fervent furnace
#

Where you call the init

#

Probably through some indexer?

faint hornet
#

Ive tried awake and start;

private void Start()
  {
    foreach (var item in instruct)
    {
      item.Init();
    }
  }
fervent furnace
#

Item is local copy

#

It wont affect anything in the collection

faint hornet
#

do i need an OG forLoop?

fervent furnace
#

What is instruct, array or list

faint hornet
#

How do i call init()?

#

Array

fervent furnace
#

Then use forloop and use indexer call directly

cosmic rain
#

I think you'll be accessing a copy in any case. You'll need to copy the initialized struct back into the array.

faint hornet
#

like

intruct[i].init();

??

cosmic rain
#

I think that's gonna be a copy too.

faint hornet
#

hmm. this is weird i don't understand why

fervent furnace
#

Array indexer not indexer, it actually dereferencing the address

#

Not returning the copy

faint hornet
#

would a list be different? should i use that?

fervent furnace
#

Indexer of list is returning the copy

cosmic rain
faint hornet
cosmic rain
#

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.

faint hornet
cosmic rain
#

Yes

faint hornet
#

ok ❀️

fervent furnace
#
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
    }
}
swift falcon
#

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??

swift falcon
#

@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...

latent latch
#

You can just do the trees yourself and disable them independently, but disabling a whole terrain may have some overhead.

swift falcon
lean sail
#

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

swift falcon
#

is there anything like enabling objects asynchronously?

fervent furnace
#

Coroutine

lean sail
latent latch
#

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.

swift falcon
swift falcon
lean sail
orchid abyss
#

why isn't it working?

swift falcon
vagrant blade
orchid abyss
#

when i instantiate the blood it rotates properly but otherwise it doesn't

vagrant blade
#

Baffling how anyone was supposed to gather that was the issue lol πŸ€”

orchid abyss
#

my bad

swift falcon
orchid abyss
#

ill post a vid wait

mossy snow
# orchid abyss why isn't it working?

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

orchid abyss
mossy snow
#

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

orchid abyss
#

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

upper burrow
#

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

cosmic rain
swift falcon
# lean sail I dont recall that being a thing specifically, yield return null will basically ...

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?

fervent furnace
#

Dont know terrain, but the how many objs you have not affect your strategy (split them up and disable partial of them each frame)

marble mauve
#

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

mossy snow
#

if your singleton can be created on-demand, then you have two potential issues:

  1. 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
  2. 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
lean sail
swift falcon
marble mauve
mossy snow
#

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

spring creek
marble mauve
# mossy snow you might need to provide more context about what you're trying to achieve becau...

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.

faint hornet
#

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

glacial pasture
#

soloution

cosmic rain
#

Don't cross post...

glacial pasture
cosmic rain
glacial pasture
hexed pecan
faint hornet
hexed pecan
#

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

faint hornet
hexed pecan
#

That does not destroy it, no

faint hornet
#

so how do i reuse it?

#

just save a reference to it and then rewrite it?

hexed pecan
#

Create it once and store a reference to it

#

Yeah

hexed pecan
dawn nebula
faint hornet
#

no that is not working...

hexed pecan
#

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

mystic gull
#

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:

  1. Make a reference to the MapManager and call a method from it;
  2. 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.
  3. Other options or patterns I should use in this situation. Performance has more priority.
faint hornet
hexed pecan
#

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

hexed pecan
faint hornet
#

@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));
}
hexed pecan
#

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

faint hornet
hexed pecan
#

Destroy takes a UnityEngine.Object as an argument

#

GameObject, Sprite, Texture2D all inherit from UnityEngine.Object

faint hornet
hexed pecan
#

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

round violet
#

what is the bool operation name that returns true if both statements are false

#

this

if (!statement1 && !statement){
}
thin aurora
#

Yes, that

round violet
#

im asking about the name

#

like "or", "and", "nand", "xor"...

#

if it exists for that

thin aurora
#

Oh

#

&& is conditional and

#

|| is conditional or

round violet
#

sounds like there is no "name" for what i am looking for

mellow sigil
#

There's no special name for that. It's an AND operation of two negations.

mild coyote
cosmic rain
#

You don't see the term in software engineering much.

mellow sigil
#

NAND would be !(statement1 && statement2)

cosmic rain
#

Ah, right

round violet
mellow sigil
#

(!statement1 && !statement2) has the same result as NOR but nobody would ever describe that code saying that it's NOR

faint hornet
warm kraken
#

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.

cosmic rain
warm kraken
#

didn't fix it

mild coyote
#

is mouselook using lateupdate?

deft timber
#

what mouselook?

warm kraken
trim schooner
#

How are you moving the camera? It might be camera jitter, not player

#

Make sure the RB movement is in FixedUpdate too

craggy veldt
#

oh mb I completely forgot that

#

done

vestal crest
#

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

trim schooner
#

Yes there is

vestal crest
#

would you tell me what is it name or link me the docs?

warm kraken
#

I think thats the reason because i use fixedupdate for my rigidbody. But there's no other choice

trim schooner
#

change the camera update to be FixedUpdate or LateUpdate

vestal crest
vestal crest
#

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

thin aurora
#

No crossposting

tired niche
thin aurora
tired niche
mellow sigil
#

Then why tf did you post to another coding channel

tired niche
#

i just want some help

thin aurora
#

You've had help

tired niche
thin aurora
#

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

tired niche
#

thx anyway

placid compass
#

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

latent latch
#

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

placid compass
#

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

placid compass
#

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

midnight void
#

What are some good resources for a turn base jrpg combat system?

latent latch
#

keeping stuff instantiated on the client is fine and hiding it

orchid abyss
#

how to refer to child object of instantiated prefab?

round violet
#

Is Destroy called at the end of the frame or directly ?

rigid island
knotty sun
round violet
#

ty

#

so yeah its at the end

#

like a scene load

knotty sun
round violet
#

i missread with OnDestroy mb

rigid island
#

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

warm kraken
orchid abyss
#

my object falls through ground then i add force to it even tho it has a box colider and rigidbody

thin aurora
#

Good for you

orchid abyss
#

idk why the geo falls through the ground

deft timber
#

ok

placid summit
#

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 ///

trim schooner
quaint rock
#

dont really think the spaces it takes is a huge deal, since am really only putting it on public and sometimes protected methods anyways

placid summit
#

still if its standard...

lavish frigate
#

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

orchid abyss
#

i switched from ontriggerenter to oncollisionenter and now it dont work

placid compass
orchid abyss
# deft timber ok

oh i bet its caused by the skin width of the character controller again

#

-_-

placid compass
#

for collisions both objects need a collider and one of them needs rigidbody

deft timber
#

non-kinematic rb

orchid abyss
#

its already non kinematic tho

lavish frigate
#

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

mossy minnow
#

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

deft timber
#
      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

mossy minnow
#

yes

deft timber
#

ok

mossy minnow
#

i know it doesnt work

late lion
# mossy minnow hey, can someone help me clamp my fps camera to -90 and 90? ``` Vector3 ...

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;
}
mossy minnow
#

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

late lion
#

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.

bright maple
#

I put the most recent version of the player's movement code in there

icy comet
#

hey y'all, who's familiar with Behaviour Tree, Behaviour designer in unity, i need help

stone hare
#

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

vital granite
#

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);
    }
}
modern creek
#

also, use !code please

tawny elkBOT
terse quarry
#

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.

modern creek
#

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

terse quarry
#

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

modern creek
#

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

terse quarry
#

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

modern creek
#

you'd have a camera for each

terse quarry
#

So I’d have to run multiple simulations?

modern creek
#

yeah

terse quarry
#

Unless Unity has superposition

modern creek
#

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

terse quarry
#

It’s a 2D space simulation

#

N body gravity

modern creek
#

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

terse quarry
#

Will do

#

Thanks a lot

bright maple
modern creek
#

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

stone hare
#

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?

naive swallow
stone hare
naive swallow
stone hare
#

on pressing R

naive swallow
stone hare
#

staminaBar.fillAmount = stamina / maxStamina;

#

if (run == true)
{
stamina -= dValue*Time.deltaTime;
if(stamina < 0) stamina = 0;
staminaBar.fillAmount = stamina / maxStamina;
}

naive swallow
tawny elkBOT
stone hare
shrewd hornet
#

HEY GUIS SHOULD PHYSICS CODES GO IN UPDATEZ OR FIXEDUPDATEZ

wide raft
#

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.

naive swallow
#

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

stone hare
hard viper
#

You know what you did. Stop it.

spring creek
#

Also don't use all caps

shrewd hornet
#

no

bright maple
#

Idk what his deal is

shrewd hornet
#

no need to get so emotional ladies

hard viper
#

We all make choices in life. If you choose to act like a child, then I will choose to grab the moderators.

warm kraken
#

we can do this the easy way, or we can do this the hard way. the choice is yours.

naive swallow
shrewd hornet
vagrant blade
#

@shrewd hornet Can you stop being annoying, thanks.

naive swallow
shrewd hornet
bright maple
#

pretty apt considering the circumstances

spring creek
#

I guess you CAN'T stop being annoying...

bright maple
#

anyways ima stop chatting here, this is a help channel

hard viper
knotty sun
#

you are all wrong, considering UPDATEZ and FIXEDUPDATEZ don't exist. The correct answer is neither

vital granite
warm kraken
#

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?

carmine cloud
#

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?

bright maple
#

but I still had FixedUpdate() jitter problems I think

shrewd hornet
carmine cloud
#

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

shrewd hornet
# carmine cloud

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

carmine cloud
#

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

vital granite
spring creek
agile rock
#

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

warm kraken
#

show video

trim schooner
#

CM brain needs to use the same Update method that your movement is using

vital granite
dense estuary
#

How can I make a bool that becomes true for a little while after IsGrounded() = false?

vagrant blade
#

When it becomes IsGrounded = false, start a timer.

marble mauve
dense estuary
vagrant blade
#

I wouldn't, I would just track it in Update so it can be interrupted easily.

dense estuary
trim schooner
#

it should be as long as you need it to be

#

that's a game design choice

vagrant blade
dense estuary
vagrant blade
#

Sure?

#

The amount of time is irrelevant here

dense estuary
#

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?

hard viper
#

i do not have timers. I log timestamps.

vagrant blade
#

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.

hard viper
#

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

hard viper
trim schooner
#

And you're just using the current system time for that?

dense estuary
trim schooner
dense estuary
#

and it also isnt sticking to the ground

faint hornet
#

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

hexed pecan
dense estuary
faint hornet
dense estuary
faint hornet
brazen tartan
#

Good tutorial in yt for Unitys particle system to learn basics?

marble mauve
#

it' there any way to create a ws connection which perdure between scenes without doing a singleton?

faint hornet
#

@dense estuary why arnt you using a rigidbody to handle this stuff?

swift falcon
#

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

knotty sun
#

maybe because localScale is a Vector3 and you are subtracting an int

swift falcon
#

oh so what should I do instead?

rigid island
knotty sun
#

well, what do you think would make a Vector3 value smaller?

swift falcon
#

this is unity 2d

knotty sun
#

the same

dense estuary
rigid island
#

the only thing that changes is the Physics engine in the backend

swift falcon
#

why doesnt this work tho? @knotty sun @rigid island

little meadow
#

because structs and properties

swift falcon
#

so how would i fix this?

rigid island
little meadow
#

also, because you need a vector3

rigid island
#

thats the one

little meadow
#

it's both, no?

leaden ice
rigid island
#

they're using v2 but the original prop is v3

little meadow
#

right, right, me being slow-brained today πŸ˜…

swift falcon
#

wait, if i want my script to change the sprite of the object to a different sprite from a spritesheet?

leaden ice
#

how to change a sprite?
mySpriteRenderer.sprite = whateverSprite;

swift falcon
#

okay so basically i have this spritesheet and i want it to circle through the different dice in the sheet

leaden ice
#

for which of course you need references to the sprite and to the renderer

swift falcon
#

im new w arrays

rigid island
#

just do [] and now you have array

swift falcon
#

well ik that far

rigid island
#

eg public Sprite[]

rigid island
lunar kestrel
#

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?

hard viper
#

You probably want option 3, so you can more cleanly reference specific values.

simple egret
#

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

marble mauve
#

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.

https://pastebin.com/AhykNggA

simple egret
#

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

leaden ice
marble mauve
#

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.

leaden ice
faint hornet
#

what unity library uses StartCoroutine(); ?

simple egret
#

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

marble mauve
#

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

faint hornet
#

@leaden ice Oh is only MonoBehaviour?

leaden ice
simple egret
vale bridge
#

are coroutines kind of like context switching?

#

or like waiting for a child process before continuing

simple egret
#

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

vale bridge
#

Well context switching isn't parallel nor a different thread either but I get your point

simple egret
#

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

vale bridge
#

oh sorry I kept forgetting that there's two types of parallelism, I was thinking of the hardware one that's mb

simple egret
#

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

vale bridge
#

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

vale bridge
simple egret
#

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

simple egret
#

Yeah the internals of coroutine handling might be done on the C++ backend, so most likely closed-source

vale bridge
#

thanks regardless, very informing!

simple egret
mental rover
#

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

stone loom
#

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

mental rover
cosmic rain
#

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.

stone loom
#

@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?

cosmic rain
simple egret
#

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

cosmic rain
#

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.πŸ€·β€β™‚οΈ

stone loom
#

@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

cosmic rain
simple egret
#

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

stone loom
#

@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"

simple egret
#

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

wicked scroll
# stone loom but if thats what stands out, then maybe I'm just overthinking it

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).

stone loom
#

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

narrow yoke
#

.net 4.0 seems not support BitShift function in BitArray Class. Is there any alternative to do bit shift for BitArray?

somber nacelle
#

what are you trying to accomplish with bitshifting on a BitArray

narrow yoke
#

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

fervent furnace
#

You need to work in bit level in cpp?

narrow yoke
#

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) ?

fervent furnace
#

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

narrow yoke
#

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?

fervent furnace
#

You can copy the source code online if you need it

kindred wagon
#

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?

leaden ice
kindred wagon
marble mauve
#

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#

leaden ice
candid kiln
#

is there a way to serialize not auto-implemented properties?

leaden ice
#

are you asking about some specific serializer though?

candid kiln
#

like, exposing it to the inspector

leaden ice
#

I.e. JsonUtility?

leaden ice
#

only fields

candid kiln
#

:((

leaden ice
#

You can use e.g. OdinInspector or a custom editor

#

or NaughtyAttributes

candid kiln
#

even with propertydrawers?

leaden ice
#

if you want to expose properties to the inspector

leaden ice
#

it cannot make non-serialized properties get drawn

candid kiln
#

thanks

marble mauve
#

Wait, but in c# there is nothing to set a multi type property?

quaint reef
leaden ice
quaint reef
marble mauve
# quaint reef You can use generics

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.

marble mauve
leaden ice
#

C# doesn't support unions

#

I don't see why you need one

#

use an interface or parent class

marble mauve
#

Because for each different message type a different payloads is sent

leaden ice
#

you either use an interface or parent class, or use multiple fields

marble mauve
#

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#)

leaden ice
#

Not what I said

marble mauve
#

Or set the different payloads on different properties and set them as non required so I will have all the payloads

marble mauve
cosmic rain
#

C++ unions are basically a lazy way of doing just that(excluding some complex cases that require memory alignment and stuff)

mild coyote
#

not a best practice though

fervent furnace
#

You can create union by struct layout

terse surge
#

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?

cosmic rain
candid kiln
cosmic rain
#

Because it's sort of an anti pattern.

leaden ice
#

I recommend singletons all the time...

#

they make things quite simple for simple projects

cosmic rain
#

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.

leaden ice
#

All of which are non issues in most simple projects

cosmic rain
#

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

terse surge
#

idk how it was but it wasnt a lot of code

candid kiln
#

what's the alternative? scriptableobjects?

cosmic rain
cosmic rain
terse surge
#

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

cosmic rain
#

SOs can be fine. It's basically unity injecting the dependency for you.

cosmic rain
terse surge
#

oh i see

cosmic rain
#

Like a deadlock

#

Anyways, my point is singletons are never "necessary"

candid kiln
terse surge
#

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?

cosmic rain
#

Raise an event in something that is not directly related to sound and handle it somewhere on higher level.

candid kiln
cosmic rain
#

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.

cosmic rain
#

Raise an event OnDestroyed or something and subscribe from wherever you spawn it.

candid kiln
#

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)

terse surge
# cosmic rain Maybe use events?

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

cosmic rain
#

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.

inner mist
#

Why does the "Public" become an error?

wide dock
#

hover over it and see the error message

inner mist
#

I forgot an ;

#

this is my second time using C#

wide dock
#

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)

tawny elkBOT
inner mist
idle flax
#

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!

knotty sun
#

you do kow that C# has an object type, yes?

marble mauve
marble mauve
#

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

knotty sun
#

ah, the joys of JSON, solution: don't use json