#archived-code-general

1 messages · Page 148 of 1

dusky lake
#

afaik it does it already

#

as its a distance, not a delta

fervent furnace
#

Distance always >=0

#

X^2+y^2+z^2 then square root, so >=0

jade phoenix
#
public class Bullet : MonoBehaviour
{

    public float bulletSpeed;
    Rigidbody bullet;

    // Start is called before the first frame update
    void Start()
    {
        bullet = GetComponent<Rigidbody>();
        bullet.velocity = Movement.character.transform.forward * bulletSpeed;
    }

    // Update is called once per frame
    void Update()
    {
        if (bullet != null && Vector3.Distance(bullet.transform.position, Movement.character.transform.position) >= 20)
        {
            Destroy(bullet);
        }
    }
}``` whats the correct way to delete this bullet?
#

can't use this because i think that kills the prefab

fervent furnace
#

Destroy this means you destroy this script attached on the bullet

jade phoenix
#

i tried doing rigidbody and gameobject

lean sail
jade phoenix
#
        if (bullet != null && Vector3.Distance(bullet.transform.position, Movement.character.transform.position) >= 20)
        {
            Destroy(GetComponent<GameObject>());
        }```the bullets dont destroy when I do this
fervent furnace
#

Destroy (gameobject)…

lean sail
#

I'm surprised that even compiled

quartz folio
#

That is not a persistent listener (ah, sorry, discord was scrolled up)

jade phoenix
#

oh didnt know gameObject was a supplied param

#

thought you had to grab it from somewhere

fervent furnace
#

No

#

It is a property of super class monobehaviour

jade phoenix
#

when the main bullet dies im not able to shoot any more

#

thats probably expected but where do i put the main bullet then if its not supposed to be shot

lean sail
#

It's likely u are overwriting the prefab reference then

#

Because this shouldnt be an issue

jade phoenix
#
    void Update()
    {
        if (canFire && Input.GetMouseButtonDown(0))
        {
            canFire = false;
            StartCoroutine(Cooldown());
            Instantiate(bullet, this.transform.position + this.transform.forward * spawnDistance, this.transform.rotation);
        }
    }``` this is where i make the clones
night harness
#

Bit of a silly question, If I have a ScriptableObject and say I have two references of one in a List or something, are those two seperate instances of that scriptableobject or is it two references to the 1 thing

prime sinew
#

Unless you do something like... new ScriptableObject?

#

Should be easy to test

jade phoenix
#

i still havent found out how to correctly destroy the bullet?

jade phoenix
prime sinew
#

The one you instantiated?

jade phoenix
#

yup

prime sinew
#

Like the copy?

#

Instantiate returns you the copy you instantiated

jade phoenix
#

ik

prime sinew
#

Okay so destroy that

jade phoenix
#

i can destroy them but then i get errors in console one i try copying more

#

i think its cause i destroy the original one

prime sinew
#

Show code

#

Where you destroy

jade phoenix
#
public class Bullet : MonoBehaviour
{

    public float bulletSpeed;
    Rigidbody bullet;

    // Start is called before the first frame update
    void Start()
    {
        bullet = GetComponent<Rigidbody>();
        bullet.velocity = Movement.character.transform.forward * bulletSpeed;
    }

    // Update is called once per frame
    void Update()
    {
        if (bullet != null && Vector3.Distance(bullet.transform.position, Movement.character.transform.position) >= 20)
        {
            DestroyBullet();
        }
    }

    void DestroyBullet()
    {
        Destroy(gameObject);
    }
}```
#

dont look at the DestroyBullet function, i was leaning on chatgpt to help

prime sinew
#

Ew

jade phoenix
#

lol

prime sinew
#

Anyway obviously yes. Your original is being destroyed because it's also a Bullet

#

Wait

#

How are you assigning the original

#

Is it in the scene and you dragged it in?

jade phoenix
#
public class FireBullet : MonoBehaviour
{

    public GameObject bullet;
    public int spawnDistance;
    public float fireCooldown = 0.5f;

    bool canFire = true;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (canFire && Input.GetMouseButtonDown(0))
        {
            canFire = false;
            StartCoroutine(Cooldown());
            GameObject clone = Instantiate(bullet, this.transform.position + this.transform.forward * spawnDistance, this.transform.rotation);
        }
    }

    IEnumerator Cooldown()
    {
        yield return new WaitForSeconds(fireCooldown);
        canFire = true;
    }
}```
prime sinew
#

Where is your original bullet

jade phoenix
#

its public GameObject bullet; up there

prime sinew
#

And what are you dragging in

jade phoenix
#

a sphere

prime sinew
#

Show me in your editor, what did you drag in

jade phoenix
prime sinew
#

That sphere in the scene?

jade phoenix
#

yup

prime sinew
#

You should make it a prefab, and drag the prefab in instead

jade phoenix
#

how i do that

prime sinew
#

Then it won't run Update since it's not in the scene, and it won't destroy itself

tribal sedge
#

drag sphere into editor project file*
When it becomes blue then it's a prefab, drag the prefabs onto your serializedfield

prime sinew
#

By learning some basic unity
!learn

tawny elkBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

prime sinew
#

Prefabs are essential

jade phoenix
#

i know c#, just not unity ui ¯_(ツ)_/¯

prime sinew
#

Okay, you can learn. I don't have time to handhold right now. You're asking in code general, I assume basic knowledge

#

Bye

jade phoenix
#

wowza

prime sinew
#

Just look up how to make a prefab

jade phoenix
#

oh alright

tribal sedge
#

Make sure to drag the prefabs from project file and not from scene.

jade phoenix
#

can i delete the sphere from the scene now?

tribal sedge
#

Yes, you can.

jade phoenix
#

oh perfect

#

it works now

#

tysm

tribal sedge
#

Noice, Instantiated object usually from prefabs, so it'll not referencing to any other active gameobject.

tribal sedge
# jade phoenix ```c public class FireBullet : MonoBehaviour { public GameObject bullet; ...

On another tips, you can use SerializeField tag to improve class encapsulation, while you can access it on the inspector,

public class FireBullet : MonoBehaviour
{
    [SerializeField]
    private GameObject bullet;
    [SerializeField]
    private int spawnDistance;
    [SerializeField]
    private float fireCooldown = 0.5f;

    bool canFire = true;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (canFire && Input.GetMouseButtonDown(0))
        {
            canFire = false;
            StartCoroutine(Cooldown());
            GameObject clone = Instantiate(bullet, this.transform.position + this.transform.forward * spawnDistance, this.transform.rotation);
        }
    }

    IEnumerator Cooldown()
    {
        yield return new WaitForSeconds(fireCooldown);
        canFire = true;
    }
}
jade phoenix
#

alright so i sorta wanna do the same thing with a text ui element, where it pops up on the screen for a few seconds and then fades away and destroys itself

#

do i need to prefab canvas or just text

tribal sedge
jade phoenix
#

actually i could probably just keep it alive at 0 opacity

#

would that cause performance issues?

tribal sedge
#

And just another tips, destroying an object is actually expensive.

#

Like your bullet, you should re-use the bullet instead of destroy it, hide the bullet somewhere else, use it when shoot, in some range hide it again.

jade phoenix
#

is that like a garbage collector thing or?

tribal sedge
#

We called it as pooling, it's a design pattern try to avoid instantiation cost.

#

So usually we instantiate in scene load how much bullet we wanted to use, and just recycle it.

#

Because instantiation is expensive.

jade phoenix
#

hm alright ill just set the opacity to 0 and keep it on screen then

