#archived-code-advanced

1 messages · Page 68 of 1

azure moss
#

But after 10 mins, how to predict exact normalized time then?

wicked shell
#

you need the animations to be all in sync?

#

be usfull to know the context

azure moss
untold moth
wicked shell
#

but that would mean they are at diffarent points as they come back on a diffarent times no?

#

I would say have a static variable they all reference when the turn back on

azure moss
#

will it update accordingly and predict future ahead?

#

Another thing

#

why it says gameobject but not component?

#
Controls the behaviour of the Animator component when a GameObject is disabled.

Set to true to keep the current state of the Animator controller.
Set to false to clear the current state of the Animator controller.
The default value is false.```
#

how animator will work even then?

placid shell
#

getting this odd error when I swear that currently I'm not ever touching the indices nor the vertices:

https://hastebin.com/share/gabetegomo.csharp (my code is 32 characters too long for discord... sorry)

I swear that my code in its current form should just create a blank mesh with all 6 indices set to 0 and all 4 vertices being the default of my Vertex struct..... As such I'm very confused on how I'm getting this error.... Am I making a mistake somewhere?

jolly token
placid shell
untold moth
# azure moss alright what about animator if i call animator.play?

Animator.Play just causes the animator to transition to the specified animation state. It is still part of it's state.
Not sure what you mean by predicting the future. I'm afraid that kind of technology does not exist yet.😅

Is for why it says GameObject, but not component, I don't know, but it's probably the same in this context.

untold moth
azure moss
untold moth
#

Theoretically

untold moth
azure moss
#

so basically its useless? Ugh... Would be tricky to do that myself.

obtuse remnant
#

What would you guys say the duties expected from a junior developer role are?
(I'm writing up a team member to recommend promotion, and need to say how he's been meeting or exceeded requirements of his current role.)

snow flint
#

hi guys, just testing a basic scene transition with networking
ive set up everything correctly i think but i get this error

NullReferenceException: Object reference not set to an instance of an object
NetworkLobbyManager.StartGame () (at Assets/Scripts/Lobby/NetworkLobbyManager.cs:297)
LobbyUI+<>c.<Awake>b__10_1 () (at Assets/Scripts/Lobby/LobbyUI.cs:32)
UnityEngine.Events.InvokableCall.Invoke () (at <4746c126b0b54f3b834845974d1a9190>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <4746c126b0b54f3b834845974d1a9190>:0)
...
    public void StartGame()
    {
        if (!IsLobbyHost()) { return; }
        
        try
        {
            Debug.Log("Starting game");
            NetworkManager.Singleton.SceneManager.LoadScene("BattleArenaScene", LoadSceneMode.Single);
        }
        catch (LobbyServiceException e)
        {
            Debug.Log(e);
        }
    }

which makes me think it cant find the scene.. but my understanding is you just give it a string it and finds it?

flint sage
#

Guessing NetworkManager sets it's singleton in Awake and your code executes before that

tired fog
#

Ah, perfect, thanks!

#

Mmm, the problem is that my native array already comes from mesh data

#

I guess set data will be it

compact ingot
obtuse remnant
compact ingot
#

maybe specify what he’s capable of and use that as a target and argument for creating a better role for him.

obtuse remnant
#

Um, OK.
But we've got a parent company and a process for recommending the promotion, which requires them to be meeting or exceeding requirements for their current role.
Nothing about the future role.
🤷 so I need to follow the process.
I do get to decide the requirements and responsibilities of the current and future role, though. Because those aren't defined (because we're growing fast)

compact ingot
#

I’d say look at common expectations of a mid level developer (mainly autonomy in problem solving and accurate problem/solution fit)

obtuse remnant
compact ingot
#

Senior if they can eloquently talk about their work, solve complex hard problems and can basically solve anything in their general space for themselves and guide others towards solutions.

obtuse remnant
compact ingot
#

It’s hard to clearly draw these boundaries

obtuse remnant
#

What's REALLY cool is I can also recommend someone for a pay increase WITHOUT a promotion.
Because your job title shouldn't be == your pay == how much we value you.

compact ingot
#

But making metrics/expectations clear helps everyone focus on the right things

#

Also consider that senior is not the end. You should also provision for more advanced roles that have multi-team impact that aren’t management

#

You want a role with lots of impact for someone who can successfully negotiate between the most gnarled conflicting requirements and convince everyone how to solve them in a simple way.

obtuse remnant
#

We'd consider that to be a technical senior

#

Seniors should have their areas where they have deeper knowledge.
A technical senior could focus on that area instead of project management or leading teams.
And those technical areas don't necessarily have to be programming. Could be working with clients, animation etc.

#

(But usually it'd be programming, since they're developers. Otherwise they'd be a senior artist or project manager or something.
But there's value to having cross-discipline people)

snow flint
tall ferry
snow flint
#

yeah its in the build list

stark acorn
#

I'm creating random Mesh at runtime and computed the bounds and give them almost accurate BoxColliders,
and now I need to be able to drag & drop & throw them, but the problem is their pivots are all starting from the corner,
so using ScreenToWorld(clickPos) will move them but there will be a annoying offset and the result will also be different based on its rotation
any ideas?
I'm thinking about giving all of them a empty offset parent, but all the Meshes will be affected by Phyx as well

somber needle
#

Hi, I'm having some problems with my GUI: I'm trying to show in the inspector only some fields based on the value of an enum. The only problem is that when I have to draw the GUI for an array of custom classes the element is drawn twice.
The code of the property drawer is this: https://pastebin.com/hTHDJQZh
And this is the code of the property that im trying to draw: https://pastebin.com/VtxtgHZ3

#

This is how it looks in the inspector

#

The problem is in the Steps list, which is a List<QuestStep>

flint sage
#

Guessing that since you iterate over all properties, you draw the list then you iterate over all list elements and draw each again

somber needle
flint sage
#

Try next visible instead

#

That might do it but not 100%

somber needle
#

Where should I use it? I have the OnGUI override, the GetPropertyHeight override and a function to check if I want to show the field

tired fog
#

Any ideas why a Scan and compact algorithm is way faster at reducing the size of a compute buffer, than doing it with an AppendComputeBuffer?

sage radish
tired fog
#

So it could make sense

regal olive
#

Dont know if this is the place to ask

#

is there a way with unity ik to make it so it always grabs a point even if it means stretching

#

for example a character always holds the railing even if he is 100m away from it

compact moat
#

like in a bad way or like pointing to it

knotty swallow
#

is someone here familliar with ANTLR?

regal olive
#

i mean if i tell it to grab something and its out of reach, i want the shoulder to stretch just so it can grab it

knotty swallow
# knotty swallow is someone here familliar with ANTLR?

After writing a grammar in g4 and putting it into my Output Folder, there is no BaseVisitor File created after compiling with ANTLR, which i need. I am running
java org.antlr.v4.Tool -o -visitor -listener -o "Output Directory" -Dlanguage=CSharp "Input File.g4"
in the command line, and only the files on the image are being created.

i already tried upgrading ANTLR, but that gave no solution.

#

ive resolved it, i dont see why there was a "-o" before "-visitor"

regal olive
#

Hello, can anyone explain please why this happens:
If I create a new 2d empty project and just put in it a square with this code:

using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    [SerializeField] private float MovementSpeed = 5;
    private Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        
    }

    void FixedUpdate()
    {
        rb.velocity = new Vector2(-MovementSpeed, rb.velocity.y);
    }
}```
The square doesn't have a smooth movement, it actually feels a bit jittery/laggy.
Can anyone explain why this happens or how can I fix this?
sly grove
#

This is also not an advanced coding topic

regal olive
#

Interpolation makes it much worse, it makes the game really laggy

sly grove
#

you're doing something wrong then

regal olive
#

Well how do I understand what I am doing wrong?

sly grove
tropic stag
#

I'm trying to run this code


    void LoopAddCopy<TComponent>(
        Dictionary<string, GameObject> sourceObjects,
        Dictionary<string, GameObject> destObjects
    ) {
        foreach((var name, var sourceGo) in sourceObjects) {
            var sourceComp = sourceGo.GetComponent<TComponent>();
            if (sourceComp == null) continue;

            var dest = destObjects[name];
            TComponent destComp = dest.GetComponent<TComponent>();
            if (name == "Hips") Debug.Log($"what is dest comp?: {destComp}");
            if (destComp == null) {
            } else {
                if (name == "Hips") Debug.Log($"not null {destComp}");
            }
            if (name == "Hips") { Debug.Log($"(hips){name} {sourceComp} -> {destComp}");
            }
            CopyComponent(sourceComp, destComp);
        }

    }