#
   Text text;

    void Start()
    {
        text = GetComponent<Text>();
        text.alignment = TextAnchor.LowerCenter;
        text.rectTransform.position = new Vector3(Screen.width / 2f, Screen.height / 2f, 0f);
    }``` is this the correct way to center a text element on the screen?
hybrid harness
#

may I have help with this?

#

theres a bit more information above the replied message

#

.

tribal sedge
tribal sedge
jade phoenix
#

this is center middle?

swift falcon
#

how make a input buffer?

tribal sedge
# jade phoenix

if you have basic in css/winform you know that playing with canvas is similar to playing with panel, create a panel that stretch's full screen and put your text inside and center it,

tribal sedge
swift falcon
# tribal sedge Can you elaborate more?

I want an input to be saved for a few seconds and then deleted, so that if, for example, I press up 3 seconds before touching the ground, when it touches the ground the action is executed

tribal sedge
tribal sedge
# swift falcon if be saved a Keycode

Then maybe you can just make an if statement and set bool isKeyUpPressed value of that key pressed when you press up 3 seconds before touching the ground.

#

If you need exact 3 seconds, then you can count the seconds if they keypressdown pressed in that 3 seconds frame then set bool to true.

swift falcon
#

ooo

#

I'll try

#

I'll show you the results later

#

thank you

#

yeah this really work

tribal sedge
#

Maybe you can check if the file path valid?

#

If not valid, there's two ways to think about is, resources folder OR check if not exist then create new json file on disk.

exotic aspen
#

Hey folks. I'm trying to improve the algorithms used in my game to better position melee units as they engage in battle. It is an RTS with a top-down view, and at the moment each unit periodically does a circle collider cast to locate enemies, and then enters an engagement state machine which iterates them next to the enemy to fight. But this has two problems. The first is the enemy is often moving too, and units only process their state machine every 250ms to save on resources, which can lead to them intersecting or crossing paths which gets messy. The second issue is units often end up overlapping where they stop moving and begin slugging it out. I've been hesitant to make use of colliders and collider callbacks due to the physics overhead. In any case, I'm not expecting a real "here's how to fix this" but more of a - do any resouces exist that deep-dive into game design theory that might help give me insight into possible methods for improving this?

mellow night
#

@exotic aspen i can think of something that might help... if your problem is the constant 250ms delay between "AI ticks" then make that delay variable, based on distance to the closest object of interest.

exotic aspen
#

@mellow night True, variable think rates are an option to help align things better. I'm just wondering if there should be a larger framework for positioning things. For example I'm toying with the idea of a manager class that assigns positions for all units engaging in combat and ticks at a fast enough rate to keep track of stuff.

#

Two or more enemies enter combat, they register where they will be stopping to whack each other at. Then as more join the fight they register their positions. This prevents many of the above issues. The challenge of course is maintainance and cleanup, and making it look organic.

mellow night
#

well it depends how you guys move exactly bu i might have an idea for that too!

exotic aspen
#

At the moment I'm using the A* Pathfinding Pro Asset which helps with movement. Every unit has a destination they are moving to, and a state machine to manage that and what happens when they arrive at their destination.

mellow night
#

you give each unit a sort of "anti gravity" or a repulse value based on 1/distance squared. each unit has a target vector pointing towards their actual target, but that vector is affected by other nearby objects, it makes sort of flocking behaviour where units will hold formation and gently curve away from and around obstacles

exotic aspen
#

:nod: The Asset actually has crowd movement mechanics you can enable. But there's a lot of tuning required to make it so units don't permanently shake in place sort of thing. I've avoided using physics so far due to the high CPU consumption on mobile. I have colliders for raycasting, but no actual units bumping into each other at the moment. I was surprised how much just friction with the ground was slowing the engine down at 10k units, and reduced the physics accuracy a bit to compensate.

mellow night
#

heh, i have done a similar thing on this project, got rid of all rigidbodies, but now i want to do collisions bewteen convex mesh colliders, and ooh boy, thats a headache

#

my reasons weren't about performance of the physics engine though, more that is just not suitable because my game isn't strictly 2D or 3D. Rather than fixed x ,y or z everything is at a fixed distance from origin, so I was constantly having to fix and overide they standard physics, in the end I ditched it but went with sphere colliders on everything for simplicity

#

regarding unit shaking at destination though, cant you just give them a bit of tolerance? make the distance they stop moving smaller than the distance the triggers them to start moving

exotic aspen
#

:nod:

#

Well it’s more the repulse effect has trouble settling down. I’ve not experimented much with it. Just visited their discord and observed folks having trouble with various attempts at it.

#

Big picture though, I’d love to see the white boarding devs as a team can do to ideate and solve complex problems such as these.

vast wigeon
#

Does anyone know how i could make it so when i die in my 2D game my characters freeze rotation turns off so that my character become able to fall over and stuff?

mellow night
dusk apex
tiny orbit
#

I am trying to modify the IAPButton script which is offered via the In-App Purchase package in the Package Manager. I am trying to add 'using TMPro;', but the namespace is not recognized and it's giving me type or namespace could not be found. all of my other scripts using TMPro still work fine... any help?

dense estuary
dense estuary
soft shard
swift falcon
#

Try replacing all the GetAxis with GetAxisRaw

    void CameraShake() {
        if (isSprinting && Input.GetAxis("Horizontal") != 0 && Input.GetAxis("Vertical") != 0) {
            cameraShakeManager.RunCameraShake();
        }
        if (isCrouching && Input.GetAxis("Horizontal") != 0 && Input.GetAxis("Vertical") != 0) {
            cameraShakeManager.CrouchCameraShake();
        }
        if (!isCrouching && !isSprinting) {
            cameraShakeManager.WalkCameraShake();
        }
        if (!isCrouching && !isSprinting && Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0) {
            cameraShakeManager.StandCameraShake();
        }
    }
dense estuary
tiny orbit
sand raft
#

Anyone have any idea where to start looking for this issue with ScreenPointToRay? Every second frame or so the location flickers to a different one, and then back again. The mouse coordinates didn't change, and the camera is slightly moving (miniscule amounts, -22.997001 -> -22.99685 etc). Could this just be floating point errors exploding?

soft shard
tiny orbit
dense estuary
swift falcon
# dense estuary That fixed it, but now it does just stop abruptly

The abrupt stopping is because you stop calling the Shake function right away when the if statement is false /input stops

I have this issue on some of my motion logic, im still trying to find an efficient way to smooth it out once the input is no longer given / the if statement is false

So I dont really know how to fix that myself

#

ill be working on a similar thing today anyways, im gonna ping you if I find a solution

soft shard
# tiny orbit just clicking on the gameobject that has IAPButton in the scene and then clickin...

Huh, AFAIK, I dont think you can edit scripts in the Packages folder, but you can see the code, just the script itself would be "locked" from editing, if the package itself doest depend on TextMeshPro, you may either have to duplicate the script so it gets added to your Assets folder structure (and can therefore edit it in the default assembly), or create a new script that inherits from that script, and try to extend it, if you are currently able to edit the package script, id be curios where that edited file is being saved

mellow sigil
#

and it should be if (isSprinting && (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0)) anyway, otherwise it only shakes when moving diagonally

sand raft
#

Anyone have any idea where to start

gray mural
#

textIndexrepresents current TMP_Text used to type text. currLine represents current line of all these textComponents

#

sorry, I was away for several minutes

#

you can see textIndex and currLine in console

fickle sand
#

Hey so I've been working on a project in which i need a player to be able to essentially copy the rotation of other objects - my approach for this has been to take set the player's transform.up as equal to the target object's transform.up. This has been working and the player gets the correct direction, but an unintended side effect is that the other directions of the player are sometimes rotated too. In the 3 videos attached, i've got a very basic version of the system which showcase the error, which i'm currently using while i try to figure out a way to make rotation behave as intended. The green line is the up direction. When the system works as intended, the up vector rotates to be equal to the target object while moving the other directions as little as possible, which the first video demonstrates. The issue is, sometimes transform.up will add unnecessary rotation, which can mess up player aiming.

Code is here, but it really is just lerping from one direction to the other.:

public class CloneDir : MonoBehaviour
{
    public GameObject obj;
    float slerpT;

    Vector3 startUp;
    Vector3 endUp;
    // Start is called before the first frame update
    void Start()
    {
        startUp = transform.up;
        endUp = obj.transform.up;

        Debug.Log(startUp);
        Debug.Log(endUp);

        slerpT = -0.5f;
    }

    // Update is called once per frame
    void Update()
    {
        transform.up = Vector3.Slerp(startUp, endUp, slerpT);
        slerpT += Time.deltaTime;
        if (1f < slerpT && slerpT < 1.002f)
        {
            Debug.Log(transform.up);
        }
    }
}```

Does anyone have any ideas for how i can make this work better? I'm rather stumped here.
frosty lark
#

whats the goal

fickle sand
#

So the overarching system I'm trying to implement is basically a system where the player has a gravity gun and when they shoot a wall/roof/whatever, that becomes the floor and so the player rotates to be perpendicular from that surface.

#

and that works, but in the process the camera gets messed up and can sometimes rotate by 90 degrees

frosty lark
#

I think its better to not copy other objects rotations person but to copy the up direction

fickle sand
#

yeah, that's what i'm doing

frosty lark
#

kinda get what you're tryna pull off

fickle sand
frosty lark
#

where the rotation is long and unnessecary

#

what is the rotation of the object the players following?

fickle sand
#

in that particular example, the target's rotation is 90,90,0 and the player's rotation is 0,0,90

#

i guess the fact that they're all opposite could be causing issues

#

hang on for a moment, i may have found a method that works

frosty lark
fickle sand
fickle sand
#

which works a charm

gray mural
fickle sand
#

possibly

#

oh well, works now

fickle sand
#

that may be an issue but i did try it without slerping, just directly setting transform.up = target.transform.up and it had the same issue

#

oh well

#

problem solved now

gray mural
fickle sand
#

because the feature im working on is a gravity changing gun and the easiest way i could think of to do that was to make gravity always apply downward and then just copy the up direction of whatever surface's direction i'm copying

tired dagger
#

did anyone know about Newtonsoft error?

buoyant oyster
#

I am currently using raw Rotate and Translate calls on a model and all was working fine, but I was getting some awkwardness with motion in animations, so I turned of Apply Root Motion, my understanding was that root motion basically moved the model based on animations rather than manual movement logic, so is my understanding wrong here? or should turning off root motion stop manual movements?

empty hollow
#

Can you use operators for conditional compilation? I.e: #if UNITY_ANDROID || UNITY_IOS

swift comet
#

ye

jovial moon
#

I did it and it worked, thank you!
Buuuuut I have a new issue now! The collisions no longer work... Would you have any idea how I could fix this without requiring two meshes?

public Mesh createMesh(List<Vector3> vertices, float thiccness, float offset)
{
    Mesh mesh = new Mesh();
    mesh.subMeshCount = 3;
    float topHeight = thiccness * (offset+1);
    float botHeight = thiccness * offset;
    
    //VERTICES
    Vector3[] meshVertices = new Vector3[3*2 + 4*3];
    Vector3 vecATop = vertices[idA] * topHeight;    //A Top
    Vector3 vecBTop = vertices[idB] * topHeight;    //B Top
    Vector3 vecCTop = vertices[idC] * topHeight;    //C Top
    Vector3 vecABot = vertices[idA] * botHeight;    //A Bot
    Vector3 vecBBot = vertices[idB] * botHeight;    //B Bot
    Vector3 vecCBot = vertices[idC] * botHeight;    //C Bot
    //!VERTICES
    //TRIANGLES
    int topChannel = 0;
    int sidesChannel = 1;
    int botChannel = 2;
    //TOP
    meshVertices[0] = vecATop;
    meshVertices[1] = vecBTop;
    meshVertices[2] = vecCTop;
    int[] topTriangles = new int[3]
    {
        0, 1, 2
    };
    //!TOP
    
    //SIDES
    //AB
    meshVertices[3] = vecATop;
    meshVertices[4] = vecBTop;
    meshVertices[5] = vecBBot;
    meshVertices[6] = vecABot;
    //!AB
    
    //BC
    meshVertices[ 7] = vecCTop;
    meshVertices[ 8] = vecBTop;
    meshVertices[ 9] = vecBBot;
    meshVertices[10] = vecCBot;
    //!BC
    
    //AC
    meshVertices[11] = vecATop;
    meshVertices[12] = vecCTop;
    meshVertices[13] = vecCBot;
    meshVertices[14] = vecABot;
    //!AC
    int[] sideTriangles = new int[6*3]
    {
        //AC
         5,  4,  3,
         5,  3,  6,
        //!AC
        //BC
        10,  7,  8,
        10,  8,  9,
        //!BC
        //AC
        14, 11, 12,
        14, 12, 13
        //!AC
    };
    //!SIDES
#

    
    //BOT
    meshVertices[15] = vecABot;
    meshVertices[16] = vecBBot;
    meshVertices[17] = vecCBot;
    int[] botTriangles = new int[3]
    {
        15, 17, 16
    };
    //!BOT
    //!TRIANGLES
    
    //UV
    Vector2[] uv = new Vector2[18]
    {
        //TOP
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 0),
        //!TOP
        
        //AB
        new Vector2(1   , 1),
        new Vector2(0   , 1),
        new Vector2(0   , 0),
        new Vector2(1   , 0),
        //!AB
        
        //BC
        new Vector2(1   , 0),
        new Vector2(1   , 1),
        new Vector2(1   , 0),
        new Vector2(0   , 0),
        //!BC
        
        //AC
        new Vector2(0   , 1),
        new Vector2(1   , 1),
        new Vector2(1   , 0),
        new Vector2(0   , 0),
        //!AC
        
        //BOT
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 0),
        //!BOT
    };
    //!UV
    mesh.vertices = meshVertices;
    mesh.SetTriangles(topTriangles, topChannel);
    mesh.SetTriangles(sideTriangles, sidesChannel);
    mesh.SetTriangles(botTriangles, botChannel);
    mesh.uv = uv;
    //Calculate normals (optional)
    // mesh.RecalculateNormals();
    // Return the created mesh
    return mesh;
}
jovial moon
stable osprey
#

otherwise create a 'half-cube' from blender and export it, and have it on your object as a collider 😛

violet wyvern
#

I not sure what is going on here but when I instantiate some objects at run time in Scroll View and I set their layer below some other canvases I have in the scene the instantiated objects still appear above them. Anyone know why?

jovial moon
#

Thank you Lyrcaxis! ❤️

stable osprey
#

np 🙂

stable osprey
#

The only other way to change this is to use layer/sorting order on the canvas component itself

steady moat
# gray mural

There is 2 lines per index ? What you want ?

textIndex = currLine / 2 ?

0 / 2 = 0
1 / 2 = 0
2 / 2 = 1
3 / 2 = 1
4 / 2 = 2
5 / 2 = 2
...
violet wyvern
#

Hmm I tried using the layers and sorting order but still nothing and now I tried the hierarchy index as well but the instantiated objects seem to ignore it all

#

Bing says it is a known bug but not sure

stable osprey
#

Show pics?

violet wyvern
#

The find panel is the object at the side that the images are positioned above

#

I made the layer UI Top to try and position it on the top but didn't work

#

Everything else is in the UI layer

sacred mesa
#

i check order in layer all good

stable osprey
#

For UI ppl use the Image component

#

Otherwise u run in all kinds of issues, especially with ordering 😄

violet wyvern
#

@stable osprey Oh well thats good to know thanks!

stable osprey
#

np

spark flower
#

Reset() is basicly what happens when you use the Reset option on a component?

#

does it run when you first create the component

quartz folio
pale halo
#

Hello, i have a mesh that is attached to another mesh the structure looks like this:

Character
Ring

I have a script attached to the Character, how should i access ring's render for the script??

stable osprey
burnt echo
#

Not necessarily a unity question so I hope this is ok, but does anyone have some experience with VSCode custom tasks?

I'm trying to create a simple task to execute a bash command to run a linter on the current open file and return any errors in the terminal.

I got it to "run" once, but it never seemed to complete, and when I tried to run the task again it said it was already running

unborn pollen
#

Hi guys i was wondering if anyone have any kind of troubles when a Android device change his current refresh rate.

Im getting this error:
Java_com_google_androidgamesdk_SwappyDisplayManager_nOnRefreshRateChanged

So there is anyway in unity to hook to an event that check the current refresh rate?

steady moat
#

And what is the error specifically ? Because this is not an error.

gray mural
steady moat
#

This is wrong.

#

You cannot know the amount of line from the textIndex

#

There is two possible answer.

#

Because of the floor operation.

gray mural
#

it also floors

steady moat
#

currLine will either be (int)(textIndex * 2); or (int)(textIndex * 2) + 1;

gray mural
#

(int)9.99f = 9

steady moat
gray mural
#

but I don't count middle lines

gray mural
steady moat
#

If you want to know the amount of line from the index you cannot.

gray mural
#

n, n + 1, n + 2

steady moat
#

Because there is two answer.

steady moat
wraith vector
#

for projectiles is velocity or transform.position better? just in general

#

im reading mixed things

steady moat
#

If you have 3 lines per index, there is 3 possible answer for the amount of line given an index.

steady moat
#

(int)(textIndex * 3); or (int)(textIndex * 3) + 1 or (int)(textIndex * 3) + 2

gray mural
#

it's either +1 or -1 if difference is 1 line

gray mural
#

so I have done it in this way.

#

diff is text index offset

#

value is in set =>

#

value is future textIndex

#

so textIndex + 1 if += 1

#

but that's not really maths

steady moat
#

So, the answer is currLine = (int)(textIndex * 2) + diff

gray mural
#

it won't ever be float

steady moat
wraith vector
#

man everyone has a different answer for this. annoying

steady moat
#

(And you are right, you do not need the (int))

gray mural
steady moat
gray mural
#

I have inted it myself

#

my bad

gray mural
steady moat
wraith vector
#

the reason im worried is there will likely be a lot of projectiles eventually, so i dont know if transform every update is a good idea

gray mural
steady moat
#

What you want ? Line in function of index ?

gray mural
steady moat
#

I gave you the math

gray mural
#

I am just not that good in maths

gray mural
steady moat
#

I explained to you that you cannot find the answer with just math

fathom horizon
#

hello everyone

steady moat
#

Because there is 2 answer.

fathom horizon
#

Are there any algorithms that can suggest the optimal shot in a snooker game ?

#

am working on a project which aims to make an automatic cue for a snooker game

steady moat
gray mural
wraith vector
#

thats what I figured, i just didnt know if the physics might get fussy

gray mural
#

value is setted new textIndex

#
private void SetTextIndex(int value, bool alignCaret, bool removeText = false)
steady moat
gray mural
#

actually I don't really need to I guess.

#

for now

#

though it should be set actually

#

I now just change lines when text is wrapped

#

so when TMP_Text's width exceeds maxWidth

steady moat
#

If you only have 2 lines, I guess you can use it to know if the answer is
(textIndex * 2) or (textIndex * 2) + 1

gray mural
#

otherwise (textIndex * 2) + 1

#

when typing

steady moat
#

(textIndex * 2) + (diff != 0 ? 1 : 0)

gray mural
#

(textIndex * 2) when deleting

steady moat
#

However, that will only work if you set the textIndex when you change line.

gray mural
#

currLine = (value * 2) + (diff != 0 ? 1 : 0)

steady moat
gray mural
#

you mean that method is called multiple times?

steady moat
#

Exact

gray mural
#

it will be executed fast enough

steady moat
#

If you call the method twice, diff will be always be equals to 0.

steady moat
gray mural
steady moat
#

So, yeah, if you do not call set index each time you change line and (only then), it is not gonna work.

gray mural
#

but, actually, if we use value * textLineCount

#

I think is should then be + (diff < 0 ? textLineCount - 1 : 0)

#

currLine = (value * textLineCount) + (diff < 0 ? textLineCount - 1 : 0)

#

that should work.

#

@steady moat thank you for your help!

wise arch
#

I want to make a tetris like inventory system in Unity (Like dayz, tarkov, unturned)
I am wondering what the best way is to visualise this. I would love some kind of visual representative in the editor but if I think of how I would do it in editor (basically grid layout with cells and then some kind of image on top for the division of cells) I am struggling to find a way to detect which cell object corresponds with the internal grid code
Any suggestions or help?

forest imp
#

Why might this be happening with the weapon following the characters mouse. I'm using a raycast to find a point

potent sleet
leaden ice
wise arch
potent sleet
tardy mortar
#

I'm using the new input system and I have my EventSystem configured with the "Left Click" set to the Mouse Click action in the UI map. This Mouse Click action is a button with a binding where the Trigger Behavior is set to "Press Only" but when I click something in the UI, it's fired on press and on release. How can I make it so that is fired only on press?

potent sleet
#

Custom editor script would be used if you do it with a 2D array or something @wise arch

#

then you can visualize it without being in playmode

wise arch
forest imp
wise arch
forest imp
leaden ice
potent sleet
forest imp
forest imp
leaden ice
wise arch
potent sleet
#

edited it , use new one. according to docs is better

wise arch
#

Seems weird that execute always is better than not always hha

elder granite
#

I'm trying to make a 2d chess game and I don't know how to implement En Passant

potent sleet
# wise arch Seems weird that execute always is better than not always hha

This attribute is being phased out since it does not take Prefab Mode into account. If a Prefab with a MonoBehaviour with this attribute on is edited in Prefab Mode, and Play Mode is entered, the Editor will exit Prefab Mode to prevent accidental modifications to the Prefab caused by logic intended for Play Mode only.

#

To indicate that a MonoBehaviour correctly takes Prefab Mode into account and is safe to have open in Prefab Mode while in Play Mode, the attribute ExecuteAlways can be used instead of the attribute here.

wise arch
#

Okay I see

#

So if I use this attribute I assume I make the visual parts of the grid in code?

potent sleet
#

you could probably do it with tilemap too tbh it's a 2D array-like grid as well

wise arch
#

Yeah fair haha but Imean there is a way that I would read and count the children and determine the grid from there but it would be a hassle

steep saddle
#

I'm trying to use System.Management to get some more detailed info about com port devices. System.Management is not implemented in Unity/Mono. I made a plugin to try and get around this, but I just get a NotImplementedException thrown at me.

Does anyone have any recommendations for a workaround here?

potent sleet
#

?

steep saddle
#

Yes, but I'm not confident I did it correctly

potent sleet
#

iirc System.Management is windows only

#

usually unity doesn't add those natively

potent sleet
steep saddle
#

Right. This is only a personal use thing

#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Text.RegularExpressions;


namespace ComPortInfo
{
    public class ComPortInfoClass
    {
        public struct ComPort // custom struct with our desired values
        {
            public string name;
            public string vid;
            public string pid;
            public string description;
        }

        public int doThing()
        {
            return 47;
        }