and I'm getting a log not null null
As if the destComp == null comparison fails, but when I try to log what it actually is it's logged as a null?
(I should put more effort into connecting a debugger, but I'm on osx+vscode and ran into problems, so stuck with logs for now)

upbeat path
#

so this

TComponent destComp = dest.GetComponent<TComponent>();

failed

tropic stag
#

yes, but it's logged inside if (destComp == null) { } else { so how can it be null and fail destComp == null?

upbeat path
#

yes, exactly destComp == null

#

sorry its the else

tropic stag
#

I changed it to:

            if (destComp == null) {
                Debug.Log("never logs");
            } else {
                if (name == "Hips") Debug.Log($"not null {destComp}");
            }

and never logs is never logged

upbeat path
#

try

TComponent destComp = dest.GetComponent<TComponent>();
Debug.Log($"{destComp} {destComp.GetType()}");
fresh salmon
#

Ah it's probably because of the fact that TComponent is not constrained, so comparing it with == does not check for Unity's object lifetime stuff (destroyed but not null yet) state.
You might want to constrain that type parameter where TComponent : Component

tropic stag
#

hmmm... I also tried this:

    void LoopAddCopy<TComponent>(
        Dictionary<string, GameObject> sourceObjects,
        Dictionary<string, GameObject> destObjects
    ) {
        foreach((var name, var sourceGo) in sourceObjects) {
            var sourceComp = sourceGo.GetComponent<TComponent>();
            if (sourceComp == null) continue;

            var dest = destObjects[name];
            CopyComponent(sourceComp, dest);
        }
    }

    void CopyComponent<TComponent>(TComponent src, GameObject dst) {
        Debug.Log("generic");
    }
    void CopyComponent(Rigidbody src, GameObject dstGo) {
        Debug.Log("concrete");
        Rigidbody dst = dstGo.GetComponent<Rigidbody>();
        if (dst == null) {
            dstGo.AddComponent<Rigidbody>();
        }
    }

this doesn't work either because only the generic variant gets called... :/

#

I thought the concrete implemention would be preferred

#

@fresh salmon sorry new, to csharp, where to I put this constraint on the LoopAddCopy declaration ? TComponent:Component?

fresh salmon
#

After the method arguments

void Sample<T>(string s) where T : Component
{

}
tropic stag
#

(will try to go back to the original question and see if this fixes the destComp comparison, but in the mean time is there a way to get rid of this error?
cannot convert from 'TComponent' to 'UnityEngine.Rigidbody' [Assembly-CSharp]cshar
(this comes up on CopyComponent(sourceComp, dest); if I don't provide a generic definition, and only provide concrete ones for CopyComponent (but if I do , then only the generic one gets called)

#

@fresh salmon with the constraint the destComp == null works correctly! (any thing I can google to explain why? : )

fresh salmon
tropic stag
#

hmmm... I don't think I have a destroyed component there... but I guess the explanation is still valid!

fresh salmon
#

GetComponent might not return null for a component that wasn't found, after all

#

Maybe you get a fake-null, that passes == null checks

tropic stag
#

I'm actually back to the second problem now, even if I can add the components in a loop, I can't call an overloaded method?
the whole point of this excercise I was trying to abstract away the looping and matching armature game object and have custom functions for copying components... but it just seems impossible

tropic stag
jolly token
#

Other option is just using Component class than downcast to specific classes

tropic stag
#

Ah that's a nice idea! I'll try that when I confirm I can get it working with the many ifs

#

How do you mean use a component class that downcast?

timber flame
#

Have you implemented chunk generation using job system in a voxel game?
My problem is when same chunk should be updated while the previous one is not completed yet.
I have created a dictionary with chunk index as a key and a list of chunk requests which should be updated.
Different chunks are regenerated independently but same chunks are regenerated by order sequentially.
Is it OK?

Requests, for example first chunk 1 changes, then chunk 4, then again chunk 1,..
If they run sequentially it will be completely OK but I want to utilize paralisim

jolly token
#

Of course not that pretty so I'd prefer just passing Action

tropic stag
#

Need to try this, cause judging from the other errors I've been getting I'm half expecting for the action approach to not work either. Will a copycomponent(rigidbody a, rigidbody b) work as an action of tcomponent type? Won't it just tell me it can't cast from tcomponent to rigidbody?

jolly token
sand acorn
#

Hello, I need some help on calculating my procedural mesh normals, I have no idea on how to do it

#

I have used some code chat gpt provided but it does not look correct, it looks like it is still missing something important so I always see a part of the mesh with correct normals while the other side is completly white

#

Here is an example

#

This is what I am using for calculating normals (I am using mesh data API)

    for (ushort i = 0; i < meshData.Length; i++)
        {
            meshData[i] = new VertexData
            {
                Position = vertices[i],
                Normal = CalculateNormals(i),
            };
        }
  
        SetTriangles(faceCount);
    }

    float3 CalculateNormals (int vertexIndex)
    {
        float3 vertexNormal = float3.zero;

        // Calculate the face normals and add them to the corresponding vertices
        for (int i = 0; i < triangles.Length; i += 3)
        {
            int vertIndexA = triangles[i];
            int vertIndexB = triangles[i + 1];
            int vertIndexC = triangles[i + 2];

            float3 vA = vertices[vertIndexA];
            float3 vB = vertices[vertIndexB];
            float3 vC = vertices[vertIndexC];

            float3 faceNormal = math.cross(vB - vA, vC - vB);

            if (vertIndexA == vertexIndex || vertIndexB == vertexIndex || vertIndexC == vertexIndex)
            {
                vertexNormal += faceNormal;
            }
        }

        // Normalize the vertex normal
        return math.normalize(vertexNormal);
    }
#

The reason of why I need to calculate normals by hand is because my own vertex attributes won't apply if I do so, If I happen to use mesh.recalculateNormals, the model looks as expected but just my vertex attributes would be overriden by the Unity default vertex attributes

tropic stag
# jolly token As long as you are calling it with `TComponent` as `Rigidbody` then it should wo...

Great! Thankyou, passing my overloaded method as an action worked. In combination with the TComponent : Component constraint it's finally looking like I wanted it (almost 🙂

    void LoopAddCopy<TComponent>(
        Dictionary<string, GameObject> sourceObjects,
        Dictionary<string, GameObject> destObjects,
        Action<TComponent, TComponent> operation
    ) where TComponent : Component {
        foreach((var name, var sourceGo) in sourceObjects) {
            TComponent sourceComp = sourceGo.GetComponent<TComponent>();
            if (sourceComp == null) continue;

            var dest = destObjects[name];
            TComponent dst = dest.GetComponent<TComponent>();
            if (dst == null) dest.AddComponent<TComponent>();
            dst = dest.GetComponent<TComponent>();
            operation(sourceComp, dst);
        }
    }

    void CopyComponent(Rigidbody src, Rigidbody dst) {
    }
    void CopyComponent(BoxCollider src, BoxCollider dst) {
        dst.center = src.center;
        dst.size = src.size;
    }
    void CopyComponent(SphereCollider src, SphereCollider dst) {
        dst.center = src.center;
        dst.radius = src.radius;
    }
    void CopyComponent(CapsuleCollider src, CapsuleCollider dst) {
        dst.center = src.center;
        dst.radius = src.radius;
        dst.height = src.height;
        dst.direction = src.direction;
    }

(I didn't want to explicitly copy the component configs, but just have it happen magically, I saw some Editor methods to copy component values, but this is close enough!) Thank you again!

sterile walrus
#

Maybe I just havent' spent enough time searching but could someone point me in the right direction for finding a specific object in a scene using the UnityEditor code? It's code that won't need to be in builds it's more for helping build the maps properly.

Example for how it's used:
SceneA is transitioning to SceneB

SceneA has GameObject1
SceneB has GameObject2

When GameObject3 touches GameObject1, GameObject3 moves to GameObject2's position in SceneB.
The code for this is already functional, I just want to code a way to verify that this connection exists and that the object can be found (In Editor) so that there aren't problems in builds

jolly token
plucky laurel
#

get scenes, use GetRootGameObjects()

#

use GetComponent on those

fallow plover
#

I'm currently having a weird issue that may just be super simple to solve but my brain cannot figure it out for the life of me (also please tell me if this is the wrong channel and I'll move the message to the correct channel).

I've stemmed off of the Sebastian Lague tutorial for perlin-noise based procedural landmass generation and currently have the noise being generated onto a 2D plane (think end of 4th episode, maybe a tad further).

My current noise function is as follows:

#

    public enum NormalizeMode {Local, Global};

    public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, float zoom, int octaves, float persistance, float lacunarity, Vector2 offset, NormalizeMode normalizeMode) {
        float[,] noiseMap = new float[mapWidth,mapHeight];

        System.Random prng = new System.Random (seed);
        Vector2[] octaveOffsets = new Vector2[octaves];

        float maxPossibleHeight = 0;
        float amplitude = 1;
        float frequency = 1;

        for (int i = 0; i < octaves; i++) {
            float offsetX = prng.Next (-100000, 100000) + offset.x;
            float offsetY = prng.Next (-100000, 100000) - offset.y;
            octaveOffsets [i] = new Vector2 (offsetX, offsetY);

            maxPossibleHeight += amplitude;
            amplitude *= persistance;
        }```
#
            scale = 0.0001f;
        }

        float maxLocalNoiseHeight = float.MinValue;
        float minLocalNoiseHeight = float.MaxValue;

        float halfWidth = mapWidth / 2f;
        float halfHeight = mapHeight / 2f;


        for (int y = 0; y < mapHeight; y++) {
            for (int x = 0; x < mapWidth; x++) {

                amplitude = 1;
                frequency = 1;
                float noiseHeight = 0;

                for (int i = 0; i < octaves; i++) {
                    float sampleX = (x-halfWidth + octaveOffsets[i].x) / scale * frequency;
                    float sampleY = (y-halfHeight + octaveOffsets[i].y) / scale * frequency;

                    float perlinValue = Mathf.PerlinNoise (sampleX, sampleY) * 2 - 1;
                    noiseHeight += (perlinValue * amplitude) / zoom;

                    amplitude *= persistance;
                    frequency *= lacunarity;
                }

                if (noiseHeight > maxLocalNoiseHeight) {
                    maxLocalNoiseHeight = noiseHeight;
                } else if (noiseHeight < minLocalNoiseHeight) {
                    minLocalNoiseHeight = noiseHeight;
                }
                noiseMap [x, y] = noiseHeight;
            }
        }

        for (int y = 0; y < mapHeight; y++) {
            for (int x = 0; x < mapWidth; x++) {
                if (normalizeMode == NormalizeMode.Local) {
                    noiseMap [x, y] = Mathf.InverseLerp (minLocalNoiseHeight, maxLocalNoiseHeight, noiseMap [x, y]);
                } else {
                    float normalizedHeight = (noiseMap [x, y] + 1) / (maxPossibleHeight/0.9f);
                    noiseMap [x, y] = Mathf.Clamp(normalizedHeight,0, int.MaxValue);
                }
            }
        }

        return noiseMap;
    }

}```
#

The issue I am trying to solve is having the "zoom" parameter zoom inwards towards the centre of the screen adjusting to match the zoomed out image. Trying to achieve this with an increased Noise Scale variable changes the shape of the terrain, which is something I'm trying to avoid.

The final product I'm looking for would be the ability to increase the zoom function and have the pixel ratio stay the same as it zooms (ie. stay within a 256 x 256 grid), however no matter what I have tried I can't seem to make it zoom towards the centre of the screen, It will always either do one or both of:

a) Move the whole function in a direction, leading to the zoomed area being thousands of units away

b) Change the function completely, leading to a different piece of land being displayed upon zooming

mellow sail
#

Anybody know about this error?

#

i know its about some script that require to reference some thing, but i already assigned it into the script that needs it

flint sage
#

You doing any custom editors

mellow sail
#

before i created an Editor folder but i already deleted it because i even didnt make any costum editor

#

the error shows after i create this script

flint sage
#

Sounds lke a bug in your unity version

mellow sail
#
public class LevelScoreCounter : MonoBehaviour
{
    public int targetScore = 100;
    public float increaseSpeed = 10f;
    [SerializeField] private TextMeshProUGUI textMeshPro;

    private int currentScore;
    private float currentDisplayScore;

    private void Start()
    {
        currentScore = 0;
        currentDisplayScore = 0f;
        UpdateScoreText();
    }

    private void Update()
    {
        if (currentScore < targetScore)
        {
            currentDisplayScore += increaseSpeed * Time.deltaTime;
            currentScore = Mathf.FloorToInt(currentDisplayScore);
            UpdateScoreText();
        }
    }

    private void UpdateScoreText()
    {
        textMeshPro.text = currentScore.ToString();
    }
}
mellow sail
flint sage
#

Try updating to the latest 2021.3 patch version

mellow sail
#

Ooops silly me, it seems like the result was because i open two inspectors at the same time

midnight violet
#

Maybe restart and kill the library folder might help too

#

Oh 😄

mellow sail
#

found it on stackoverflow

#

well, new knowledge i guess hahaha

mellow sail
midnight violet
#

Might work too 😄

#

But believe me, some library folders can mess up things a lot, so its a proven solution sometimes 😄

mellow sail
#

oh yeah sure, i was thingking about doing that. But need a little bit research before went onto that

midnight violet
#

Yeah thats like the bazooka of "fixing" if nothing else helps. More power to research for sure first 😄

gloomy mica
#

Is it possible Raycast2D skip frames occasionally? I'm using Physics2D.Raycast against Collider2D in Update, and my problem shows in the screenshots

#

moved the logic to FixedUpdate but not working

#

the red and green line are debug rays, when ray hit collider character should stop. I moved my character horizontally from left to right, sometimes character get into the obstacle collider one step further, which is the problem I want to fix

plucky laurel
#

rays are extended by speed factor?

gloomy mica
plucky laurel
#

not sure whats going on there, most likely its your code

gloomy mica
robust flare
#

Anybody here has experience with rect transform?

I want to do this on an Object wich has a Rect Transform Component:
transform.position = new Vector3(x,y, transform.position.z );