        private const string vidPattern = @"VID_([0-9A-F]{4})";
        private const string pidPattern = @"PID_([0-9A-F]{4})";
        public List<ComPort> GetSerialPorts()
        {
            
            using (var searcher = new ManagementObjectSearcher
                ("SELECT * FROM WIN32_SerialPort"))
            {
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
                return ports.Select(p =>
                {
                    ComPort c = new ComPort();
                    c.name = p.GetPropertyValue("DeviceID").ToString();
                    c.vid = p.GetPropertyValue("PNPDeviceID").ToString();
                    c.description = p.GetPropertyValue("Caption").ToString();

                    Match mVID = Regex.Match(c.vid, vidPattern, RegexOptions.IgnoreCase);
                    Match mPID = Regex.Match(c.vid, pidPattern, RegexOptions.IgnoreCase);

                    if (mVID.Success)
                        c.vid = mVID.Groups[1].Value;
                    if (mPID.Success)
                        c.pid = mPID.Groups[1].Value;

                    return c;

                }).ToList();
            }
        }
    }
}```
#

What I'm not confident about is which System.Management I should be referencing

night sparrow
#

How can i check if a certain collider will collide with anything if i move it to a specific position

potent sleet
#

to the location

night sparrow
#

That doesn't really help if i have a complex collider

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

potent sleet
night sparrow
#

Mesh collider/different colliders together under the same object

potent sleet
#

yeah but they overall make a shape together

#

how accurate does the hit need to be

night sparrow
#

I want to be precise

steep saddle
#

Edited the code block

night sparrow
#

With multiple colliders i can maybe handle it by iterating over them and checking each one.
However to a mesh collider i have no idea

potent sleet
#

you should be using it as a Class LIbrary

steep saddle
#

It compiles, Unity is happy with it, and when I had other simple functions in the ComPortInfo class, they worked. It's just the ManagementObjectSearcher where I keep getting the not implemented exception

#

NotImplementedException: The method or operation is not implemented.
System.Management.ManagementObjectSearcher.Get () (at <76ecc80888b243be801ffc133a5b2fc8>:0)
(wrapper remoting-invoke-with-check) System.Management.ManagementObjectSearcher.Get()
ComPortInfo.ComPortInfoClass.GetSerialPorts () (at <2432236533334f279a1f9bad52c6787b>:0)
PicoController.Start () (at Assets/Scripts/PicoController.cs:30)

#

From my limited understanding, Mono does not implement the managementObjectSearcher, but I don't know how to get Unity to ignore the Mono version of System.Management and only reference the one I referenced in my dll

potent sleet
#

oh this is for some type of IOT devices ?

steep saddle
#

Eh, sorta. Microcontrollers. Raspberry Pi Picos and/or Arduinos.

#

I/O for an escape room

potent sleet
#

sor

steep saddle
#

No worries. Technically I'm not even at the point of testing it with a Pico. Just trying to get the stupid dll to use the right system.management

#

Ha, yeah the last comment in that thread is from me

potent sleet
#

oh haha was wondering the date "what a coincidence lately "

tawny mountain
#

I have this script using the new input system , I have an issue I need help with , My movement is working except when I release the movement keys my character slides in the direction I was last moving in , I want it to stop when movement keys are released

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField]
    private float speed;

    [SerializeField]
    private Rigidbody2D playerRigibody;

    [SerializeField]
    private Animator playerAnimator;

    [SerializeField]
    private PlayerInput playerInput;



    private Vector3 positionChange;
    private PlayerInputActions playerInputActions;
    private Vector2 inputVector;


    private void Awake()
    {
        playerRigibody = GetComponent<Rigidbody2D>();

        playerAnimator = GetComponentInChildren<Animator>();

        playerInput = GetComponent<PlayerInput>();
        playerInputActions = new PlayerInputActions();
        playerInputActions.PlayerControls.Enable();
    }

    
    private void FixedUpdate()
    {
        inputVector = playerInputActions.PlayerControls.Movement.ReadValue<Vector2>();

        playerRigibody.AddForce(new Vector2(inputVector.x, inputVector.y) * speed, ForceMode2D.Force);

        if (playerInputActions.PlayerControls.Movement.ReadValue<Vector2>() != Vector2.zero)
        {
            playerAnimator.SetFloat("MoveX", playerInputActions.PlayerControls.Movement.ReadValue<Vector2>().x);
            playerAnimator.SetFloat("MoveY", playerInputActions.PlayerControls.Movement.ReadValue<Vector2>().y);
            playerAnimator.SetBool("IsMoving", true);
        }
        else
        {
            playerAnimator.SetBool("IsMoving", false);
        }
    }
}

heady iris
#

then you probably need more friction or to do your own friction

#

by adding force in the opposite direction of the current velocity

#

newton's second law is relevant here

leaden ice
#

or yes, stop by adding forces

#

but - you know - it's a physics sim

#

it does physics things

heady iris
#

as ME2 taught us, Sir Isaac Newton is the deadliest son-of-a-bitch in space

leaden ice
#

newton's first law baby

heady iris
#

wait it was the first law

#

dammit

#

I was thinking of the second law of thermodynamics

#

😭

tawny mountain
heady iris
#

well, that would just make your input vector be zero...

leaden ice
#

that makes... very little sense

#

That's basically saying "if input is zero, make input zero". Think about that for a sec.

heady iris
#

well, on its own, it's just "input vector is always zero"

leaden ice
#

adding forces changes the velocity. If you don't do any change... you are left with the current velocity not changing

heady iris
#

i can't quite tell if that's a typo'd conditional or just a statement on its own

pure cliff
#

if you are just wanting "hairpin" start/stop char control where as soon as you hit left, you go left, and as soon as you let go, you stop going left

#

.AddForce is meant for "coasting" style where you will ramp up and ramp down your speed, resulting in a build up to max velocity, and then a slow down to 0 on release

#

if you do want the ramp up/down still but just faster, thats primarily achieved by modifying the characters Rigidbody properties to change friction values and mass

tawny mountain
tawny mountain
leaden ice
# tawny mountain Like this

what's the point of your inputVector variable if you're going to repeat that long-ass ReadValue line 4 times 😢

tawny mountain
steady moat
# tawny mountain Like this

You do not want to update animation in FixedUpdate. In fact, you do not even need fixed update here as you use velocity.

tawny mountain
steady moat
#

Also, is your input updated in FixedUpdate ?

#

Only Update

#

.velocity set the velocity of the rigidbody which will be move in the fixed update.

#

If you were increasing the velocity, that would have been different.

#

Move the animation update into the Update();

tawny mountain
#

Haven't done opitmization yet just getting started , was using old input system , just trying to swap it over to new input system

#

Like

private void Update()
    {
        inputVector = playerInputActions.PlayerControls.Movement.ReadValue<Vector2>();

        if (inputVector.magnitude < 0.01f)
        {
            playerRigibody.velocity = Vector2.zero;
        }

        if (inputVector != Vector2.zero)
        {
            playerAnimator.SetFloat("MoveX", inputVector.x);
            playerAnimator.SetFloat("MoveY", inputVector.y);
            playerAnimator.SetBool("IsMoving", true);
        }
        else
        {
            playerAnimator.SetBool("IsMoving", false);
        }
    }


    private void FixedUpdate()
    {
        playerRigibody.velocity = new Vector2(inputVector.x, inputVector.y) * speed;
    }
tawny mountain
simple sable
#

Hey there.

So I have two objects in my scene and I'm trying to make object A move to the position of object B using DoTween. I tried doing this with DoMove and it works. The problem is that the target object (B) is moving. So when I call DoMove I give it the position of the target at that moment, but if object B moves away, my object A doesn't follow the new position of the target.

I'm not sure how to fix that. 🙂

opal scroll
#

using UnityEngine;

public class DiveController : MonoBehaviour
{
public float diveForce = 10f; // The force applied when diving
private bool isDiving = false; // Flag to track if the object is currently diving

private Rigidbody rb; // Reference to the Rigidbody component

private void Awake()
{
    // Get the Rigidbody component attached to the object
    rb = GetComponent<Rigidbody>();
}

private void Update()
{
    // Check for input to initiate a dive
    if (Input.GetKeyDown(KeyCode.G) && !isDiving)
    {
        // Apply the dive force in the upward direction
        rb.AddForce(Vector3.up * diveForce, ForceMode.Impulse);

        // Set diving flag to true
        isDiving = true;

        // Call a coroutine to reset the diving flag after a certain duration
        StartCoroutine(ResetDivingFlag());
    }
}

private IEnumerator ResetDivingFlag()
{
    // Wait for a certain duration before resetting the diving flag
    yield return new WaitForSeconds(1f);

    // Reset the diving flag
    isDiving = false;
}

}

simple egret
tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

mellow sigil
#

smells like ChatGPT

steady moat
#

A lot

simple egret
#

Oh yeah, now that I see the very obvious comments

#

player.Kill(); // Kill the player

potent sleet
#

diveForce = 10f; // The force applied when diving

#

no shit

steady moat
#

(Every line is commented)

mellow sigil
#

and apparently diving involves moving upwards in gptland

potent sleet
#

dive into the cosmos

golden flume
#

Hey guys. I would like to create a turn system
Do i use State for that ?
Case turn1
Case turn2
Etc ?

golden flume
#

Ok that was m'y first idea

gray mural
#

Do I need to stop Coroutine in OnDestroy()?

potent sleet
steady moat
potent sleet
#

don't think it matters once it's destroyed coroutine is gone

gray mural
simple egret
#

OverlapSphere returns multiple colliders at once, in an array. Your variable must be of type Collider[].
Next time post the error message that goes with the code, we're not compilers

lean crescent
#

I don't know if this belongs here, but I'm trying to disable movement when an object is held using an interaction ray. Also ignore the file name/commented out code, its reused because i didnt need it for its original purpose.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;

public class ActivateGrabRay : MonoBehaviour
{
    // public GameObject leftGrabRay;
    // public GameObject rightGrabRay;

    public XRRayInteractor rightRayGrab;
    // public XRDirectInteractor rightDirectGrab;

    public LocomotionSystem ContinuousMoveProvider;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        // leftGrabRay.SetActive(leftDirectGrab.interactablesSelected.Count == 0);
        // rightGrabRay.SetActive(rightDirectGrab.interactablesSelected.Count == 0);



        ContinuousMoveProvider.enabled = (rightRayGrab.interactablesSelected.Count == 0);

    }
}
gray mural
#

is subscribing to events usually done in OnEnable()?

dusk apex
#

Wherever necessary but yes, that would be a spot - assuming subscription is removed on disable

late lion
dusk apex
#

It would be fine if the object is to be instantiated and destroyed only but enable and disable would be a better practice unless they explicitly do not want it to occur during those steps.

gray mural
#

ok, thanks

fierce orchid
#

Hi, I was wanting a joint to rotate freely (using a CharacterJoint at the moment), for instance the rigidbody the joint is connected to is constantly spinning, I want the joint to just act as a joint and not break or have a limit on how much the gameobject can twist etc before it spazzes out.
Thanks in advance

gray mural
#

Why is Delete key not included in Keyboard.current.onTextInput?

jovial moon
languid hound
#

Just curious with most Unity functions if you hover over them it gives a brief description. How could one do this?

#

Oh wait

pure cliff
languid hound
#

Hell yeah cheers!

pure cliff
#

I think also works in VS Code too :3

languid hound
#

I'll give it a shot now

#

Perfection

#

Thanks lol

weak crag
#

Hello guys!
I need some information. I'm starting the test phases to publish a game on Google Play.
I am able to Run and Build using my device (Samsung Note 10)
But I can't download the test version from Play Store. It says that my device is not compatible.
I already checked the Android version and it is supported. Any clues?

simple egret
#

What if the overlap detects two objects, but the player comes second in that array?

leaden ice
#

the layermask could be wrongly configured
the player could be missing colliders
the player layer could be wrong
the player could not be in the area

simple egret
#

You need to loop through the array with for or foreach, to scan all elements of that array.

ashen bough
simple egret
#

Then you need so debug things, is this code getting executed at all? How much elements are in the array? If there's some, what's the object names these colliders are attached to?

gritty gust
#

Is there a way to cast UnsafeList to NativeList, or do a memcpy or something

ashen bough
simple egret
#

Okay, just for testing remove the layer mask and try again

gritty gust
#

CopyFrom was the first thing I checked

#

Guess I need to update my packages (it only showed T[] and NativeArray<T> as options)

#

cheers

leaden ice
ashen bough
simple egret
gritty gust
#

Ah guess I'm not on a high enough Unity version for 2.X. Not sure I really want to update to 2022 just yet, maybe I can backport the change. Or bite the bullet and upgrade. Hmm

simple egret
#

You probably didn't configure it correctly if you used bit ops 1 << layer, or used the layer directly (a layer is not a mask)

ashen bough
#

Yes, that's exactly how I do it.

leaden ice
#

So you're saying the layer was not actually set properly on the object that had the collider

gritty gust
#

Incidentally, doing NativeList.GetUnsafeList()->CopyFrom works, and is what the new NativeList CopyFrom overload does internally. So that makes things easy

molten charm
#

anyone have any ideas on this?

Warning    CS8032    An instance of analyzer Unity.MonoScriptGenerator.MonoScriptInfoGenerator cannot be created from C:\Program Files\Unity\Hub\Editor\2022.3.4f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll: Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file 
specified..    Assembly-CSharp    C:\Program Files\Unity\Hub\Editor\2022.3.4f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll```
#

it's only a warning but looks severe

#

and probably related, a new class I've put in for enemy movement is acting strange

#

runitme is not making sense

last raven
#

can someone help me with this code, I'm trying to make component to make clickable links in TMP, it works perfectly, except on one of the links it for some reason highlights the very first character in TMP (not even close to the link):

[RequireComponent(typeof(TextMeshProUGUI))]
public class TextMeshLinks : MonoBehaviour, IPointerClickHandler
{

    [System.Serializable]
    public class LinkClickEvent : UnityEvent<string>
    {
    }

    private int link;

    private TextMeshProUGUI textMesh;

    [SerializeField]
    private Color32 highlightColor = new Color32(0xC8, 0x27, 0xB4, 0xFF);
    [SerializeField]
    private Color32 linkColor = new Color32(0x4E, 0xDB, 0xFF, 0xFF);

    [SerializeField]
    private LinkClickEvent linkClicked;

    private void Awake()
    {
        textMesh = gameObject.GetComponent<TextMeshProUGUI>();
        textMesh.ForceMeshUpdate();
    }

    private void Start()
    {
        if (linkClicked == null)
            linkClicked = new LinkClickEvent();
    }

    private void OnEnable()
    {
        link = -1;
    }

    private void LateUpdate()
    {
        if (textMesh.isActiveAndEnabled)
        {
            int curLink = TMP_TextUtilities.FindIntersectingLink(textMesh, mousePosition, Camera.main);
            if (curLink == link)
                return;

            if (link >= 0)
                LinkHighlight(textMesh.textInfo.linkInfo[link], false);

            link = curLink;

            if (link >= 0)
                LinkHighlight(textMesh.textInfo.linkInfo[link], true);

            textMesh.UpdateVertexData(TMP_VertexDataUpdateFlags.All);
        } else {
            link = -1;
        }
    }

    private void LinkHighlight(TMP_LinkInfo linkInfo, bool hover)
    {
        var textMesh = linkInfo.textComponent;
        int s = linkInfo.linkTextfirstCharacterIndex;
        int e = linkInfo.linkTextLength + s;

        DebugConsole.log($"link position: {s} {e}", this);

        var color = linkColor;
        if (hover)
            color = highlightColor;

        for (int i = s; i < e; i++)
        {
            // Get the index of the material / sub text object used by this character.
            int meshIndex = textMesh.textInfo.characterInfo[i].materialReferenceIndex;

            int vertexIndex = textMesh.textInfo.characterInfo[i].vertexIndex;

            // Get a reference to the vertex color
            var vertexColors = textMesh.textInfo.meshInfo[meshIndex].colors32;

            vertexColors[vertexIndex + 0] = color;
            vertexColors[vertexIndex + 1] = color;
            vertexColors[vertexIndex + 2] = color;
            vertexColors[vertexIndex + 3] = color;
        }
    }

    void IPointerClickHandler.OnPointerClick(PointerEventData eventData)
    {
        if (eventData.button != PointerEventData.InputButton.Left)
            return;

        int link = TMP_TextUtilities.FindIntersectingLink(textMesh, eventData.pressPosition, Camera.main);

        if (link < 0)
            return;

        var linkInfo = textMesh.textInfo.linkInfo[link];
        var linkId = linkInfo.GetLinkID();

        linkClicked?.Invoke(linkId);
    }
}
#

the start and end character in linkinfo are correct

#

it seems like this code breaks when link text includes whitespace

dusk apex
#

How to post !code

tawny elkBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

last raven
#

I did inline code block, this is a pretty small code block? just a single small component

potent sleet
#

Large Code Blocks

simple egret
#

The fact that it takes 2.5 screen heights is probably a no, small code blocks are like 15-20 lines

last raven
#

shrugR well it's small to me, it easily fits into discord message and this doesn't say how much is "large"; is there any actually useful advice

simple egret
#

Yes, using a paste website

#

It's better in all ways because it also has line numbers, which is useful if you have a stack trace or something that points to a line

last raven
#

there is no stack trace or anything, code works perfectly, it just highlights first character in TMP when text inside <link> tags includes whitespace

pure cliff
#

Its about stuff like people can go "On line <n> you did this, but then on line <x> y ou did that, you want to add <this> to line <y>"

#

also try and take the time to cut down your code to only the parts that matter, can just stick a ... to replace the chunks that arent relevant

#

like when I see stuff like DebugConsole.log($"link position: {s} {e}", this); in your code you want help with, that makes it harder to parse and isolate out "what part of this code do I gotta be actually looking at"

last raven
#