but x and y always end up as a completly different value

devout hare
#

RectTransforms should be moved using anchoredPosition

robust flare
#

@devout hare thx that was it

silk epoch
#

How could I "shatter" a polygon into smaller pieces of itself, keeping the original texture?

#

Like this, but dynamically, with a decent range of control over the new poly count and spacing?

sly stag
#

Easiest way is to just create two versions of the model, a whole version and broken version that has the various pieces separated out

#

Hardest way is to generate custom meshes to simulate the pieces

silk epoch
#

That makes sense - I was interested in the generate approach, but that may be overkill... Thank you!

silk epoch
#

Yeah exactly that!! Thank you! I'll see if a 3D version exists!

sly stag
#

Dynamically generated pieces will be a lot more GPU intensive, so keep that in mind if you have a setup where you will "break" a lot of objects

#

You won't get any of the benefits of GPU instancing

regal olive
#

You can avoid lag by Pre-generating a couple of those broken models before the game starts

chrome dune
#

Hello! I am encountering a weird bug: I am trying to load a texture from the disk into a sprite, the texture being a picture taken from an Iphone, but when loading it with the following code, the width and height are inverted. But on some other picture it is not ? AM I missing an option ?
byte[] pngBytes = System.IO.File.ReadAllBytes(imgPath); Texture2D tex = new Texture2D(1,1); tex.LoadImage(pngBytes); Debug.Log("WIDTH " + tex.width + " HEIGHT " + tex.height + " " + imgPath);

#

And here is the picture in question

sage radish
chrome dune
#

@sage radish Oh wow thank you so much!

frail parrot
#

I'm working on a little multiplayer game and I've got something working using Photon Fusion. The rotations on the player after the first isn't being stored correctly. Anyone here familiar with Photon Fusion and know what the problem might be?

regal lava
#

#archived-networking
There's also a photon discord server which you'd probably find more discreet help

frail parrot
#

oh great! I couldn't find it before

plain gate
#

I am wanting to move an object at 6 units per frame per 60 fps or (6 * 60). I am wanting to do this in fixed update which runs at 50fps. How can i make a function like Mathf.MoveTowards(velocity.x, top speed * 60, acceleration * 60). This function is like this because velocity is measured in velocity per second not per frame. How do i need to edit this function to have desired results? I am thinking I need to use Time.FixedDeltaTime.

devout hare
#

Just to be clear, you want the object to move 6 * 60 = 360 units per second?

plain gate
#

correct

#

at most and i want it to grow at a rate i can determine. like 3 * 60

devout hare
#

add 3 * 60 * Time.FixedDeltaTime to the velocity until it reaches 360

plain gate
devout hare
#

probably

zealous tide
#

Hey guys, does anyone know how can I simulate a muscle in real-time in unity?

plain gate
zealous tide
#

For example I want to contract the biceps in an arm, skinned meshes don't actually contract the biceps, is there a way i can achieve this feat?

dusty wigeon
sand acorn
sand acorn
balmy path
#

Hello I want to learn scripting in unity but I don’t understand anything from YouTube tutorials

#

😦

dusty wigeon
zealous tide
sly grove
#

doesn't seem like a code question

old swift
dusty wigeon
zealous tide
dusty wigeon
#

There is multiple transform that form the rigs. You move them.

#

Like an animation would do.

zealous tide
#

How would it perform a stretch and squishing animation? I want to perform it on a single muscle i.e. a single mesh. For example when your flex your hands your bicep actually moves inwards and when you relax your hand the muscle then moves outward / to normal position.

#

I want to simulate some kind of soft body mechanic over one single mesh for squishing them..

dusty wigeon
#

You would rig your mesh accordingly.

#

If you want to simulate soft body, this is not the right engine.

#

Unity is a Runtime engine.

#

Soft body simulation is usually done in other engine as it is not something that can be done fast enough to satistify runtime.

#

That being said, there is exception such as Cloth.

#

And some water system.

zealous tide
#

Can I move a bone on runtime using C# script?

dusty wigeon
#

yes

zealous tide
#

For example when the character's arm flexes i want to interpolate the location of the tail / head of a bone accordingly

dusty wigeon
#

You can

#

However, you should look into creating an animation or use Inverse Kinematic library.

zealous tide
#

I have Inverse kinematics on my body are you talking about activating such muscles using inverse kinematics too ?

#

rather than writing a script for doing the same?

hoary plinth
#

I am currently switching from BinaryFormatter to Json(newtonsoft) for my save game system. Are there any other alternatives to BinaryFormatter that can serialize and deserialize with minimal manual mapping? I'm trying to make the system as flexible as possible, being able save/load with minimal configuration as possible. I'm using JSON and already I ran into some issues where properties that are classes with a collection of values(i.e HealthStat{Hp=5,MaxHp=10}) rather than Data types like int or string. I was able to find a converter that seems to be working and now they are deserializing as expected but would be nice to know if there are better alternatives to JSON.

sage radish
lyric mirage
#

as long as it's different fileid and guid it's different gameobject and components right?

stable python
#

I have a Jagged Array for Images, but I cant see them in my Inspector to add the gameObjects to the array so the code knows where to put the pictures. How do i get the Jagged Array to show up in my Unity Inspector so i can move the Images into specific Array.

    public Image[][] mPortraits = new Image[9][];
void Awake(){
for (int i = 0; i < 9; i++)
    {    
    mPortraits[i] = new Image[10];
    }
}```
austere jewel
# stable python I have a Jagged Array for Images, but I cant see them in my Inspector to add the...

Serializing nested collections

Unity cannot directly serialize nested collections.

Instead of directly serializing a collection inside of another, create a serializable type that you can nest your collection inside.

// 🔴 Will not serialize
public List<float[]> Values;

// 🟢 Will serialize
[System.Serializable]
public class ValuesWrapper
{
    public float[] Values;
}

public List<ValuesWrapper> Values;
#

(I haven't added this to my troubleshooting site yet so it's a copy paste from the source 😉 )

#

You can't serialize jagged arrays either, so your choices are either nesting as above, or using ISerializationCallbackReceiver and serializing it manually into a flattened array

stable python
#

thank you, just trying to figure out how I am suppose to do this. I seem to be coding beyond my capabilities.

#

so i can do like

public class PortraitHolder
{
  public Image[] mPort0 = new Image[10];
 public Image[] mPort1 = new Image[10];
}
PortraitHolder portraitHolder = new PortraitHolder();
for (int i = 0; i <2; i++){
  string fieldName = mPort + i;
Image[] currentArray = portraitHolder.fieldName
  for(int j = 0; j<10;j++){
    currentArray[j] = getSpriteCode(); 
}
}```
orchid marsh
#

And just create an array of that type - the wrapper.

austere jewel
#

Literally just made this, very little testing done

#

should be able to do [SerializeField] private JaggedArray<Image> _images; and it should appear in the inspector and work as you would expect.

stable python
#

Thank you for the help, I used the Class with Arrays inside it and

this seems to be working for me.

austere jewel
#

Is that some other unrelated part of your implementation

stable python
#

I dont know what I am doing! lol :

        if(emptyMiningSlot != -1){
            if(foundObject.Task == "Idle"){

                    MiningArea[SelectNumber][emptyMiningSlot] = foundObject;
                    string fieldName = "mPort" + SelectNumber;
                    Image[] currentArray = (Image[])typeof(PortraitHolder).GetField(fieldName).GetValue(portraitHolder);
                    SetMonsterPortrait(currentArray[emptyMiningSlot], foundObject.Name);
                    foundObject.Task = "Mining";
                    foundObject.nodeLocation = emptyMiningSlot;
                    foundObject.Location = nodeName[SelectNumber];
                    emptyMiningSlot = -1;
                    CheckForIdleMonsters();
            }
        }}```
#

i would have used a video but i dont know how to do that.

austere jewel
#

I don't understand why you're not just accessing the fields on portraitHolder

#

instead of declaring the indexed arrays manually

stable python
#

I'lll take a look, but I have 9 different areas and with this code it lets me use the int SelectNumber as a way to tell which area they player is trying to add the monster to.

gloomy mica
long ivy
#

Update and FixedUpdate run at different rates, so the answer to your original question was yes if frame rate > physics rate

gloomy mica
#

that's right

marsh violet
#
    {
        itemAmounts = new int[inventory.inventory.Count];
        int iteration = 0;
        foreach (var item in inventory.inventory)
        {
            if (inventory.inventory[iteration].itemData == null)
            {
                itemAmounts[iteration] = 0;
                iteration++;
            }
            else if (inventory.inventory[iteration].itemData != null)
            {
                itemAmounts[iteration] = inventory.inventory[iteration].stackSize;
                iteration++;
            }
        }
        yield return null;
    }```
``` private IEnumerator UpdateInventoryItemAmountsToDB(PlayerInventory inventory)
    {
        yield return UpdateInventoryItemAmounts(inventory);
        try
        {

            
            DBreference.Child("users").Child(User.UserId).Child("InventoryItemAmounts").SetValueAsync(itemAmounts)
                .ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                    // Handle the error here, such as logging or displaying an error message.
                    Debug.LogError("Failed to update InventoryItemAmounts: " + task.Exception);
                    }
                    else if (task.IsCompleted)
                    {
                    // Handle the success case, if needed.
                    Debug.Log("InventoryItemAmounts updated successfully");
                    }
                });
        }
        catch (Exception e)
        {
            // Handle any general exceptions that may occur.
            Debug.LogError("An error occurred: " + e);
        }
    }```
Im trying to save data to firestore, but this is causing major memory leakage, ultimatly causing unity to crash
untold moth
viral onyx
#

I want to move a camera in 3d world space to it's UI in 2d space how do I move and rotate according to it's Ui

dusty wigeon
viral onyx
dusty wigeon
#

I do not see any 2D UI here

#

Do you mean a world space UI ?

viral onyx
dusty wigeon
#

There is no UI... ?

#

Only an icon on a wooden floor ?

#

In 3d space

viral onyx
#

icon

dusty wigeon
#

There is definitely no overlay UI there.

viral onyx
barren fern
#
    {
        if (axeReturn)
        {
            if (time < 1f)
            {
                axeThrow = true;

                rbAxe.position = QuadraticBezierCurvePoint(time, oldPos, curvePoint.position, targetAxe.position);
                rbAxe.rotation = Quaternion.Slerp(rbAxe.transform.rotation, targetAxe.rotation, 50 * Time.deltaTime);
                time += Time.deltaTime;
            }
            else
            {
                ResetAxe();
            }
        }
}

[Command]
    public void ReturnAxe() //AnimationEvent
    {
        RpcReturnAxe();
    }

    [ClientRpc]
    void RpcReturnAxe()
    {
        rbAxe.gameObject.GetComponent<AxeController>().activated = true;
        time = 0f;
        oldPos = rbAxe.position;
        rbAxe.velocity = Vector3.zero;
        axeReturn = true;
        rbAxe.useGravity = false;
        rbAxe.isKinematic = false;
    }

Mirror Multiplayer System
(Includes ax network transform.)
I couldn't sync the axe's return

zealous tide
#

Hey guys, Is there a way to properly rotate one characters bone transform to another (retargetting it?) I made a script which maps the rotation values for the bones however, the rotations seem to be off...

obtuse arch
tawny violet
thin mesa
tawny violet
dense drift
#