well the part that breaks is right after it but that part is literally just copy from TMP examples (the working one because examples included the ones that didn't work at all as well)

#
        for (int i = s; i < e; i++)
        {
            // Get the index of the material / sub text object used by this character.
            int meshIndex = textMesh.textInfo.characterInfo[i].materialReferenceIndex;

            int vertexIndex = textMesh.textInfo.characterInfo[i].vertexIndex;

            // Get a reference to the vertex color
            var vertexColors = textMesh.textInfo.meshInfo[meshIndex].colors32;

            vertexColors[vertexIndex + 0] = color;
            vertexColors[vertexIndex + 1] = color;
            vertexColors[vertexIndex + 2] = color;
            vertexColors[vertexIndex + 3] = color;
        }

this is the relevant part (since s and e are correct)

#

anyway, I figured out the fix myself

#

or at least not a fix

#

but workaround

#
        for (int i = s; i < e; i++)
        {
            if (!textMesh.textInfo.characterInfo[i].isVisible) continue;
            int meshIndex = textMesh.textInfo.characterInfo[i].materialReferenceIndex;
            int vertexIndex = textMesh.textInfo.characterInfo[i].vertexIndex;
            var vertexColors = textMesh.textInfo.meshInfo[meshIndex].colors32;
            vertexColors[vertexIndex + 0] = color;
            vertexColors[vertexIndex + 1] = color;
            vertexColors[vertexIndex + 2] = color;
            vertexColors[vertexIndex + 3] = color;
        }

this is workaround

elder granite
#

How to use a public function in a static public function?

hidden parrot
elder granite
#

How do I do that?

hidden parrot
#

You can't call public functions from a static function without some instance of the class first

hidden parrot
simple egret
#

Function in a function? You can't access local functions from outside the method that declares it

#

Assuming you have something like the following

public void A()
{
    // other code...
    
    void B() { }
}

B can only be called from inside A

elder granite
#

No
I have:

     {
        isCheck = false;
        SimQueen(1, 0, x, y);
        SimQueen(0, 1, x, y);
        SimQueen(1, 1, x, y);
        SimQueen(-1, 0, x, y);
        SimQueen(0, -1, x, y);
        SimQueen(-1, -1, x, y);
        SimQueen(-1, 1, x, y);
        SimQueen(1, -1, x, y);

        return isCheck;
    }
#
     {
        NewBehaviourScript sc = controller.GetComponent<NewBehaviourScript>();

        int x = xPiece + xInc;
        int y = yPiece + yInc;

        while (sc.PositionOnBoard(x, y) && sc.GetPosition(x, y) == null)
        {
            x += xInc;
            y += yInc;
        }
        if (sc.PositionOnBoard(x, y) && sc.GetPosition(x, y).GetComponent<Chess>().player != player)
        {
            if (sc.GetPosition(x, y).name == "black_queen" || sc.GetPosition(x, y).name == "white_queen" || sc.GetPosition(x, y).name == "black_bishop" || sc.GetPosition(x, y).name == "white_bishop")
            {
                Debug.Log("Jauc");
                isCheck= true;
            }
            if ((sc.GetPosition(x, y).name == "black_pawn" || sc.GetPosition(x, y).name == "white_pawn") && x==xPiece+xInc && y==yPiece+yInc)
            {
                Debug.Log("Jauc Pijun");
                isCheck = true;
            }
        }
simple egret
#

Ah yeah, so you need a reference to an instance of whatever class this is in, to be able to call it from the static method.
Though why is the method static in the first place, is it for easy access?

elder granite
#

Yeah.

#

Atelast I think it is the easiet way to acces it from another script?

simple egret
#

It's not the right way though, what if you somehow need two of whatever script this is in the scene?
You're better off not making anything static at all, and let the script that called CheckIfPieceIsAtk() take in a reference to an instance of that script

#
[SerializeField] private TheScript _script; // drag-drop in the Inspector

void Start()
{
  _script.CheckIfPieceIsAtk(42, 69);
}
elder granite
#

Should I put that in the other script?

simple egret
#

The script that used the static method before

summer rose
#

Is unity officially support VScode ?

potent sleet
summer rose
potent sleet
buoyant crane
tawny elkBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

buoyant crane
#

read the bottom message

potent sleet
#

which is true

elder granite
summer rose
summer rose
simple egret
potent sleet
elder granite
simple egret
#

Okay, so you need whatever object that Instantiates it, to pass the script for you

#
GameObject clone = Instantiate(prefab);
clone.GetComponent<SomeScript>().Script = _script;
potent sleet
#

why not just spawn it as SomeScript and avoid the GetComponent

elder granite
simple egret
#

Well, how would you be able to reference it then? If there's no instance of it anywhere, you can't call a method on it

#

Static did you bad it seems, taking shortcuts thus not learning how to reference properly

elder granite
#

Thanks

pure cliff
#

its fine to have static methods if all the way down the chain they are "glass box" methods that dont need to access stuff outside of them that isnt also static

#

but it looks like your method there shouldnt be static and should be on the Queen or whatever instead

#

when your method name has a thing name in it, thats usually a code smell, like in your case instead of SimQueen(...) perhaps it should be Queen.Sim(...)?

glass crag
#

Hello, in order to read a json with a dictionary composed of english words and their meanings, i have this code https://hatebin.com/dwjnkhstgj that and an example of the json file: {
"word1": "meaning1",
"word2": "meaning2",
"word3": "meaning3"
}
and i get the following error: object reference not set to an instance of an object on line 37 with the foreach. anyone know how to read a json file into a class with dynamic properties?

dim whale
glass crag
#

the json was obtained from a dictionary, this is the original file i was trying to read for a game with words and their meanings

dim whale
# glass crag the json was obtained from a dictionary, this is the original file i was trying ...

I don't believe that is technically valid JSON.
Perhaps in some sense. But it looks like a Key-Value pair type of thing, which is typical for a dictionary.
Perhaps it is a dictionary object. But I don't know how one would resolve that from JSON into a Dictionary in C# 🤔

Either way, a simple fix is to simply parse all the key-value pairs from the raw text file.
It would involve writing code that knows when it is inside/outside "quotation marks", and whether the current text is a key or a value.

dim whale
glass crag
#

making it a dictionary<string,string> was one of the things i tried but to no avail unfortunately

#

would probably be easier to create something like a javascript program to convert the json into a more suitable format and use it then

glass crag
#

i believe it was the same error

dim whale
static matrix
#

Task.Delay() doesn't work in unity right?

glass crag
#

all lead to that no matter what i did

cosmic rain
static matrix
#

ill just use coroutines

#
public static IEnumerator ShakeObject(this GameObject gameObject, float HowMuch, int HowMany)
    {
        for (int i = 0; i < HowMuch; i++)
        {
            var off = Random.onUnitSphere * HowMuch;
            gameObject.transform.position += off;
            yield return new WaitForSeconds(0.5f);
            gameObject.transform.position -= off;
        }
        

    }

This look allright?

cosmic rain
static matrix
#

unity when you make a for(;;) loop:
"This little manouver is going to cost us 51 years"

static matrix
#

yeah

potent sleet
stable osprey
static matrix
#

yeah

#

ohhh

stable osprey
#

that's a bug (?)

static matrix
#

thank you

stable osprey
#

np 🙂

static matrix
#

it is

#

thanks

eager tundra
#

Hey guys, I'm trying to do some maths to figure out projectile trajectories, but my smooth brain is not helping.
I want to shoot a straight projectile so that it collides with a straight moving target. They're both moving at different but constant speeds.
This is happening on a 2d plane.

What I have:

  • projectile speed
  • projectile initial position
  • target speed
  • target position
    What I need to discover:
  • projectile direction
lean sail
# eager tundra Hey guys, I'm trying to do some maths to figure out projectile trajectories, but...

You'll probably need to calculate how long the projectile will take to reach the targets initial position, then calculate the targets predicted location within this time. Then point towards the predicted location
Although clearly the time to reach the predicted location wont be the same as the initial location, but this can be ignored if you are able to apply more/less force to make up for this

leaden ice
eager tundra
#

Yeah, smoothness has taken over here too
But I'm starting to think that it can't be done under the circumstances

lean sail
#

I dont think a general solution exists, since there are cases where your projectile will never catch the target based on speed

eager tundra
#

I actually don't have the projectile speed

leaden ice
eager tundra
#

It's based on the projectile direction, which is what I'm trying to find out

leaden ice
#

you'd end up with a system of equations with no real number solutions (only complex solutions)

leaden ice
lean sail
#

If you had the equation you could just set them equal to each other, to see where they meet

leaden ice
#

if both variables are free, there will be many possible solutions

eager tundra
#

I thought that I had the speed, but I only have the multiplier

leaden ice
#

what is "the multiplier"

eager tundra
#

It's a spaceship that fires projectiles according to this formula:
LinearVelocity + worldDirection * ProjectileSpeed

#

ProjectileSpeed is a float, the other two are vectors

leaden ice
#

that's confusing

#

I understand worldDirection * ProjectileSpeed but then what the heck is LinearVelocity

pure cliff
#

Are you fine with cases where the output is just "not possible"?

eager tundra
eager tundra
leaden ice
#

in fact, the full velocity of the projectile

eager tundra
#

No, the full velocity is dependent on the worldDirection, which is what I need to find out

leaden ice
#

yes but

#

it''s all fully defined

#

it's not an unknown

#

there's a function for it

#

that can be plugged into the math

#

(which I remain too smoothbrained for still 😉 )

lean sail
#

This is better since you have the vector and the direction its gonna move, rather than just the velocity as a number

#

Although, now im curious as to why the direction even exists, since the goal is to calculate your own

pure cliff
#

@eager tundra step one is first work out the formula for calculating the intersection point of the 2 vectors for the two traveling objects.

Then the formula for time it takes em both to get to that point t1 and t2

Then just solve for t1 = t2

eager tundra
#

A bit more context might help here, It's something like an aimbot

#

Like an unfair AI

#

I can fire in any direction, but I want to fire in a direction that it will always hit, if the velocity allows

lean sail
lean sail
eager tundra
#

No, just fire and forget

lean sail
#

Like not even the initial fire speed?

eager tundra
#

Nothing, just the direction that it'll be fired

#

It's totally fine if it doesn't hit

lean sail
#

I would probably go with what I initially said then

eager tundra
eager tundra
#

That actually looks pretty interesting, let me give it a try

lean sail
#

Well it would be pretty inaccurate depending on if the target is moving fast tbh

#

I too am being smooth brained, but I'm out so cant really look up the formula that im forgetting

#

What praetor said with systems of equations can work too

pure cliff
#

So to start you can calculate for a given specific angle, with velocity constant, if it will or won't hit

#

Then work backwards from there to "reverse engineer" the angle

leaden ice
#

you may also need to solve this piecewise (per axis)

drifting crest
#

CommandInvokationFailure: Failed to update Android SDK package list.
C:\Users\visha\AppData\Local\Android\Sdk\cmdline-tools\latest\bin\sdkmanager.bat --list

#

Can anyone help me with this error , Im tryin to build my AR app and this is happening

#

i followed steps from Youtube and stackoverflow but it's not working

cobalt gyro
#

if i do ScriptableObject ojb = new ScriptableObject(); will it create a new file?

pure onyx
#

Hello, can i set the size of the graph view manually without using the function graphView.StretchToParentSize() ? Thank you

quartz folio
night harness
#

I’m looking to check if a specific function has been added to a UnityEvent, is a string comparison using GetPersistentMethodName inside a loop of the added events the best course of action or is there a way to directly compare functions

leaden solstice
#

Why do you need to "check if a specific function has been added to a UnityEvent"?

night harness
#

Oh I'm doing some absolutely cursed stuff dw haha. I have two separate systems that can link up but also i'm trying to go heavy into observer pattern stuff so if System A needs System B that connection happens through a UnityEvent, then I want to add the relevant listeners

#

It's probably an over engineered idea but I'm a game designer who's still learning programming so I wanna make it as designer friendly as possible while trying to keep it optimized

lean sail
#

each system shouldnt really have to worry about other listeners

night harness
#

I don't understand this response, Could you please elaborate?

pure cliff
#

Im guessing your sort of angling towards a Pub/Sub model, and you want to save time by not bothering to publish stuff to your pipeline that has zero subscribers?

lean sail
#

like in the observer pattern, you can think of your code as reacting (by calling your function) when something happens (the event is invoked). Each observer shouldnt really worry about other observers, as in you might be doing something wrong if you have to decide to observe based on if someone else is

#

though its hard to really specify, since everything said so far is high level. itd be easier to help if you said what this system was actually for

night harness
pure cliff
night harness
#

The two systems are my Interaction system, and my new Inventory system

The Interaction system is a super generic prefab+script that handles a majority of the interactions in my game. Checks if the player is in range and looking at the object and then if the Player holds down the interaction key it does a timer and then finishes. All of this is changable in the inspector and I use UnityEvent's to allow for designers etc. to chuck in whatever they want to happen on an Interaction completion or failure.

The Inventory system is a way to store different types of things the Player might have using ScriptableObjects, the most relevant type of item I use is a Pickup.

I want these two systems to be as abstracted as possible but with the ability for them to link, a practical example would be the player obtaining a Keycard Pickup, Then using that to open a door via an Interaction

The other major example that prompted my initial question is that an Interaction can give the player a Pickup, for example that Keycard would use an Interaction. The players ability to do that Interaction can change depending on the type of Pickup, ie. if the player can only hold 1 Keycard then I need to lock the Interaction if the player has that Pickup. I want to do this by checking if the Interaction is trying to provide a Pickup in it's completion event, then tell that Interaction to listen to if the PickupInventory happens to change

#

I am so sorry for that worddump of explanation 😭

#

I think comparing method strings might end up being the best way to handle this without adding anything new to the Interaction inspector (which realistically is probably the right answer but im being stubborn and wanna streamline it as much as possible)

pure cliff
#

Gotcha aight so, what I would do is instead break up all your Interaction logic into 2 pieces each.

Interaction + ValidateInteraction

fierce orchid
#

Hi, I was wanting a joint to rotate freely (using a CharacterJoint at the moment), for instance the rigidbody the joint is connected to is constantly spinning, I want the joint to just act as a joint and not break or have a limit on how much the gameobject can twist etc before it spazzes out.
Thanks in advance

pure cliff
#

first you check the ValidateInteraction which returns some form of ValidationResult thing, that then informs you as to whether you even bother calling Interaction

lean sail
fierce orchid
#

Ah ok, thanks 🙂

gray mural
#

how do make it so that one field is shown in inspector just when another boolean is true?

#

custom inspector, isn't it?

somber nacelle
#

custom inspector, naughty attributes also has an attribute for that if you don't want to write the custom inspector/attribute for it yourself

gray mural
somber nacelle
leaden solstice
#

You don't have to use Attribute but it would be most generic.

gray mural
somber nacelle
#

did you install naughty attributes?

gray mural
somber nacelle
#

well obviously it won't work if you didn't install the package

gray mural
#

also, I have installed naughty attributes, but I still get error

#

also there is no NaughtyAttributes namespace

tepid juniper
#

https://pastie.io/rdxxoh.cs

Okay I need help. I want to download already compressed Images instead of doing it on the runtime. But this code me returns Debug.LogWarning($"Error while downloading resource < {url} >, error: Download result was null");

How should I approach downloading already compressed images?

steep imp
#

Do you guys have any idea, how I can implement this type of movement into my 2d game? In Tutorials it is only shown how to move forward and backward, but I wanna move also to the side like shown here because I think it gives the game more depth

#

Do you have an idea how I can manage this?

gray mural
#

implement WASD movement first

steep imp
#

How can I do that

golden flume
steep imp
#

I just followed the Brackey tutorial for 2d player movement

#

Let’s give our player some moves!

● Check out Skillshare: https://skl.sh/brackeys7

● Character Controller: https://bit.ly/2MQAkmu
● Download the Project: https://bit.ly/2KPx7pX
● Get the Assets: https://bit.ly/2KOkwjt

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

·································································...

▶ Play video
golden flume
#

if u know how to move in x axis u should be able to make the move to y it's the same thing

gray mural
#

How to stop executing script when throwing custom exception?

#
if (smthIsBad)
{
    Debug.LogException(blabla);
    StopExecutingScript();
}
#

or does script stop executing itself when exception is thrown?

buoyant crane
gray mural
#

probably

buoyant crane
gray mural
#

how does it help?

buoyant crane
# gray mural how does it help?

If you have error pause enabled, unity will pause the whole game when an exception is thrown. If you only want a specific script to stop, you’ll have to try catch it and handle the exception yourself.

gray mural
#

thank you

tepid juniper
#

https pastie io rdxxoh cs

gray mural
late mango
#

hi everyone

normal glade
#

Hello, I'm trying to update an old project that was using Unet to netcode.
The old code is using the class Unity.Networking.MessageBase but it doesn't exist in Netcode and I can't find in Google how to update this, do you have an idea to help me ? Thanks in advance

stable osprey
carmine wind
#

Not exactly code but I've made a game where you have different levels in unity but the levels are pretty similar and all use the same prefabs. is it better to have each level as it's own scene or one scene that places the level you want in the game as a prefab, so each level is it's own prefab. or is there some better way to manage these levels?

stable osprey
#

separate scene per level is last resort, so anything else is a better way 😛

tepid juniper
stable osprey
#

but thinking back on it, it might not always be the case*. I was thinking levels like Super Meat Boy for example, in which case it'd be a drag..

carmine wind
#

what are subsenses and addressables?

carmine wind
stable osprey
#

for stuff like Fable where the levels can be detailed and big, a scene per 'level' is best

normal glade
# stable osprey probably not the correct approach to just expect to change type names + variable...

I understand, is this the correct documentation to what i'm trying to do ?
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/custom-messages/
Example of code I need to update to Netcode :

 public class Hook : MessageBase
    {
        public int to;
        public int from;
    }

A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages.

stable osprey
#

I don't know :/

carmine wind
tepid juniper
ashen yoke
#

netcode has its own serializer?

carmine wind
ashen yoke
#

yeah

normal glade
# ashen yoke seems like it yes

i updated MessageBase like this but i don't know if i'm correct

    public class Hook : INetworkSerializable
    {
        public int to;
        public int from;

        public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
        {
            serializer.SerializeValue(ref to);
            serializer.SerializeValue(ref from);
        }
    }

Before :

public class Hook : MessageBase
{
    public int to;
    public int from;
}
ashen yoke
#

i guess? seems like it

lean sail
languid saddle
#

how can i do something with half of an array selected randomly

#

?

deft timber
#

hm?

ashen yoke
#

rephrase the question

languid saddle
#

ok sorry

#

i have an array of gameObjects, and i want to call a function in half of them

#

but that half has to be selected randomly

deft timber
#

so if you have array of 10 elements

#

you want to either do that function on 0-4 or 5-9 indexes?

#

or randomly as in random half elements from X index

ashen yoke
#

easiest approach is to first shuffle/randomize the collecton, and then simply take the amount you need

languid saddle
#

more or less, it whould be a random between 1-10, the thing is idk the number of elments that the array will have

deft timber
ashen yoke
#
        public static IList<T> Shuffle<T>(this IList<T> list)
        {
            int n = list.Count;
            while (n > 1)
            {
                n--;
                int k = UnityEngine.Random.Range(0, n + 1);
                T value = list[k];
                list[k] = list[n];
                list[n] = value;
            }

            return list;
        }
#

you can adapt it for an array

languid saddle
#

i will try it

ashen yoke
#

but list is preferable in your case

lean sail
deft timber
#

you can do it with void asewll

#
    public static void Shuffle<T>(this IList<T> collection)
    {
        int n = collection.Count;
        while (n > 1)
        {
            n--;
            int k = UnityEngine.Random.Range(0, n + 1);
            T value = collection[k];
            collection[k] = collection[n];
            collection[n] = value;
        }
    }
languid saddle
#

hmmm, i didnt use lists very much, but i will give them a try

ashen yoke
ashen yoke
#

while at it learn also Stack/Queue/HashSet/Dictionary

#

invest time into learning fundamental collection types

languid saddle
#

okay, thanks :)

steady moat
#

You should not cross-post.

potent sleet
sick coral
#

I want to make my text black with Outline, but because of the language I use, the words are written stuck together, the texts are in this way

ashen yoke
#

you can adjust spacing between character in TMP settings

sick coral
#

With this, Fonta will be uncoordinated

#

And again, the outline is determined between the characters

hollow shard
#

Oof. I just got tangled up reading about ScriptableSingletons (editor only unfortunately), asset bundles, and addressables and now I no longer know what to do. What is the recommended way to store global settings or configuration variables? Values that do not change during gameplay or values that might be constants that are only changed between new builds of a game. I want to get rid of magic numbers (and public const int variables at the tops of my scripts) and move all of that into "Debug Configuration" and "Asset Import Configuration" ScriptableObjects so I can stop hunting for magic strings in my code if I need to change something. My gut instinct is to stick my scriptable objects into the Resources directory and create a singleton "SettingsManager" class through which I can access the variables in my configuration. Should I not do that? People online just parrot "Singletons bad" and "Resources folder bad".

A core feature for me would be not having to assign any references in my components or editor windows, hence why I'm thinking of using a singleton.

potent sleet
#

nothing wrong with singletons

warm bloom
#

Does anyone know by any chance if yielding the same instance of WaitForSeconds is supported?

WaitForSeconds sleepTime = new WaitForSeconds(1F);
while (true) {
    // ...
    yield return sleepTime;
}
fervent furnace
#

yes

warm bloom
#

C# side seems to just store how long to wait, not sure how the native side stores the elapsed time and if each evaluation starts the counter over

#

Cool, thanks

vagrant blade
#

Actually, that is how I'm doing it (lol) for a project I'm on.

shadow ruin
#

Hi, does this server have a code review channel?

#

or an appropriate place I can submit my code for a community review?

rain minnow
vagrant blade
shadow ruin
#

boowomp

hollow shard
rain minnow
golden flume
#

Hey guys, having a if in update is that ok ?
i mean it can mess up with performance no ?
the if i want in my update is that

  if(player.HP <= 0)
    {
      state = BattleState.TURNTWO;
    } 
heady iris
#

it's fine.

#

computers are fast.

#

don't try to micro-optimize your game

golden flume
#

ok see 🙂 thx

fervent furnace
#

you are looking for branchless programming, but you may end up with a much slower code, you have to test it

heady iris
#

eh, not really branchless here

#

probably more event-driven

#

i.e. you do this check when you change the player's HP

barren void
#

does having a object rigidbody that is static will not be available to a OnCollisionEnter2D detection?

golden flume
#

Yes great idea, i'm on it, check when HP change

potent sleet
#

static has 0 to do with it

idle flax
#

Hey, I'm getting a really weird bug, where my scripts aren't able to get variables from a scriptableobject until I open said scriptableobject in the inspector (no errors). I think it might have something to do with how I load/save the scriptableobject.

I have a "bank" that stores references to my scriptable objects using string id's, so to save/load scriptableobjects I just store the string id, and use it again to find the scriptableobject using the bank.

Here's the code for loading:

for (int i = 0; i < data.restaurantData.activeMainCourseItems.Count; i++)
        {
            foreach (KeyValuePair<string, ScriptableObject> keyValuePair in DataPersistenceManager.instance.prefabManager.prefabBank.scriptableObjectBank)
            {
                if(keyValuePair.Key == data.restaurantData.activeMainCourseItems[i])
                {
                    FoodItemSO itemToAdd = (FoodItemSO)keyValuePair.Value;
                    mainCourseItems.Add(itemToAdd);
                }
            }
        }
shadow ruin
#

The input action manager's input UI doesn't position the top part correctly, is there a way to fix this?

ashen yoke
#

null ref? default values?

idle flax
#

it just returns null

ashen yoke
#

show the code for the dictionary

#

how is it serialized

idle flax
#

it shouldn't be an issue with the dictionary, as it works for other cases

#

it's able to get the scriptableobject itself, just not the variables from it for some reason

ashen yoke
#

this is not enough info

#

dump more info

idle flax
#

nvm solved it, it was an issue with naughtyattributes.

ripe ember
#

does anyone knows why cant i move contents inside my scroll view

ashen yoke
#

probably because it is being controlled by some layout group

ripe ember
#

dude im so stupid

#

xd

#

it's my horizontal layout group

golden vessel
#