Hey so idk if anyone can help me but im working on a project that i have a inventory system (for a game so its not going to be attached to a specific avi) but I am trying to figure out what the code would be if I would want to push downwards or push upwards on the right joy stich and which than after a second or 2 the inventory (the one i have made) be enabled

So since my inventory is based on a interactable UI in unity im thinking that the code would be related to the UI coding and stating that if the foat value range is greater than or equal to 1 the menu will open and if not closes but idk if i have the right idea with this

if anyone has any articles or references that could help me or replying to me Id really appreciate it

dusty wigeon
dense drift
dusty wigeon
frail parrot
#

Is wave function collapse a good solution to creating randomized racetracks or no? I'm kind of on the fence about it because it could be used to only generate valid tracks, but it doesn't have to return to the same origin, considering its all random. It could very easily just go out of bounds and then it doesn't have to complete a circle

tiny pewter
#

no

plucky laurel
#

you can in theory if you find closest point to start and generate another one with hopes to hit it closer, iterate until you can carve a straight segment right through

tiny pewter
#

and probably generating a racetrack with curve is something that need infinite state which is unsolvable

plucky laurel
#

im assuming the wfc is used only as a guide for sampling

#

which can probably be done with noise and circling slopes or something like that

tiny pewter
plucky laurel
#

i was picturing something like trackmania hearing wfc

frail parrot
#

that does look interesting

#

basically my idea was, create one piece of track. considering it can only connect to other track pieces, it should connect to itself in the end

sly stag
#

The easiest way to handle it is to start with a circle, and then apply distortions to that, rather than trying to start with a line like you're drawing on paper

grave raft
#

bullet problem?

sleek marsh
distant onyx
#

Has anyone tried the new Rigidbody2D.Slide method in 2023.1? I'm a big fan of Godot's built-in solution for 2D kinematic character controllers and I'm pleased to see a similar effort from Unity

#

I'm curious about Unity's implementation here -- Godot's CharacterBody2D works well enough but the code is a nightmare mess

#

Would love to see Rigidbody2D.Slide implemented on the C# end sometime

austere jewel
#

!collab

thorn flintBOT
unkempt egret
#

I have a question regarding MonoBehaviour in Authroing scripts or just Components, is it only needed to assign variables from the inspector?

jolly token
unkempt egret
#

In quantum ECS or ENTITAS you have a single script that can take components you wrote

#

so you don't have to use monobehaviour in every component or authroring scripts of yours

jolly token
unkempt egret
#

alright thank you for your time then!

balmy quest
#

https://codeshare.io/dwPMqZ
I am trying to do PCG, having tiles generate at a random gap, with tiles generating 50 ahead of the player, and my script wont work, I think it is line 59

devout coyote
#

You need to inherit from monobehaviour in order to attach it to a game object

#

Although in runtime you can instantiate entities using EntityManager or an EntityCommandBuffer

plain temple
#

Does anyone know how i can get avatar/profile picture from steam?

tall ferry
tall ferry
plain temple
tall ferry
#

you'll have to convert the image to a texture or sprite, which is also definitely covered in tutorials

fresh salmon
#

Yeah Facepunch's version is way better, it's actually real C#. The others are just wrappers around the C++, and it feels like you're doing C++ in C#

plain temple
tall ferry
#

At least steamworks has uh some documentation. Facepunch is literally just a list of method names, it's a godsend if any method has a 1 sentence description

fresh salmon
#

Most of what you'll do is in the repo's README anyway

plain temple
#
public static Texture2D GetSteamImageAsTexture2D(int iImage) {
    Texture2D ret = null;
    uint ImageWidth;
    uint ImageHeight;
    bool bIsValid = SteamUtils.GetImageSize(iImage, out ImageWidth, out ImageHeight);

    if (bIsValid) {
        byte[] Image = new byte[ImageWidth * ImageHeight * 4];

        bIsValid = SteamUtils.GetImageRGBA(iImage, Image, (int)(ImageWidth * ImageHeight * 4));
        if (bIsValid) {
            ret = new Texture2D((int)ImageWidth, (int)ImageHeight, TextureFormat.RGBA32, false, true);
            ret.LoadRawTextureData(Image);
            ret.Apply();
        }
    }

    return ret;
}
#

would this work?

#

just found it on google but i dont know how to use it

fresh salmon
#

Call it, pass the ID of the user to get the avatar, and it returns a Texture you can apply to some image

fresh salmon
#

What?

plain temple
#

oh nvm u meant the method

fresh salmon
#

Of course, reading the code should be self-explanatory enough

#

It's not the most complicated stuff that's in this method

tall ferry
real blaze
#

hey. is it possible to change a local git commit's date and push it to origin? I want yesterday's local commit to appear as today's when pushing to origin

#

asking for a friend

tall ferry
real blaze
#

also, yeah it's not Unity specific, but I thought it's related to code-advanced topic. if not I'll gladly delete it

tall ferry
#

"Change git commit date"

#

I've only really seen friends do it for school to lie about submitting on time.. not sure why anyone would this otherwise tbh

real blaze
# tall ferry "Change git commit date"

answers are mostly manual time changing. I was sort of looking for a way that's designed specifically for this scenario: to update the timestamp to the push date
but yeah those workarounds do work fine

flint sage
#

I mean there's no functionality for this

#

Sinec tehre's no real reason to do so

#

You did the work on day x and pushing jsut syncs taht work to the server

tall ferry
#

Building something to do it automatically is probably overkill. Would probably be easier just doing it manually this one time, and then changing how you commit for later times

#

Could even save the changed version and undo the commit if it's just like a file that was changed. I maybe wouldnt do this if it was like a scene change

real blaze
fresh salmon
#

That's a good question

#

If you have a username then you somehow need to ask Steam to give you an ID from that, if that's even possible

#

The documentation surely has resources on that

plain temple
#

to grab the texture as a image i need to pass a int iImage

#

and on the steamid its a type csteamid?

#

how do i convert it to int?

#

nvm i converted it to int and it still doesnt work

tall ferry
# plain temple

It's the CSteamID that you plug into the GetAvatar...() function.
Thatll return u an image ID which u use with steam utils I believe to get the data

#

Really itll just be easier if you find a guide which uses steamworks. Converting to int is just guessing

tall ferry
plain temple
#

oh yeah thats the exact same code i have

#

shoutout to you bro

#

only problem i got is passing the image onto where the blue pen marks

plain temple
#

i cant really pass it onto there

#

so what do i do?

dense cloud
#

hello, i change the rotation of my object from script but it seems to have one frame delay between the animation trigger and the rotation change, anyone have a solution for that?

#

animation changes first, transform rotation changes after, even tho they are called at the same time

dusty wigeon
dusty wigeon
dense cloud
#

@dusty wigeon it doesnt, still doesnt matter it is an internal bug, i tried all possible combinations. Only fix was setting the sprites directly

#

best i could was 1 frame delay which caused a stutter

dusty wigeon
#

So, it is not about changing rotation isnt ?

dense cloud
#

nope. its another unity animator bug

dusty wigeon
#

...

#

Stop blaming Unity.

#

You do not even describe your issue and blamme it on the engine.

#

As far as I know, you might not even use it correctly.

dense cloud
#

the sprites do not get changed instantly when its set to, exittime 0 with any update conditions engine has

#

ive had worse when i set 15 animators trigger at the same time and they played out of sync by seconds.

#

not my first rodeo

dusty wigeon
#

If you are doing 2D sprite base animation, maybe the Animator is not suitable for your use case. I am pretty sure the Animation are threaded, thus it might be expected to have a frame delay between the trigger and the actual change. In most case, this should not be an issue or it could be mitigate by waiting for a frame before doing the actual behavior.

dense cloud
#

yeah. if i change it by scripts it works fine. but if i make the animator sprite renderer fully transparent and change it by script also, it still lags 1 frame

dusty wigeon
dense cloud
#

the animator somehow lags the script i have no idea why

dusty wigeon
#

Maybe the animator is running before the script.

#

Did you try to manipulate the Execution Order and use LateUpdate ?

dense cloud
#

if i make the animator fully transparent it lags one frame. if i remove it , it doesnt

dusty wigeon
#

So, the issue is on the SpriteRenderer not on the animator ?

#

It is kinda hard to follow what you are saying.

bleak citrus
#

i do not understand how one makes an animator transparent

dense cloud
#

by making its sprite renderer transparent

#

adding a second sprite renderer

#

and changing the second sprite renderer by script

#

if animator is enable second sprite renderer still lags

dense cloud
dusty wigeon
#

There is also the possibility to force the Animator to Update with Animator.Update.

bleak citrus
#

animation updates normally happen between Update and LateUpdate.

dusty wigeon
dense cloud
#

if i reference the spriterenderer connected to the animator at all. it will lag

#

weird af

#

i guess ill use two seperate scripts on two seperate objects

dense cloud
#

@dusty wigeon calling update helps a bit but doesnt fix it. thanks for your help tho

#

it lags less amount of frames

potent shoal
#

In unity, rotations work in a 360 full circle.. I am trying to determine when a rotation is greater than the last rotation, but this fails when the rotation resets. How can I solve this?

hoary plinth
#

I'm not even sure this is the right place to ask, but I'm wondering if it is worth it to attempt to upload and market a Toolkit I'm working on. The goal is to provide allot of generic code that can be used to speed up development. The features I have mostly working so far are Generic Repositories for storing many of a single type. I've also started work on a SaveableObjects for things that need to be saved but only one or few in the game. Also code and logic for taking all those things and serializing them into Json string with optional encryption as well as deserializing them back into their types. I'm also thinking about taking a stab at creating a custom monobehaviour that will be able to handle registering/deregistering events automatically and a static ServiceLocator for registering and Locating Unity Singletons with Maybe another custom monobehavior class specifically for singletons that will include the unity singleton pattern in their base code. --Does this seem like something worth trying to sell or is the market oversaturated with this kind of asset?

sly grove
dusty wigeon
# hoary plinth I'm not even sure this is the right place to ask, but I'm wondering if it is wor...

If you are interesting in marketing tool, from a User stand point, I suggest that you

  • Concentrate your effort in a single point. (Save or Event, but not both)
  • Make things that are actually long to make or hard to make. (Save is pretty straight forward, Event are easily done)
  • Consider extensively the interface of your tool. (The UI and the Code interface)
  • Be sure to be able to add more value to your tool then what it already exists. (Performance, Flexibility, Usability, Price, etc.)

Also, consider that as an User, I am also a developer. I can easily do most of what you want to do. (And have done it several time) It is more a question of how much time it would take to make it. Thus, if you are not ready to invest a considerable amount of time in your tool, then you should not do this.

#

That being said, as an individual, it is really useful to have your own toolkit and you should definitely do it for your own benefit.

barren frigate
#

Anyone have experience setting button OnClick function arguments via script? I'm struggling a bit with it.

#

tried this in a function that passes the int:
dropItemButton.onClick.AddListener(delegate { dropInventoryItem(invSlotId);});

#

trying to select an inventory slot, and have the slot update the int illustrated above based on index/id

#

or open to suggestions if that is a bad way to do it

dusty wigeon
# barren frigate

You cannot and should not update the int you are showing. The state of what is currently being selected should be handle else where such a class name InventoryUI.

barren frigate
dusty wigeon
#

In other words, follow a sort of MVC flow between your different composant.

#

You inventory should be agnostic of your UI.

barren frigate
#

Hmm, wondering how much backtracking I should do.. My UI is currently just reading from the playerInventory and applying it to the slot

dusty wigeon
#

There is multiple of MVC approach, this is what I prefer from experience.

dusty wigeon
#

Code is evolutive. When you add extra feature, you sometimes have to refine the structure of things that are already in place.

barren frigate
#

I may be using this model, but I was double checking to confirm 😄

#

The inventory list of game objects is on the player, inventoryManager.CS (perhaps a bad name) reads the inventory list, and the empty slots get updated in realtimew based on the live inventory adjustments

#

not sure if that is traditional (or technically MVC)

dusty wigeon
#

The controller manipulate the data from a UI perspective in a VideoGame context (Which should be the same in Web Application).

barren frigate
dusty wigeon
#

What you have describe seem to qualify as a controller, however it is poorly named.

barren frigate
#

you are likely right on that... this is my first go at open world game with a lot of aspects a large team would be handling... but I'm solo

dusty wigeon
#

I do not think you should have a InventoryManager

dusty wigeon
#

Large team is all about work division.

#

It is hard to have several person work on the same feature at the same time.

barren frigate
#

yeah, so I'm learning a lot of different things on the fly.. execution probably not perfected on anything

#

but making an effort

dusty wigeon
#

Nobody is perfect, and the essence of programmation make it even harder as it is continously evolve while you work on it.

#

One good solution, can become a terrible solution after a few iteration.

barren frigate
#

the "Use" and "Drop" button get updated based on the selected inventory item, (whether they are disabled, canDrop, etc.)

barren frigate
#

so, if the inventoryItem.cs has canDrop = true... the button enables, but I currently feed the button function an int argument... maybe just try to change the function to read a more global int?

#

from the inventoryManager.cs?

dusty wigeon
#

The decision should come from the poorly name InventoryManager.

#

I would expect to see something like UpdateView which would content a specific section attributed to the Drop and Use button.

#

You could also decide to dissociate the button and the InventoryManager, however I feel like it would add complexity for no particular reason.

#

If you do, you would need to define a class that manage the state of your button that can be extended to include the specific of the Drop and Use button.

#

One way could be to use something like a Condition which is evaluated at the Button level.

#

Inside the condition you would define a contract between the condition and the Inventory

barren frigate
#

I was going to make a script to handle button states, but didn't want to unless it was appropriate

dusty wigeon
#

Something like CanUseCondition which content an indirect reference to the InventoryManager through and interface ICanUse which define a function IsUsable.

#

This, would be complex for no real immediate benefit.

#

The avantage of such a structure is that it can be reuse in mutliple place.

#

It would be easy to make the CanDropCondition after having done the CanUseCondition.

#

Also, given you used an interface, you would even be able to reuse the condition on other context than an inventory. However, I feel this is making the things more complex than it needs to be.

barren frigate
#

Ok, looking into this

#

kind of funny, my game object is named InventoryUI

dusty wigeon
#

It is an appropriate name.

barren frigate
#

thank you by the way

spark spade
carmine sundial
hardy sentinel
# dusty wigeon

what's with the red markers there? :p The player only ever interacts with the UI

dusty wigeon
hardy sentinel
#

mainly the ones changing 'request':

dusty wigeon
hardy sentinel
#

but.. but.. 😛

dusty wigeon
#

It is not possible in fact.

#

How would you interact with something that has no interface.

hardy sentinel
#

aaahh got super confused because you labeled the controller as "Inventory UI"

dusty wigeon
#

The view are the specific element that compose the UI.

#

Toggle, Button, Panel, etc.

#

You can have higher level element

#

Such as scroll view

#

However, you always gonna have a coordinator between the view and the model.

#

The model being the game (Player, Inventory, Environment, etc.).

#

View element are agnostic to the model

hardy sentinel
#

yeah technically in Unity the View is always the prefab (or multiple parts of it), but usually gets grouped together with the underlying code (which would be the Controller)

dusty wigeon
#

While the controller is the bridge between the view and the model.

hardy sentinel
#

god objects ftw

dusty wigeon
hardy sentinel
#

well, had UI in mind, where a bunch of Buttons consist a prefab and that technically makes prefab 'be' the controller

dusty wigeon
hardy sentinel
#

but yeah nothing stops views or controllers or even models from being prefabs anyway

#

Anyway, my point is that in Unity it's a bit complicated, because of industry standards and the game engine's design itself.
What's to take from MVC/MVVM is that it's important to always separate UI from data.

snow flint
#

hi guys, can you ask multiplayer questions in here?

wondering why my toggle is acting so strange

UI
        readyToggle.onValueChanged.AddListener((value) =>
        {
            NetworkLobbyManager.Instance.SetPlayerReadyServerRpc( value);
        });

Lobby manager
    [ServerRpc(RequireOwnership = false)]
    public void SetPlayerReadyServerRpc(bool value, ServerRpcParams serverRpcParams = default)
    {
        int playerDataIndex = GetPlayerDataIndexFromClientId(serverRpcParams.Receive.SenderClientId);
        
        PlayerData playerData = _playerDataList[playerDataIndex];
        
        playerData.isLobbyReady = value;
        
        _playerDataList[playerDataIndex] = playerData;
    }

UI
    public void UpdatePlayer(Player player)
    {
        this._player = player;

        if (player.Data.ContainsKey(NetworkLobbyManager.KEY_PLAYER_NAME))
        {
            playerNameText.text = _player.Data[NetworkLobbyManager.KEY_PLAYER_NAME].Value;
        }
        else
        {
            playerNameText.text = "Unknown";
        }
        
        // debug.log player data name and ready
        Debug.Log("player data name: " + NetworkLobbyManager.Instance.GetPlayerData().playerName + " ready status " + NetworkLobbyManager.Instance.GetPlayerData().isLobbyReady);
        readyToggle.isOn = NetworkLobbyManager.Instance.GetPlayerData().isLobbyReady;
    }
sly grove
snow flint
# sly grove "acting strange" is extremely vague - but maybe because when you do `readyToggle...

yeah sorry, definitely should have been more detailed

interesting didn't know there was a call back

basically the toggle is false by default, the log prints false, which is fine as i poll the lobby for updates

then when i press the toggle it goes true for one update then back to false

server side though its recorded as the play being ready

so when you set isOn it calls another method?

reading the docs now, thanks

#

im using this now

        /// <summary>
        /// Set isOn without invoking onValueChanged callback.
        /// </summary>
        /// <param name="value">New Value for isOn.</param>
        public void SetIsOnWithoutNotify(bool value)
        {
            Set(value, false);
        }

but it still flicks to off the next poll but the code says its true, only only passing true

thin mesa
#

This is not an advanced topic. You can use the Instantiate method to clone an object. Back to #💻┃code-beginner if you need further help

plucky laurel
snow flint
modest lintel
devout coyote
#

It's probably you overwriting it somewhere

plain temple
#

Hello im trying to make a scoreboard where whenever a player joins the server a ui prefab instantiates so that everyone can see on the scoreboard. Right now i have a script where username and profile picture from steam goes into the scoreboard but you can only see your own username and pfp.

This is my script which i handle everything: https://pastebin.com/exaqv1Az
If you need more info please let me know

devout coyote
#

yes what is the actual problem?

plain temple
devout coyote
#

You don't seem to be having any code that handles a player joining, or a list of players that are currently in the game

#

Probably look at the documenation for the networking solution you are using to figure that one out

plain temple
#

basically see the player joining and list of players done (just ignore it)

devout coyote
devout coyote
#

Next time that is, for now just create a property and drag it in the inspector

plain temple
#

the problem is not referencing bruh

#

nvm its all g

devout coyote
#

then what is?

#

I know what your goal is, but what exact problem are you running into?

plain temple
#

basically 20 people can be in a game but in the scoreboard it only shows the local player

devout coyote
#

okay but you dont know how to display multiple entries on the scoreboard or is it something else?

plain temple
#

i have an event where a player joins and leaves

devout coyote
#

Alright so your scoreboard implementation does not support multiple entries?

plain temple
#

it does

dusk vine
#

that code only shows the part where you get the local players data

devout coyote
plain temple
#

i just need a normal multiplayer scoreboard

devout coyote
#

Thats the goal

#

but not the problem

plain temple
dusk vine
#

@plain temple where's the actual networking code?

plain temple
#

i only have an event where a player joins and leaves

dusk vine
#

not sure why your showing that script then if the problem is in the networking

devout coyote
#

Its not in the networking either, he's just discovered that his scoreboard doesnt support multiple entries

#

:)

plain temple
tall ferry
dusk vine
plain temple
#

need to set it up so when anyone joins it will instantiate that with their values

tall ferry
#

All I did was breakdown the problem into steps for you, because you really arent specifying what was actually done. This code only shows u grab the local player, so it's clear only the local player will be shown

plain temple
tall ferry
#

Reread what I wrote. I've already understood what u have, I've seen the code. You just have to extend the functionality now to use your friends CSteamID

plain temple
#

thank you ill fix it

tired wyvern
#

Thoughts on this pattern? Hooking up regular C# classes to Update() using an UpdateHook():

public class UpdateHook : Singleton<UpdateHook> {

    List<Action> callbacks = new List<Action>();

    public static void Add(Action callback) {
        instance.callbacks.Add(callback);
    }

    public static void Remove(Action callback) {
        instance.callbacks.Remove(callback);
    }

    void Update() {
        foreach (var item in callbacks) {
            item?.Invoke();
        }
    }
}
dusty wigeon
devout coyote
tired wyvern
tired wyvern
devout coyote
#

How would you instantiate a new gameobject?

dusty wigeon
devout coyote
#

And maybe it's short lived, so you destroy it aswell

#

E.g. a bullet (if not using object pooling)

tired wyvern
tired wyvern
plucky laurel
#

you lose inspector especially felt if you have oding with [ShowInInspector, ReadOnly]

dusty wigeon
plucky laurel
#

its better in almost every way to derive from mono

devout coyote
#

You'll notice you'll end up impleneting a simplified version of monobehaviour

dusty wigeon
#

From my experience, there is no situation where you want code to be updated without being indirectly connected to a MonoBehavior.

plucky laurel
#

you can have IUpdatable, ILateUpdatable and relay unity events down the chain, to some internal objects

devout coyote
#

If you are looking for a different paradigm altogether, take a look at unity DOTS

devout coyote
plucky laurel
#

well no

#

there is a reason to do that, you dont need to maintain a components lifecycle, no need to have or construct a go

#

but again you are dodging the unity pipe, you are losing a bunch of very useful perks

#

especially for debugging

dusty wigeon
#

MonoBehaviour can sometimes be overkill. By example, you would not necessary create a MonoBehaviour per state in a state machine. However, the statemachine or the owner of the statemachine should be a monobehaviour and relay any events that are necessary.

plucky laurel
#

@tired wyvern imo a middle ground is best, if you have a root gameobject that carries those, you can have an api that automates their construction sort of var myobj = Create<T>()

#

and it constructs a go, attaches it, adds mono, you get the benefits of it having its own inspector, its transform which can carry utility objects itself

tired wyvern
#