Hey, I get the error "Coroutine continue failure" from this code ;

        if (currentBubbleCoroutine != null)
        {
            StopCoroutine(currentBubbleCoroutine);
            yield return null;
        }
        if (GameOptionsMenu.instance.language == Language.English)
        {
            currentBubbleCoroutine = StartCoroutine(CombatDialogue(buckAI.dialogueBuck[6]));
        }```
#

How do I stop the previous call to a coroutine before starting the next one?

ashen yoke
#

you clear the coroutine anywhere?

golden vessel
#

What do you mean by clearing?

ashen yoke
#

you start a coroutine, you store it in a variable

#

coroutine stops, you check for null, its still there

#

variable still references dead coroutine

golden vessel
#

Oh I thought it would become null as it ended

ashen yoke
#

no, it doesnt inherit Unity.Object

golden vessel
#

So the error comes from stopping a finished coroutine?

ashen yoke
#

im not sure what the error means, ive never encountered it, is there any additional info in the error?

golden vessel
#

Absolutely none

#

Which makes it hard to tackle

#

I'll try setting the coroutine back to null after stopping it

#

Thanks for the help

#

Btw, is there a way to do what I did inside the coroutine?

#

That would be handy, but I think I can only assign the coroutine as I start it

#

I guess I can wrap everything in a method

ashen yoke
#

oh

#

i think i understand what the error means

#

im not sure how its possible for unity to detect this case, but

#

is the code above the code of the same coroutine that you start/stop?

golden vessel
ashen yoke
#

whats the name of the coroutine

#

which code you posted

golden vessel
#

currentBubbleCoroutine

ashen yoke
#

thats the variable name

#

not the IEnumerator name

golden vessel
#

CombatDialogue then

ashen yoke
#

so what happens, you send a coroutine to execute, it reaches the null check, it stops

#

at this point the coroutine is removed from unity coroutine manager and MoveNext() will not be called on it

#

but you still yield a null instruction after that

#

which means you yield into nothing, which probably is what produced that error

#

try yield break and see if the error is gone

golden vessel
#

Do you mean the yield return null after the StopCoroutine in the code I posted?

ashen yoke
#

yes

golden vessel
#

Cos that was just a test, I was wondering if waiting for a frame would solve the problem

ashen yoke
#

you cant wait a frame for a coroutine that is already stopped

#

it is removed from enumeration, it wont be called again

golden vessel
#

The coroutine from the code I posted is not the coroutine I'm calling

ashen yoke
#

why did you post it

golden vessel
#

Cos I'm suspecting the error coming from the way I handle the variable

#

The Coroutine variable

#
    public void CallCoroutineCombatDialogue(string text)
    {
        if(currentBubbleCoroutine != null)
        {
            StopCoroutine(currentBubbleCoroutine);
            currentBubbleCoroutine = null;
        }
        currentBubbleCoroutine = StartCoroutine(CombatDialogue(text));
    }```
I get the behaviour I expected doing that
#

Probably needed to make the variable null again before reassigning it

#

Thanks for the help

ashen yoke
#

you mean the error is gone?

#

add yield return null; after currentBubbleCoroutine = null;

golden vessel
#

The error is gone, and the previous coroutine stopped

#

That's not a coroutine tho

ashen yoke
#

right

golden vessel
#

Cos the coroutine made a dialogue bubble fade after a certain time, so if I were to call the coroutine before the previous one finished, the dialogue would fade too early

#

Dunno how clear that is. Anyway, seems to work, I'm not gonna ponder on that :p Thanks for the help

mossy shard
#

Which is better a cooldown using Courutines or a cooldown using Invoke?

#

even tho, is like Invoke any efficiency wise better than courutines or vice-versa?

#

used for cooldown puropuses ofc

rugged goblet
#

My personal preference is neither, just a countdown in Update

vagrant blade
#

A countdown in Update means you can extend/shorten it, adjust the speed of the cooldown or straight up cancel it very easily.

potent sleet
#

eh id not to have many scripts use update at all , unless you had a global update

ashen yoke
#

how many would you have?

#

ballpark number?

potent sleet
#

I only have 1 global one any other scripts can tap into

#

Unity's recommendation

#

multiple scripts with Update methods are bad

ashen yoke
#

but how many would you say can be used given the standard 16ms frame budget?

#

like whats the threshold?

#

which tests did you run?

potent sleet
# ashen yoke which tests did you run?

idk

Minimize.code.that.runs.every.frame.
Consider whether code must run every frame . Move unnecessary logic out of Update, LateUpdate, and FixedUpdate . These event functions are convenient places to put code that must update every frame, while extracting any logic that does not need to update with that frequency . Whenever possible, only execute logic when things change .
If you do need to use Update, consider running the code every n frames . This is one way to apply time slicing, a common technique of distributing a heavy workload across multiple frames . In this example, we run the ExampleExpensiveFunction once every three frames:

ashen yoke
#

yeah i know all that

potent sleet
#

I'm just parroting unity , I did not personally test this. Just follow the goat

ashen yoke
#

i was asking a concrete thing, what is the point where you decide that the overhead of update is bigger than the overhead from maintaining your own update manager

potent sleet
#

no clue. I just rather start early on doing it if it's non-proto project tho

ashen yoke
#

i wonder if it can be tied to frame budget?

#

like if you are bottlenecked by raw update overhead i would consider porting it to custom update dispatcher

#

probably hooked into playerloop

rugged goblet
# potent sleet multiple scripts with Update methods are bad

This kind of authoritative statement isn't useful. While it's true that there's a small cost to using lots of Update calls versus one object calling lots of Updates, you'll need hundreds of objects in the scene before this adds up to really be worth addressing. Just avoiding Update period because of this sort of performance thing is premature optimization.

ashen yoke
#

will need a base class for all your game comps, or interface and boilerplate code in OnEnable/Disable

rugged goblet
ashen yoke
#

some very optimized fast intert/remove collection to keep track of them

potent sleet
#

i exagerrated the amount probably, you probably do need over (1k assuming) update scripts maybe dent some

ashen yoke
#

lock?

rugged goblet
#

Just use the library I provided if you're worried about the performance impact at all, or it can at least show how to do that sort of thing

potent sleet
#

probably one day I can be big brain and just use ECS completly 🤞

ashen yoke
rugged goblet
#

Which question?

ashen yoke
#

what is the point where you decide that the overhead of update is bigger than the overhead from maintaining your own update manager

potent sleet
#

good ?

rugged goblet
#

Best way to tell is using the profiler, and the math involved depends on the Update management system you use, since different mitigation systems can have different performance impacts when you're at that kind of micro-optimization level. For example, my system uses an Interface, and calling an Interface method is slightly slower than calling a class method

potent sleet
#

I'm just wondering back to the original question,
would it probably be less garbage to have a script just for Timer in Update or make Coroutine when needed with the timer tracked in there

#

that's what sparked this in the first place

rugged goblet
#

There's no hard and fast way to tell when; if you expect to have 100+ objects with Update in a scene, an Update management system is probably a good call, otherwise if you suspect a bottleneck profile it and address it

ashen yoke
#

alright ill run the numbers im really curious

rugged goblet
#

You can do Coroutines in a way that doesn't generate garbage, so either way can be 0 garbage

ashen yoke
#

coroutine is still slower and its not dynamic

#

the optimal way to solve this is to create a Timer class and use it classes that require some internal timer for something

#

you can extend the timer to have modifiers, scales whatever

rugged goblet
#

Somebody did the math on the cost of Update calls at some point on the Unity forums, but I can't find it

potent sleet
#

what about if you turn timer into a Job 😈

split furnace
#

hi, how do I check bool in WaitForSeconds

gray mural
heady iris
#

you don't?

#

yield returning a WaitForSeconds tell unity to wait for that many seconds

#

if you want to wait for a condition to be true, consider WaitUntil

gray mural
heady iris
#

debug mode is--

#

goooone

gray mural
#
yield return new WaitUntil(() => boolean);
stark jacinth
#

this is my AI enemy script: https://gdl.space/emuyahapiv.cpp

I'm trying to play a jump scare when the enemy reaches a certain distance away from my player. The idea of the jumpscare is that the agent stops and the jumpscare animation plays, but my player also stops (by disabling his playermovement script) and I force him to look at the enemy. The player also takes 25 damage. I want the jump scare to stop after 5 seconds and have the enemy move back away from the player after its done. With the way my code is now after 5 seconds my player is still frozen and the enemy wont move away from the player. Also, the player keeps taking 25 damage rather than just taking it once.

ashen yoke
#

so the difference is about 2x, 50k unity updates use 10ms, direct ~5.2, interface ~5.2, virtuals ~5.2 on my machine in release mode

#

so about 3ms unity update per 10k objects

#

hm i still wonder, a game with 10k updating components would probably not be something trivial

rugged goblet
#

Interesting that your test didn't show any difference between interface calls, I know there has been a minor difference in the past

ashen yoke
#

i know there is theoretical difference

#

since its sort of virtual, afaik it goes through vtable? i dont know clr that well

#
            case UpdateType.Interface:
                foreach (var item in _interface)
                    ((IUpdate)item).InterfaceUpdate();
split furnace
gray mural
ashen yoke
#

major difference compared to list iteration, but obviously that cant be used, i wonder if fast array would work here

gray mural
#

or true in your case

split furnace
#

how do you type that?

gray mural
#

on keyboard

#

if that's what you mean

rugged goblet
#

You want us to write your code for you?

gray mural
split furnace
#

can I speak

gray mural
#

I don't understand formulation though

gray mural
ashen yoke
#

yeah with fast array its down to ~2.6

split furnace
#

i meant how do you write that code so that it doesn't break in half because i my code is as stable as paper clips and gum

rugged goblet
#

Write the code, and then ask us about the issues in the code

gray mural
fierce orchid
#

When having scuff marks when dragging something or making tire drags etc, is it better to do it via the particle system or by decals?

split furnace
gray mural
ashen yoke
#

so ok assuming average game has the upper limit of about 3k updating components, then the difference between unity update and the fast one would be around 0.5ms

split furnace
#

I am new to programming and I have little cofidence in myself to not get a 1000 new errors

ashen yoke
rugged goblet
#

Every error is a learning opportunity

fierce orchid
gray mural
ashen yoke
#

no not really

split furnace
split furnace
gray mural
static matrix
#

OnBecameInvisible doesn't seem to be detecting correctly

leaden ice
#

and it won't become invisible if the scene camera is watching it

static matrix
#

oh
even if im not on the scene tab?

leaden ice
#

Possibly? not 100% sure

static matrix
#

int NearLights = gameObject.GetNearObjectsWithTag("Lights", 20, out NearestLight);
fancy line of code

knotty sun
#

pointless line of code without the extension method that sits behind it

tiny pollen
leaden ice
tiny pollen
#

charpos2 = mCharaTop.transform.position;

    charpos3 = charpos2 - charpos1;
    cam.transform.Translate(charpos3);
#

this is camera

#

mCharaTop.transform.Translate(Vector2.left * speedMultiplier * Time.deltaTime);

#

this is player

#

i tried many ways to move camera but all of them lagged

timid dune
#

quick question is it possible to get the normals of the collision while using OnTriggerEnter2D?

#

I don't really need physics so I'm not using any rigidbodies except for one

#

So is it possible to retrieve the normals from a collider2d that is returned by the ontriggerenter

leaden ice
#

you can do workarounds

#

like raycasting from the object's previous position or something

timid dune
#

I figure that's probably more intensive than just using another rigidbody right?

#

its a static rigidbody anyway