It was useful reading your convos.

  • It's clear to me that there are cases where some code has no reason to be a monobehaviour still wants access to Update(),
  • that being said, there are weird bugs that have come up because of using the UpdateHook() so maybe its not worth the hassle.
  • I don't use the inspector as much because serialization gets really annoying to deal with sometimes, so that's not an issue for me.
tired wyvern
plucky laurel
#

i advice to use it at least for [ShowInInspector, ReadOnly]

#

on pretty much everything everywhere that doesnt need unity serialization, but helps you debug

tired wyvern
#

I just use the Debug toggle in the inspector

plucky laurel
#

god thats smart

#

thanks i just gained iq by putting 2 + 2

tired wyvern
#

😄

plucky laurel
#

always knew of odin

#

always knew of debug

#

never occured (not sarcasm)

devout coyote
tired wyvern
#

An example of a weird bug from UpdateHook:

The following scene GameObjects were found:
SingletonUpdateHook```
plucky laurel
#

hardly a bug

devout coyote
#

Probably missing some clean up code somewhere

plucky laurel
#

just deinitialization order issue, which is only affecting editor

#
        public static bool IsNullOrDestroyedSilent(this object uobject)
        {
            try
            {
                return !(uobject as UnityEngine.Object);
            }
            catch
            {
                // swallow the exception
            }
            return true;
        }
#

wait im messing it up again

devout coyote
#

(he could also actually be spawning stuff from OnDestroy)

plucky laurel
#

yes i misinterpreted

#

that is probably something in the base singleton trying to init a null reference again when entering edit mode

#

which can be remedied with hooking into

#

EditorApplication.playModeStateChanged

#

catching ExitingPlayMode

tired wyvern
#

My guess is that I'm calling the static field here when I shouldn't:

public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
    
    static T _instance;
    protected static T instance {
        get {
            if (_instance != null) return _instance;
            
            _instance = FindObjectOfType<T>();
            if (_instance != null) return _instance;

            GameObject obj = new GameObject();
            _instance = obj.AddComponent<T>();
            obj.name = "Singleton" + typeof(T).ToString();
            
            return _instance;
        }
    }
    
    protected virtual void Awake() {
        if (_instance == null) {
            _instance = this as T;
        }
        else if (_instance != this) {
            Destroy(this);
        }
    }
}
plucky laurel
#

something like this

#

that code also probably assumes that you have domain reload disabled on play

#

since i dont have it enabled for years i dont really know how the InitializeOnLoad and statics should be properly working there

mellow sail
#

hello guys, i wanted to ask. What would be the most effecient way in making a touch input for a button?

sly grove
#

wdym by "efficient"?

#

is there something inefficient about how buttons normally work?

mellow sail
#

nah i mean making an input system using touch for a button

#

some people said using this asset

#

i found a tutorial too in youtube. Is it more easy using this?

sly grove
#

are you asking how to use UI buttons when you are using the new input system?

mellow sail
#

Sorry for the confusion. Im making a button that would execute something when its tapped (touch) for a mobile game. Is there an easier way or the quickest way in making that other than the new input system?

sly grove
#

you just want a UI button

#

the fact that it's a mobile game isn't really relevant

mellow sail
#

Oops, okay then ill moved into the ui ux section

azure moss
#

Is there anyway to change animation execution order?

#

reason being i am doing animation stuffs on FixedUpdate(need to predict for collision stuffs)

#

now can i change bone rotation or something if set AnimatePhysics?

sage radish
azure moss
azure moss
sage radish
azure moss
#

if only i knew this a lot earlier....

tired wyvern
#

Isn't Resources.Load() misleading in its name? The asset in the resources folder is loaded at the start of the game. It's actually just returning a reference given a string path

regal olive
#

So for the past 16 hours I'd been struggling with this issue. Where I'm casting a sphere from the cameras position inside the players controller.

The way Unitys raycast/spherecast works, generally speaking it's not supposed to return a collider if the origin of the cast intersects it.

My issue was that when I fired and jumped at the same time, the raycasthit would usually return my players collider. Not what I wanted.

Spent HOURS debugging and trying to zero in on the issue. Then I put my Character Controller's Move() function inside Fixed Update.

And now the bug is gone.

#

So I guess my question is: does the game only update the games colliders on Fixed update? Even if the object itself is moving in update?

sly grove
#

which is synced with FixedUpdate

regal olive
#

Ah

sly grove
#

a call to Physics.SyncTransforms() would do it too

regal olive
#

I guess it makes sense.

regal olive
sly grove
#

if you change a collider position in Update and need it to be visible to physics queries at that time, sure

regal olive
#

Thanks!

raven jetty
#

Yo Ive been struggling with the Tilemap.BoxFill. I've checked just about every forum post about it but I still cant seem to get it to work

background.origin = Vector3Int.zero;
background.size = new Vector3Int(width, height);
Debug.Log($"Tilemap Size: {background.size}");
background.ResizeBounds();
Debug.Log($"Tilemap Bounds: {background.cellBounds}");

background.BoxFill(background.origin, backgroundTile, background.origin.x, background.origin.y, background.size.x, background.size.y);

My debugs return that the size is what Id expect (9, 9, 1) and the debug for the bounds gives the position as (0, 0, 0) and size as (9, 9, 1) as well, but for whatever reason the tilemap refuses to fill no matter how I go about it
At one point I even tried doing my own for loops using the SetTile but that didnt do anything other than give me this single tile as well

Anyone able to point out where Ive gone wrong?

Edit: Ive also tried changing the arguements being passed into boxfill to just about every combo I can think of and it seems to do very little

coral schooner
obtuse arch
#

I have this basic InputBufferAction struct which utilizes FrameSliceCounter which is also a struct. They work perfectly when I make them serializable or when I make them class (non-serializable) but break when they are struct and non-serializable.

For eg. in image the frameSliceCounter should count 15->14 then in next frame 14-13 and so on, with class and serializedStruct the state(frame Idx) is preserved while with non-serialized struct they dont. Any insights ?

sly grove
#

but basically - it sounds like you are probably getting tripped up somewhere by the pass-by-value and copy-on-assign semantics of structs

glacial zodiac
#

Automatic File Reading

obtuse arch
# sly grove it's unclear how and where this code is running

Sorry I forgot to mention, But consider the HasFrameSliceExpired()' in BufferdInputAction as an Update() loop as it is invoked in one.

Thats all, there are no extra calls to method,
I understand pass by value and ref and ik structs are blittable types, but Im unable to grasp where the link breaks. There are no assignments no variable resets nothing, just making it serializable works and removing it breaks it.

dusty wigeon
obtuse arch
dusty wigeon
raven jetty
sand grail
#

Collider[] colliders = Physics.OverlapSphere(transform.position , radius); is there any way to change the source code for Physics.OverlapSphere or any overlap?

#

when taking the colliders into the array to be exact

dusty wigeon
sand grail
#

saves a lot of time

#

because i would not have to iterate trough all the array

dusty wigeon
#

Which colliders enter the array ?

sand grail
#

whatever i want

#

with the ID i want

#

or whatever

dusty wigeon
#

because why was so hard for this command to let me choose** which colliders enter the array**

#

What collider ?

#

It is the result of the function.

#

What you want ?

sand grail
#

i just want to have an overload for this function where it creates the array and takes in just the colliders with the tag i want

#

i would want to acces the source code for Physics and find the function

#

is it possible

fresh salmon
#

OverlapSphere peeks into the C++ side, the physics engine. You can't

sand grail
#

if yes where to look

sand grail
#

impossible*

#

c++ is no concern to me

thin mesa
#

you planning to re-write PhysX?

dusty wigeon
#

You can use layers ?

sand grail
#

is just an overload

sand grail
#

could you explain more?

fresh salmon
#

I don't understand why you would need to take an array in that. It's a physics call, it queries the physics engine and returns the collider around some point. If you need to do some filtering on the results, it's either afterwards on the array that it returns, or beforehand with a Layer Mask

thin mesa
sand grail
#

iteration with an O(n) algo is just pain

fresh salmon
#

That's an XY problem here

#

Querying the physics engine is cheap

dusty wigeon
fresh salmon
#

Profile, only optimize if it needs to be optimized

dusty wigeon
#

Big O is only useful with high numbers.

hasty monolith
#

Hello I'm having an issue with DoTween that warns reaching maximum tweens. It comes from an object that is spawned quite a lot so I'm suspecting that I'm not properly killing my sequence but can't figure it out exactly.

private Sequence sequence;
private void Start()
    {
        sequence = DOTween.Sequence();

        sequence.Append(transform.DOMove(transform.position + (Vector3)Random.insideUnitCircle.normalized, 1).SetEase(Ease.OutCirc)).SetTarget(transform);
        sequence.AppendCallback(() => Destroy());
    }

    private void Destroy()
    {
        Destroy(this.gameObject);
    }

    private void OnDestroy()
    {
        sequence.Kill();
    }
sand grail
sand grail
#

i tested when maxed

#

i got -10 frames

#

which tbh is a lot

dusty wigeon
#

It is going to take a ridiculous short time.

#

How many frame are you running ?

sand grail
#

60

#

peak

dusty wigeon
#

So, you went down to 50

sand grail
#

yes

dusty wigeon
#

How many colliders do you have ?

sand grail
#

total?

dusty wigeon
#

Yes. Approximatively

#

100, 1'000, 100'000 ?

sand grail
#

normal items and entities - 20

world structers and others - 30

fresh salmon
#

40? lmao

sly grove
dusty wigeon
#

Are you running the request on every object ?

fresh salmon
#

The shotgun I made shoots more than that

sly grove
#

this creates garbage

hasty monolith
sand grail
sand grail
hasty monolith
dusty wigeon
sly grove
fresh salmon
#

Yeah I was wondering if using OnTrigger* methods would lighten that up

sly grove
sand grail
#

wait that's a genious idea

sly grove
#

so I assume they go away when they're done

sand grail
#

how could

dusty wigeon
#

And layers to reduce the number of potential collision with object that cannot and should not collide.

sly grove
#

or in OnDestroy

#

after sequence.Kill

sand grail
#

i am so dumbfounded that i did not think about that

hasty monolith
gray creek
#

Is it possible to not draw a specific set of meshes in the editor so that I can have a custom OnSceneGui to draw meshes?

dusty wigeon
frail parrot
#

out of curiosity, how do those Vector3 shorthands work, like Vector3.left? From what I can see in the code all it says is {get;}, but that doesn't explain how there's a difference between Vector3.left and Vector3.right

dusty wigeon
frail parrot
#

well yeah I know that, but how does the code specify that

dusty wigeon
#

What exactly you want to know ?

#

Because it seem pretty straigh forward.

frail parrot
#

on the class of Vector3, this is what it says for Vector3.left and Vector3.right

#

all it says is {get;}

#

and they read the exact same

#

how does it know what to return

dusty wigeon
#

You are looking a decompiled code.

frail parrot
#

ah

#

i'm dumb

somber swift
dusty wigeon
#

Here you go.

frail parrot
#

yeah that makes a lot more sense, thanks lmao

gray creek
# dusty wigeon I do not understand what you are asking for.

I want to create a component that allows designers to specify different armors for submeshes. For example, the head could be a critical zone which would have a debug color of red, and the hands and feet could be trivial zones which would have a debug color of blue.

gray creek
dusty wigeon
#

However, normally, you do not use mesh collision but primitive for collision such as hit zone.

#

(Hit zone are sometimes bigger then the actual target)

hazy epoch
#

I believe I've asked this before, but don't recall if I got a concrete answer or not. If I have a ScriptableObject asset, and that ScriptableObject class has methods in it... If there are two separate GameObjects in a scene that have a script on them that references the ScriptableObject asset, and I call one of the methods on GameObject(A)...will it automatically excute on GameObject(B) too? ...just double checking my understanding of ScriptableObjects usage and how they work.

orchid marsh
dense drift
#

hey so i am working on a game involving vr controllers and I would like to know what do i have to do in unity if I want to link a UI menu i created in unity to connect to the controller
ive been told it is code related i just dont know what lines of code they would be

obtuse arch
#

Probably due to Unity Serialization

dense drift
hardy sentinel
#

libraries of code 😛 check for ready asset if you're new to coding, as this is no simple task, and anything you hear in #archived-code-advanced is probably gonna be way too complex

untold folio
#

dang I thought you were calling them a liberal

dense drift
hardy sentinel
#

the asset store would be the go-to

#

I assume you want to render a dot wherever the VR controller is pointing to, detect clicks on buttons, support dragging around, etc

azure moss
#

im not seeing animator stuffs from this playerloop?

#

is legacy animation same as animator's update?

quick ibex
#

How do I get the list of bones from a loaded Mesh asset? Not sure if there's a way. But I've also tried creating a GameObject in a custom editor tool, adding a SkinnedMeshRenderer to it, and then setting the sharedMesh field, and then trying to access the bones array but it is empty.

quick ibex
hardy sentinel
#

when you export a rigged character as FBX from blender, it exports the whole hierarchy, which includes
A) the mesh
B) the bones

#

and when you import it in Unity (or any other game engine), you get a GameObject that contains
A) The root GameObject
B) A GameObject with the renderer (referencing the mesh)
C) The hierarchy of bones

#

so, that said, there's no way to get a list of bones from just a Mesh asset

quick ibex
#

what about the bones array on the SkinnedMeshRenderer? otherwise I can get the bone names from the heirarchy

hardy sentinel
#

you would need to access the prefab

quick ibex
#

I'll try that, thank you

sage radish
quick ibex
hardy sentinel
hardy sentinel
#

ah I doubt you can get those, unless editor scripting (?)

quick ibex
#

yes I'm creating an editor tool to import and setup ~3000 assets, so can't do anything manually 😢

quick ibex
plucky laurel
#

those are built in materials, im not aware how to get them after the fact but they must be present during import, if there is no way otherwise you can try caching them in your custom asset post processor

#

built in the fbx, generated by unity

hardy sentinel
#

you should be able to get those via Importer yeah. pretty sure I had.. I can check for an old importer in like 10 minutes

#

hmm iirc I wrote another script to edit those to hardcoded values

#

or.. nvm

hardy sentinel
#

doesn't work.. 😛 sec

#

I remember I had to do some hack for this, just not 100% certain which hack 😄

#

@quick ibex can you post the .meta file of the model whose inspector you linked?

quick ibex
#

I'll DM you

hardy sentinel
#

I wonder if the names are there :p

quick ibex
#

hmmm doesn't look like the names are there

hardy sentinel
#

RIGHT! so.. once you export, the fields for 'remapped materials' should match the name of the material

#

my importer is on an HDD I don't wanna bother attaching now, but the hack I remember I did was something like this:

var originalAssetPath = AssetDatabase.GetAssetPath(myObject);
MoveAllMaterialsToFolder($"{originalAssetPath.TrimEnd(".fbx")}/Materials");

var importer = (ModelImporter) AssetImporter.GetAtPath(originalAssetPath);
importer.materialLocation = ModelImporterMaterialLocation.External;
importer.SearchAndRemapMaterials(ModelImporterMaterialName.BasedOnMaterialName, ModelImporterMaterialSearch.Local);
importer.SaveAndReImport();
#

this made all materials get automatically mapped from the Materials folder.. but I never managed to get the name of the fields (neither did I need them, tho)

quick ibex
#

I really just need the names, because I have a bunch of textures that have the material slot names in their file names. I guess my last resort is to use a fbx file importer library 🤣

hardy sentinel
#

I also had another script that exported all textures and stuff to match the material name (on 3D software)

#

so, Ball.mat would have Ball_Diffuse.png, Ball_Height.png, Ball_Normal.png, Ball_[...].png

#

but yeah.. those names are probably not obtainable easily.. there should be a way if you dive deep in Unity's inspector internals, but Unity doesn't like that ;p

quick ibex
#

that's alright, I'll just do the ineficient thing and load the file again using a fbx importer library haha

#

thanks for your help

hardy sentinel
novel plinth
#

if they're not merged into a single mesh you can just do var meshes = myGo.GetComponentsInChildren<MeshFilter>(); and do the same as above to get the name

tropic stag
#

I'm trying to transition an animated model to a ragdoll in unity and it looks "explosive". I already set each rigidbody's velocity and angular velocity t; zero. what else can I try?

brave wharf
#

guys hello how can i fix this error

orchid marsh
#

False positive. Restart the Unity Editor or simply clear the logs / ignore it.

brave wharf
#

when i press the play button it comes

#

im restarting now

#

yes it worked i think

#

thanks 🙂

tiny pewter
#

what is the algorithm of linecast (or raycast) on a quadtree
four children check if line intersect (or is contained) in the AABB, if yes then recursively call on those children intersected? it sounds slow but i only comes up with this algorithm, probably can be slghtly speeded up by cohen-sutherland algorithm

sly grove
molten socket
#

I have a 6 vertex, 5 polygon extruded triangle that is built in code. I would like each face to have a unique material with its own UV coordinates. How could I do this?

sly grove
#

each material corresponds to a submesh

#

split your mesh into submeshes and you'll be able to apply a separate material to each

molten socket
#

I've been doing that! And I managed to get every submesh its own material.

#

My issue came with the UV

#

For some reason, no matter what I did - each one of my submeshes used the first one's UV

sly grove
#

sounds like you need to actually do the UV mapping process in Blender

molten socket
#

That's the thing, I can't!

#

It's a dynamic shape

#

It will always be an extruded triangle

sly grove
#

if you are making the mesh programmatically you will need to assign the UVs programmatically

molten socket
#

But the size and angles will change

molten socket
#

And I would Love to do that

#

But it's not doing it the way I would expect it, and unfortunately - I can't quite figure out anything else to try..!

#

I'll send some code in just a bit!

sly grove
#

I presume you simply have a bug in your code if it's not turning out properly

molten socket
#
public Mesh createMesh(List<Vector3> vertices, float thiccness, float offset)
{
    Mesh mesh = new Mesh();
    float topHeight = thiccness * (offset+1);
    float botHeight = thiccness * offset;
    //Set the vertices
    Vector3[] meshVertices = new Vector3[6];
    meshVertices[0] = vertices[idA] * topHeight;    //A Top
    meshVertices[1] = vertices[idB] * topHeight;    //B Top
    meshVertices[2] = vertices[idC] * topHeight;    //C Top
    meshVertices[3] = vertices[idA] * botHeight;    //A Bot
    meshVertices[4] = vertices[idB] * botHeight;    //B Bot
    meshVertices[5] = vertices[idC] * botHeight;    //C Bot
    mesh.vertices = meshVertices;
    int topMeshIndex = 0;
    int acSideMeshIndex = 1;
    int botMeshIndex = 2;
    //Triangles
    int[] topTriangle = new int[3]
    {
        0, 1, 2,    //Top
    };
    
    int[] acSideTriangles = new int[3*2]
    {
        0, 2, 3,    //AC Top
        5, 3, 2,    //AC Bot
    };
    mesh.subMeshCount = 2;
    mesh.SetTriangles(topTriangle, topMeshIndex);
    mesh.SetTriangles(acSideTriangles, acSideMeshIndex);
    // mesh.SetTriangles(botTriangle, botMeshIndex);
    //UV
    Vector2[] topUV = new Vector2[3]
    {
        new Vector2(0   , 0),
        new Vector2(0.5f, 1),
        new Vector2(1   , 1)
    };
    Vector2[] acSideUV = new Vector2[4]
    { 
        new Vector2(0   , 0),
        new Vector2(1   , 0),
        new Vector2(1   , 1),
        new Vector2(0   , 1)
    };
    mesh.SetUVs(topMeshIndex, topUV);
    mesh.SetUVs(acSideMeshIndex, acSideUV);
    //Calculate normals (optional)
    // mesh.RecalculateNormals();
    // Return the created mesh
    return mesh;
}

I removed some parts for clarity - I have all the sides setup, and mapped out correctly

#

My problem comes with the fact that all of my sides use the topMeshIndex UV

#

If I uncomment mesh.SetUVs(topMeshIndex, topUV);, then the acSide no longer has any UV either.

#

Also this doesn't work in the first place

#

I was padding the UV arrays to have 6 elements before

quick ibex
cyan vessel
#

hmm... so, I'm confused about one property of asset bundles - when I load asset bundle filled with sprites in one scene (loads ok) and then switch scenes, texture associated with that asset bundle gets destroyed while sprites are still there, using destroyed texture

#

texture seems to be auto-generated atlas by Unity containing all sprites of asset bundle I'm loading

#

so basically:

Before scene change:
asset bundle > sprites loaded from bundle > auto-generated texture backing the sprites

After scene change:
asset bundle > sprites loaded from bundle > null

#

any idea why this happens? I'm sure I'm not deleting the texture manually

dusty wigeon
#

If you delete asset. (Destroy(...)) They will be destroyed from the asset bundle if I remember correctly.

cyan vessel
#

so I'm assuming it's something related to how Unity handles dynamic sprite atlasing

dusty wigeon
#

I'm using Atlas in an AssetBundle without any issue.

copper plover
#

is gpu skinning good on a GPU bottlenecked game?

plucky laurel
#

never used but i know the theory, and what it achieves is removes all the cpu objects, transforms, vertex buffers and offloads to gpu shader

#

so maybe it can help by removing the cpu/ram/gpu roundtrip, reduce bandwith usage, but the shaders become more complex

raven jetty
# coral schooner BoxFill is pretty buggy last time I checked. I would try setting a single ``back...

Yo sorry to bug you but this doesnt seem to like me either and I wasnt sure if you knew of anything I might be missing to make it hate me

background.origin = Vector3Int.zero;
background.size = new Vector3Int(width, height);
background.ResizeBounds();

Debug.Log($"Tilemap Size: {background.size}");
Debug.Log($"Tilemap Bounds: {background.cellBounds}");

background.SetTile(background.origin, backgroundTile);
background.SetTile(background.origin + background.size, backgroundTile);
background.BoxFill(background.origin, backgroundTile, background.origin.x, background.origin.y, background.size.x, background.size.y);

I tried playing with the arguements being passed in and doing things like not resizing the bounds and whatever else but it still just gives me a single tile shown like before. Is there anything in the inspector I should be double checking or are tilemaps just a bit funky sometimes?

potent shoal
#

Greetings, I'm running into a dillama where I need to use .net framework in my unity project over .net standard.
I am wondering if that is a dangerous choice long term, and if it is advisable to avoid it.

#

I ideally want to run my game on multiple platforms in the future.

coral schooner
dusty wigeon
coral schooner
# raven jetty Yo sorry to bug you but this doesnt seem to like me either and I wasnt sure if y...

I see the issue now, the problem is the position argument is not for the origin, or rather, it doesn't work for the origin, do this instead:

background.ClearAllTiles(); //Optional
background.origin = Vector3Int.zero;
background.size = new Vector3Int(width, height);
var endPosition = background.origin + background.size;//In case origin isn't 0
background.BoxFill(endPosition, backgroundTile, background.origin.x, background.origin.y, endPosition.x, endPosition.y);
background.ResizeBounds();

And needless to say make sure backgroundTile isn't null. This is why we need Option<T> in C#.

grave rune
#

I thought it was Nullable<T>

sour robin
#

Does anyone have any idea on how to reduce the time a SphereCast creates? Im doing a spherecast to detect objects to damage and the profiler is reading that this spherecast is taking 20ms to run. Is this normal? What can i do to reduce it

{
    foreach (Collider col in Physics.OverlapSphere(transform.position, radius))
    {
        if (col.attachedRigidbody == null || col.gameObject.Equals(gameObject)) continue;

        foreach (IDamageReceiver damageReceiver in col.GetComponents<IDamageReceiver>())
        {
            if (impactEvent.Receivers != null)
            {
                if (impactEvent.Receivers.Contains(damageReceiver)) continue;
            }
           
            float distance = Vector3.Distance(damageReceiver.Position, transform.position);
            float damageFalloff = Mathf.Clamp(RawDamage / Mathf.Pow(distance, 2 / radius), 0, RawDamage);
            damageReceiver.Damage(new HealthEvent(damageFalloff,
                                                  damageReceiver.Position,
                                                  (damageReceiver.Position - transform.position).normalized,
                                                  source));
        }
    }

    base.Activate(source, impactEvent);
}```
fresh salmon
#

OverlapSphere you mean?
Yes, a good start would be to use the non-allocating version of it, SphereCastNonAlloc. Instead of creating an array each time it's called, you pass your own and it fills it by reference.
Another way that would be more performant if you have a lot of objects with that script on, would be to not use SphereCast at all, and track what enters and exits your vicinity using OnTrigger* methods

coral schooner
sour robin
fresh salmon
#

Allocate an array that's estimately big enough to store the maximum colliders you might have in one query. It returns an int that tells you how much of them it detected, you can for-loop with that

sour robin
#

Alright, ill give that a go

sour robin
#

Ran into another problem, Unsure if this is the right channel; Would anyone have any ideas as to why [ParticleSystem].Stop() is causing a performance spike of over 350ms?

raven jetty
inland halo
#

Hello working on a multiplayer game i got this error just now havent been able to figure it out, using Photon 2 free

fresh salmon
#

It's a warning, not an error. It's telling you that PrefabInstanceStatus.Disconnected is obsolete for the reason stated in the message: prefabs can never be in a "disconnected" state. You can remove the second part of that condition entirely.

#

(you can keep it, it won't do anything, but it might transform into an error if you upgrade the version of Photon later on)

inland halo
fresh salmon
#

No, what's after the || and the || itself

inland halo
#

yes ofcourse thanks

plucky trellis
#

I'm trying to use a compute shader in a command buffer, but setting data in a compute buffer with cmd.SetComputeBufferData() is for some reason, depreciated? Why? What's the alternative?

#

Ohh wait cmd.SetBufferData() exists now, nevermind.

glacial wedge
upbeat bane
#

hello! I created this mesh, and now I want to change the color of the selected face (like in the image). How can I change the vertex color? Do I have to user shaders?

tall ferry
glacial wedge
tall ferry
glacial wedge
#

I'm doing an OverlapSphereNonAlloc in a specified point, but i don't know if there are 10 or 1000 colliders near the point. I'm good taking the closest 10. dunno if i can keep the array size = 10 or have to take in consideration all the colliders and than filter for distance

tall ferry
obtuse arch
next marsh
#

I'm monkeying around with writing my own collision system using Burst but I've hit a bit of a wall design-wise. Here's my current process:

  1. For each object, I get all the nearby object (optimized with quadtree partitioning)
  2. I pass the object along with its found neighbors each into their own job to check and resolve movement and collisions for that object (in -> a collider info NativeArray, out -> a 1-index-long Vector2 position NativeArray)
  3. I apply the output position to the transform of the main object
  4. I adjust the quadtree partition based on all the objects' new positions

I'm having terrible overhead in allocating NativeArrays with miniscule time spent in jobs.

Do I expand the neighbor searching and batch groups of collisions together instead of giving each one their own job? Do I consolodate all of them into a single job- if so, how can I do that while still using a quadtree to avoid n^2 performance?

TL-DR; Too many NativeArray allocations are killing my performance. What's a better approach that keeps the quadtree performance gains in lieu of giving each thing in my scene their own job to resolve nearby collisions?

sage radish
#

NativeArray allocation performance

brisk spruce
tiny pewter
#

no you dont even need to sort, you only need a max heap of size 10

#

so for finding 10 smallest item in n items only require O(n log(10)) = linear run time

hardy jacinth
#

Is there a library that handles HLSL or Shaderlab AST?
To be precise, I would like to generate shaderlab or hlsl shaders from code and be able to transform them easily

#

The only thing I found for now is a reference on Vulkan's site to something called DXC (DirectXShaderCompiler) which under the hood generates an AST after parsing HLSL

#

can it help me and is it possible to use it in unity somehow?

azure moss
#

What's the proper way to slow down animator update? What I mean by this is, I want to lower animation update at far distance, somewhat similar to what RDR2 and Elden Ring does. What's the way to approach that?

#

I know about animator.update but that's not a solution since its single threaded only

sage radish
dusty wigeon
azure moss
dusty wigeon
#

Just be more aggressive with it.

azure moss
#

I got a scene of 2000+ objects

#

Not DOTS btw

dusty wigeon
#

You might consider switching to DOTS...

azure moss
#

I killed animation at far distance

azure moss
dusty wigeon
azure moss
#

Also not much Hybrid solution out there

azure moss
dusty wigeon
#

Still, the answer is using Update.

#

It works well when you have a relatively small amount of object.

#

You spread the update on multiple frame.

azure moss
#

Can I spread it using Job? Does Update support parallel calculation even?

#

Oh got what you meant

dusty wigeon
#

I think you might be interested in using the Playable API.

#

There is finer control there.

#

Maybe you can solve your batching issue.

dusty wigeon
#

It works correctly when you have a relatively small amount of object.

#

I have done it*

#

Do not remember the exact performance gain though.

azure moss
#

I have 2 layer and using prediction to replay from previously left state using Time.time

#

1st layer is normal

#

2nd layer is the one where animator just disabled

azure moss
#

also following strict pattern of blend tree to make prediction work

dusty wigeon
#

Prediction ?

#

In an Animator ?

azure moss
#

Firstly you calculate Time.time when you disable

#

Later on lets say you are close by, then when turning it back on you substract current time with previously left time

dusty wigeon
#

Oh, you mean to start animation where it should be starting again.

azure moss
#

Yeah

dusty wigeon
#

Pretty much over-engineering in my opinion.

azure moss
#

For blend tree we are using 60 frames for idle, 30+30 for walking and 20+20+20 for running. To have accurate prediction

azure moss
dusty wigeon
#

Because there is more object, the player will not be bother by the small detail.

#

You can also keep the animator state when you disable it.

#

If you did not know.

azure moss
#

I mean we have problems where player is not getting its shield up behind back thanks to culling

#

To address that we introduced temporary always animate behind our back using spatial partioning

#

Can predict attacks now

dusty wigeon
#

I had this issue like yesterday.

azure moss
#

Unity doesnt give much access

dusty wigeon
#

Just set the object that was causing an issue to always animated.

#

I think the issue was because the animation was driving the position of the object.

azure moss
#

The way i see it, you have to tweak around between culling and always animate

#

I believe you should spatial partioning to make characters split into grids

#

Lets say i attacked or npc behind me attacking one another

dusty wigeon
#

You are over-engineering yet again.

azure moss
#

By default thanks to idle they wont do anything

#

Will never hit each other unless you just go radius or sphere collision

#

Design wise its not that good atleast in my case

#

Had to temporarily enable animation based on timer of the attacker's clip time

sleek terrace
#

Why do shaders on tilemap not work on Hex pointed top?
It seems whenever I apply a material to a hex pointed top map. the hexes convert to a flat top

azure moss
#

We achieved what we need but still worried how unity handles Animator.Update()

sleek terrace
#

They both use thesame material
but in tilemap, the hex shape is changed

trim shard
#

Good afternoon,
Can anyone help me with this? I'm trying to send an API request but it gives me this error: Curl error 60: Cert verify failed: UNITYTLS_X509VERIFY_FLAG_USER_ERROR1

#

I have looked for a solution in several places but have not found an answer

sleek terrace
trim shard
#

according to the api code manager, yes

#

I am in contact with him trying to resolve

#

the url works directly through the browser, only this problem occurs inside unity

dusty wigeon
#

Did you try to use something like Postman ?

trim shard
#
        // string url = "https://avatarmuskverse.com/login-game?username="+ userName +"&password="+ password + "&version=" + versao;
        string url = "https://avatarmuskverse.com/login-game?username=lmjDixon&password=******&version=1";

        UnityWebRequest www = UnityWebRequest.Get(url);
        Debug.Log("URL LOGIN: " + url);
        // www.SetRequestHeader("Content-Type", "application/json");
        // www.SetRequestHeader("X-Requested-With", "XMLHttpRequest");

        yield return www.SendWebRequest();

        if(www.isNetworkError || www.isHttpError){
            Debug.Log("Erro ao logar: " + www.error);   

        }else{
            string json = www.downloadHandler.text;
            retornoInfoUsuario = JsonUtility.FromJson<RetornoInfoUsuario>(json);

            Debug.Log("Conexão efetuada com sucesso");
        }

    }```
sly grove
fresh salmon
#

Can you try outside of Unity with wget or curl, wahtever you have?

#

Also change that password if it's the real password. It's both now leaked, and insecure

trim shard
sleek terrace
#

No one knows what could be causing my problem with the hexes?

trim shard
#

thanks, i will change

#

but now is just one test

trim shard
dusty wigeon
#

Also, what platform are you using ?

trim shard
trim shard
#

sorry my english

dusty wigeon
trim shard
#

do you think my windows defender is related?

dusty wigeon
#

If it was on other platform like Android or Hololens it could have been explained online.

trim shard
trim shard
#

I will keep looking

#

thanks for help

trim shard
tropic stag
#

I'm following a yt tutorial on how to transition from a ragdoll back to animation, and I'm trying to lerp my bones towards the first frame of my animation. But using animationclip.SampleAnimation() I'm getting bone positions in a t pose? Why would sample animation give me a t pose?

#

update: works if I reduce the weight on an animation layer... but sampleanimation cares about layers?

pseudo onyx
#
 private int FacingSign
    {
        get
        {
            Vector3 perp = Vector3.Cross(transform.forward, Vector3.forward);
            float dir = Vector3.Dot(perp, transform.up);
            return dir > 0f ? -1 : dir < 0f ? 1 : 0;
        }
    }

the property returns a value based on the dot product result. If the dot product is greater than 0, it means the character is facing left, so it returns -1. If the dot product is less than 0, it means the character is facing right, so it returns 1. If the dot product is exactly 0, it means the character is facing neither left nor right, so it returns 0.

Is this an accurate diagram to represent this code?