#archived-code-advanced

1 messages · Page 75 of 1

fresh salmon
#

If I remember correctly the code is somewhere under the References node of the project

#

At tleast that's where it is for regular C# apps

scenic forge
#

It's there, but you should also be able to just Ctrl + Click it.

brisk spruce
#

ah yeah I see that, couldnt F12 into it or anything

#

also only shows up for me during runtime on a breakpoint

dawn kettle
#

Does anyone know how I could make an efficient but simple inventory system that supports trading between players and mining resources.

dawn kettle
#

I really just want to go with the easiest inventory system possible

#

Meaning no pickups, no sorting, nothing like that

#

If I obtain an item, it will be put at the bottom of my inventory list

tall ferry
dawn kettle
#

Well couldn’t it just be played data

#

I’m using coherence multiplayer right now and it works really well

#

I just need to be able to transfer player data

tall ferry
#

Im unsure what you mean "player data", that is pretty vague

dawn kettle
#

Player data

#

I’m unsure too

#

Because I don’t know what I’m doing

quartz stratus
#

For anyone looking for a solution to this in the future: I got IPreBuildSetup working (I had my test assemblies set up wrong before so the callbacks weren't being called). And there has to be at least one NUnit test in the class or the interface callbacks won't be run. And make sure you don't rely on any static data in the set up method, it occurs before the assembly reload so any static data will be lost. I ended up setting a value in PlayerPrefs so I can read it in RuntimeInitializeOnLoad. Not elegant but it works. I'll take it, since there's no built-in way Unity provides for differentiating between Play Mode triggered by tests vs. Play Mode triggered in other ways.

wet burrow
#

When are you supposed to use EditorCoroutines vs regular coroutines? I've found some code I have to work with that's full of the former, even though I'm sure the code is meant to run at runtime.

tender ingot
#

Anyone know the best way to have a stable frame rate for 500 instances of a zombie prefab? I am using 2021.3 so can't use ecs.

#

I should mention too it's for WebGL

livid kraken
#

Look into gpu instancing

flint sage
#

Goign to need to pull lots of tricks to pull that off on webgl

#

Also look into billboarding

tender ingot
livid kraken
tender ingot
# livid kraken Have you tried profiling to see your actual bottleneck?

I believe it's because I have just 500 clones of a prefab in my hierarchy. I have heard of pooling the instantiate in memory however I can't for the life of me find anyone discussing how to do this besides lists and ECS but I wouldn't know how lists would interact with the process of instantiating a zombie prefab and have it live in the scene besides having it add to a list and whoever is in the list gets instantiated into the scene but would be the same as having clones of the prefab in the hierarchy ?

livid kraken
#

Simply having 500 objects in the hierarchy means nothing

#

Use the profiler and see what is taking up performance

tender ingot
dusty wigeon
# tender ingot I should mention too it's for WebGL

I really doubt that you would be able to run 500 instances of complex object in WebGL. You gonna need to make a lot of sacrifice like only using a defined height, not using pathfinding, using billboard, no physics component, etc.

tender ingot
raw lily
#

Does anyone have a good resource to share, or can give me some insight on the following?

What should I keep in mind while managing cameras in Unity for performance. Is it fine to have a script that'll cycle through them and just disable the gameObject if a camera is not needed?

turbid tinsel
wooden cedar
#

Or better yet if you can get away with no collisions, it will greatly speed up the enable/disable of your pooling

dawn kettle
#

Hey everyone! I have a quick question on an inventory system. Once I make an inventory system I want to create a warehouse system, where I can store items in that warehouse but it’s private only to my items. Since it’s a multiplayer game, each player can access the warehouse but instead of seeing other people’s items, they see their own private warehouse where they can stash and take items.

sly grove
upbeat path
#

an inventory of inventorys keyed by player id

dawn kettle
#

Is anyone familiar with coherence?

#

It’s a multiplayer networking service

#

That makes multiplayer very simple and easy

#

And they have accounts for games

#

So I’m guessing I can attach the inventory to that player data

earnest heron
#

Hey guys,
I'm getting back to use Unity after a few years. Just checking on of my projects and trying to modify some stuff.
I don't know how widely Zenject/Extenject is used nowadays but I have a question about it.

I have a gameObject which is called Player, It has GameObjectContext and MonoInstaller and I bind an integer there. I have a prefab (Character) which is instantiated by Player and Factory. In Character facade class, I use method injection and trying to get that integer. But it is failed and it is not resolved. How can I fix that issue ?

brisk spruce
#

You have to use the zenject instantiate method, by injecting a factory into the thing that does the instantiation

#

There's examples on the zenject docs

tired fog
#

I need some help understanding a bug I'm having. I have a compute buffer containing indices that are important. Those indices are then transformed into position and set on another compute buffer with a compute shader. So

Indices = {1,4,5,8,10}
for loop with indexI of length of indices (5)
{
  get the first indice
  transform it into a position
  verify if position is valid
  if so
  {
    finalpositions[indexI] = position
    finalIndices.append(indexI)
  }
}

the final positions buffer and the final indices bufer are pre seted on a material, all of this has been going on through a command buffer so that each step is sequential
then i copy count the finalIndices length
and I call commandbuffer drawmeshinstanced with the material
the material then does

for loop with indexI of length of final indices
{
  float3 position = finalPositions[finalIndices[indexI]]
  draw the object in that position
}

after this loop is done, the loop is repeated with a diferent set of Indices, while reusing the previous command buffers (final indices with a count value set to 0, and finalPositions untouched)
After all the commands are set, the command is executed at a certain point of the event.

The problem is, the meshes flicker. Is like some data is leacking from loop to loop, or at each loop, data is being calculated slightly diferent (the position seems to be the same, however, slightly diferent since a random generator is returning diferent values)

#

Im not sure how to debug it, the frame debugger changes the results when checking the diferent steps meaning that it is not returning the same values at each call, even if the calls and the data is always the same

#

I think there might be somethign about command buffers that I don't understand

gritty python
#

What is this problem?

earnest heron
# brisk spruce You have to use the zenject instantiate method, by injecting a factory into the ...

I'm using factory as I said.

In this way:


using UnityEngine;
using Zenject;

namespace Infrastructure.Factory
{
    // TODO: More option for instantiating like Unity
    public class ZenjectResourceFactory : IResourceFactory
    {
        private readonly DiContainer _container;

        public ZenjectResourceFactory(DiContainer container)
        {
            _container = container;
        }

        public Object Instantiate(Object @object)
        {
            Object instance = Object.Instantiate(@object);
            _container.Inject(instance);
            return instance;
        }

        public Transform Instantiate(Transform transform)
        {
            Transform obj = _container.InstantiatePrefab(transform).transform;
            return obj;
        }

        public Transform Instantiate(Transform transform, Transform parent)
        {
            Transform obj = _container.InstantiatePrefab(transform, parent).transform;
            return obj;
        }

        public Transform Instantiate(Transform transform, Vector3 position)
        {
            Transform obj = _container.InstantiatePrefab(transform).transform;
            obj.transform.position = position;
            return obj;
        }

        public Transform Instantiate(Transform transform, Vector3 position, Transform parent)
        {
            Transform obj = _container.InstantiatePrefab(transform, parent).transform;
            obj.transform.position = position;
            return obj;
        }

        public Transform Instantiate(Transform transform, Vector3 position, Quaternion rotation, Transform parent)
        {
            Transform obj = _container.InstantiatePrefab(transform, parent).transform;
            obj.transform.position = position;
            obj.transform.rotation = rotation;
            return obj;
        }
    }
}
brisk spruce
#

Specifically the prefab one u think

#

Oh hmm it's just an extension method to turn 2 lines of what you have into 1 line... hrmm

timber flame
#

I have a problem with addressable assets when building the project. It is completely OK in the editor.
There is a collection list with 90 elements. They are SOs. It is OK in the editor as I mentioned but in runtime, it logs 360!!! and then I get an exception exist same key because they are populated into a dictionary

earnest heron
tired fog
#

Is there any way to get inbetween data of a compute shaders from a command buffer?

tired fog
#

I need the data to generate colliders later on

#

But it's a conditional case, not all command steps require the generation of colliders

sage radish
#

How frequently? Just once?

tired fog
#

Yeah, i only want the data once, when needed, to generate the colliders, the command buffer is running every frame, but in some of those frames, I want to fetch the data in between commands to later generate the colliders

#

I wanted to avoid dispatching another compute shader just for the data

sage radish
tired fog
#

if I did a separate compute shader, I would do just get data

#

Maybe I can add a graphic fence?

sage radish
tired fog
#

The data is generated in the compute shader

sage radish
#

And stored into a buffer?

tired fog
#

Not stored between frames

#

Stored between commands to execute draw calls

#

But then the buffer get rewritten with new data, more draw calls, and then the frame ends

sage radish
# tired fog Im doing this

Is the condition for whether you need to fetch the data known to the CPU when you're making the commands? Or does it depend on the result of the compute shader?

tired fog
#

It is known to the cpu when Im making the commands, it doesn't depend at all with the compute shader

#

Ideally an AsyncGPUReadbackRequest could work, but that only retrieves the data of the final command dispatch, maybe there's a way of doing it with a graphics fence, but not sure

sage radish
tired fog
#

Im schedulling the command buffer to a camera event

#

So im guesing im not

sage radish
tired fog
#

The problem then is that I need to store that data in N compute buffers, which would kill my memory budget

sage radish
tired fog
#

Since im using only one buffer only always, then im in budget. However, if I need to create a compute buffer for each readback it can get out of hand and kill the budget

#

like
for loop of 20 cases, only storing it to one, a bit of memory, but if I then store those 20 cases, the memory of one * 20 is too much

sage radish
tired fog
#

In cpu ram it is not a bid deal, im quickly disposing it anyways

#

I get the data, check the pool of colliders, apply whatever position it needs to to the pool and dispose of the data

#

So there's no way to stop a command buffer, fetch the data, and continue?

sage radish
#

It would stall the frame, to synchronize the GPU and the CPU.

#

The GPU is busy processing the last frame while you're creating the commands for the next frame.

tired fog
#

Yeah, a bit of delay is expected, I want to at least be able to see how much stalling would it do

sage radish
#

You would have to synchronize it 20 times in your example

#

So that's at least 20 frames of delay.

tired fog
#

yeah

#

so is it possible?

sage radish
#

You might as well just spread the work out over multiple frames.

#

Process one case per frame.

#

Until you're done.

tired fog
#

No, because i need the draw calls to be done at the end of frame

sage radish
#

I think Unity needs to cycle through frames to begin processing async gpu requests. If the main thread is stalled waiting, Unity never gets a chance to process it.

#

The callbacks have to be called on the main thread, but they can't be called there if the main thread is stalled.

tired fog
#

I think I will separate the colliders from the command buffer, and just execute a compute shader for it

#

Thank you

vague sandal
#

whats up

#

so i am making a climbing system and im facing a pretty complicated problem

#

making a climbing system for a straight wall is a pretty easy task as you just add 2 forces that are the negative normal of the wall and the negative gravity

#

depending on if the player is pressing d or q i then move him left or right

#

but what about complex meshes

#

like rock thats made of angles and straight planes

dusty wigeon
dusty wigeon
#

The hard part is definitely having animation that fit or limiting the possible climbing position.

dry bridge
#

Hey guys! So I'm attempting to send bytes from oculus quest 2 but I keep on getting this error: error: ......\modules\highgui\src\window.cpp:281: error: (-215) size.width>0 && size.height>0 in function cv::imshow. I've tried changing the buffer side from python side but to no avail. Any suggestions on how to fix this?

#

Now it works when I'm using the editor but after having it built and ran on Quest 2, the video stream suddenyl doesnt work

tender ingot
turbid tinsel
#

also I'm pretty sure you can use ECS, just not the newest version

tender ingot
turbid tinsel
#

especially for something like this

tender ingot
# turbid tinsel > everywhere you turn see? there you go, you don't see them all at once, you hav...

I was thinking of maybe having all of them set active to false and than turned back on if it's in range of the main camera render. If that is what ur referring to than yeah I am thinking of that as well. I have to keep optimising until it works. There are so any different ways to do this but very limited things to do for WebGL. I also had thought of possibly just storing it all on a server using normal optimisation and it stream the game to a webgl client.

regal olive
#

hello I am trying to make the enemy rotate until the weapon be aiming at the player but I have no idea how to make it can someone help me making it ?

wanton sky
#

does anyone know of an elegant way to deal with effects such as Stun, in a multiplayer game, when one has client prediction? which can cause a desync in positions

remote pumice
urban warren
#

I am trying to figure out what a good spatial partitioning structure would be to use for 'find nearest object to point' type of queries. BVH, Octree, KDTree, BSP, something else? A lot of the objects are static, but some are dynamic. Any recommendations or resources?

#

I am having a hard time finding actually info on what sort of situations the different trees work best for.

sly grove
urban warren
sage radish
#

It might be beneficial to store the static objects in a separate tree optimized for that, and store the dynamic objects in a different tree better suited for updates or quick rebuilding.

urban warren
#

Though, doesn't really help me figure out which tree to use haha

sage radish
#

Yeah, rebuilding the tree is very fast with this, assuming you have the bounds ready.

#

Building the tree is not thread safe, but you can query it from as many jobs as you want.

urban warren
#

Yeah, I would assume as much since it populates a single list

sage radish
#

Even if you find a tree that supports in place updates, if enough objects move at once, rebuilding it is probably faster anyway than inserting and removing many individual objects.

ivory cipher
#

Hi, working in a project where we have 3D and VR.
I'd like to reliably interact with UI elements in World Space with rays, but not limit myself to a specific VR/XR Framework.

Upon research i could not really find any solutions for an InputModule or GraphicRaycaster that let me use my own raycast. All the solutions were based on existing XR Frameworks.
I began writing my own logic for raycasting into the UI and then handling different Selectables, but i'd like to use the unity-provided core where possible for simplicity reasons.

Anyone has ever made experiences with this or could maybe guide me into a direction?
Thanks <3

sly grove
#

it's easier than you think

#

and then you can use all of the built in stuff like IPointerEnterHandler etc

#

And it will also interact perfectly with the UI system etc

#

and put it in the scene

ivory cipher
#

I just assumed that something so basic, that probably finds a lot of use, is already optimized and accessible somewhere

urban warren
sage radish
urban warren
wanton sky
regal olive
dusty wigeon
# wanton sky does anyone know of an elegant way to deal with effects such as Stun, in a multi...

With the movement example, I can have an enemy come and stun me while I thought I can still move. 200 ms latency is enough time for a stun to happen and create a discrepancy between the move I "predicted" client side and what happened server side. This is where "reconciliation" (or "correction") comes in play. The client keeps a history of the positions it predicted. Being still server authoritative, the client still receives (outdated by x ms of latency) positions coming from the server. The client will validate whether the positions it predicted in the past fits with the old positions coming from the server. The client can then detect discrepancies and "correct" its position according to the server's authoritative position. This way, clients can stay server authoritative while still be reactive.

https://docs-multiplayer.unity3d.com/netcode/current/learn/dealing-with-latency/#:~:text=With the movement,still be reactive

solar mist
#

I am having an issue with Synty Characters in Unity.
I have a transform under the Right Shoulder where I am attaching at runtime a weapon to it.
But if I attach it with no Animator Assigned to the character the gun goes where it supposed to go.
[First Picture]

But as soon as I attached any Animator do the character even with only a simple Idle animation. The gun attachment and my transform gets all twisted.
[Second picture]

I have no idea why.

PS.: the same system with the Unity Third Person Controller character from the starter pack works.

frank socket
#

Hello,
I have a game that uses binary to store world save data. In the binary data is an array that stores the position of objects that have been placed by the player.
When I save the data in-game, it works perfectly, however when I forcefully quit the game (alt + f4) or just by stopping it in the Unity editor, and then reloading the save, the array of positions is empty and I can't figure out why yet it works if I save the data first and go back into the main menu scene.

Save Handler Class

public static class SaveManager
{
    public static readonly string FactorySavePath = Application.persistentDataPath + "/saves/{0}.sav";
    public static readonly string SavePath = Application.persistentDataPath + "/saves";
    public static void SaveGameData()
    {
        if (GameManager.Instance == null)
            return;
        if (!Directory.Exists(SavePath))
            Directory.CreateDirectory(SavePath);

        BinaryFormatter formatter = new BinaryFormatter();
        string path = string.Format(FactorySavePath, GameManager.Instance.FactoryName);
        FileStream stream = new FileStream(path, FileMode.OpenOrCreate);

        GameData data = new GameData(GameManager.Instance);

        formatter.Serialize(stream, data);
        stream.Close();

        Debug.Log("Successfully saved to: " + path);
    }
    public static GameData LoadGameData(string factoryName)
    {
        string path = string.Format(FactorySavePath, factoryName);
        if (!File.Exists(path))
            return new GameData();
        BinaryFormatter formatter = new BinaryFormatter();
        FileStream stream = new FileStream(path, FileMode.Open);

        GameData data = formatter.Deserialize(stream) as GameData;
        stream.Close();

        return data;
    }
}

Data Storage Class

[Serializable]
public class GameData
{
    public int Level = 0;
    public int Money = 350;
    public int XP = 0;
    public bool CheatsEnabled = false;
    public DeployableData[] deployableData = new DeployableData[0];

    public GameData(GameManager gameManager = null)
    {
        if (gameManager == null)
            return;
        Level = gameManager.Level;
        Money = gameManager.Money;
        XP = gameManager.XP;
        CheatsEnabled = gameManager.CheatsEnabled;

        List<DeployableData> data = new List<DeployableData>();
        for (int i = 0; i < GameManager.Instance.deployablesInWorld.Count; i++)
        {
            var deployable = GameManager.Instance.deployablesInWorld[i];
            data.Add(new DeployableData()
            {
                name = deployable.ID,
                position = new float[3]
                {
                    deployable.transform.position.x,
                    deployable.transform.position.y,
                    deployable.transform.position.z
                },
                rotation = new float[3]
                {
                    deployable.transform.eulerAngles.x,
                    deployable.transform.eulerAngles.y,
                    deployable.transform.eulerAngles.z
                }
            });
        }
        deployableData = data.ToArray();
    }
}
[Serializable]
public class DeployableData
{
    public string name;
    public float[] position;
    public float[] rotation;
}
frank socket
#

ah okay.

wicked verge
#

System.Security.Cryptography

tall ferry
wicked verge
#

Well what else can you use except BinaryFormatter

tall ferry
scenic forge
#

Any data serialization works too, eg JSON.

wicked verge
#

BinaryWriter

#

XOR encryption also works

wicked verge
tall ferry
# wicked verge XOR encryption also works

I think you have a big misunderstanding at what writing to a file means. Encryption is NOT related to this at all. XOR encryption is just symmetric encryption (which is garbage alone), and is not a file writer or a format even.

wicked verge
errant breach
#

Is it when you write to a file

wicked verge
tall ferry
buoyant leaf
#

if you want non-fallible save states you can do a backup system, where save files don't over write new ones, you just write new files, on load, you would load the latest 5 files and load the most appropriate one, this would solve mid-save corruptions by having fall back

#

I don't know how unity handles crashing/forceful closure, but you can do something like append the current save data to the crash log/dump, if that's even possible

dusty glacier
#

Does anyone know how can I 'extend' a animation curve in this way

#

Baisacly i want to extend it by some distance and when overlap happens the largest value needs to be taken

buoyant leaf
#

do you want to stretch it vertically?

dusty glacier
#

no, on all sides

#

i mean x and y

#

like the expand selection tool in photoshop if you know what i mean

buoyant leaf
#

i think you can multiply the evaluation by the factor

#

not sure tho

#

that would result in a uniform stretch on both x and y axes

dusty glacier
buoyant leaf
#

gimme a second

#

try this on for size

float stretchFactor = 2;
for (int i = 0; i < curve.length; i++)
{
    Keyframe key = curve[i];
    key.time *= stretchFactor;
    key.value *= stretchFactor;
    curve.MoveKey(i, key);
}```
#

@dusty glacier

dusty glacier
#

hold on

buoyant leaf
#

btw you only need to this once, not every frame, unless you're changing said frame

dusty glacier
#

hmm it only seems to scale the curve

#

like you scaled it around the (0, 0) point

buoyant leaf
#

you want it scaled around another point?

dusty glacier
#

let me try another way, one sec

buoyant leaf
#

maybe stretch the time and value seperatly

dusty glacier
#

i want to split every point on the curve in two points

#

left green point should split into blue ones and right one in red ones

scenic forge
#

It's like having a brush trace over the animation curve, or expand selection in various image editing softwares, so it's not just simply scaling the control points.

#

I'm not sure there's a trivial solution to it, and it also seems kind of odd that you need it?

dusty glacier
scenic forge
#

Animation curves are meant to be stretched and the units of time and value aren't the same to begin with, so tracing a circle doesn't make sense.

dusty glacier
#

one sec

#

i am making obstacle detection for character foot movement left box is the position where the foot was and right box is the position where the foot is now and i calculated the hight the foot needs to be lifted to avoid the colision

#

its show with the dotted curve

#

the only problem is that the foot has a length and I need to compensate for that otherwise collision would occur

#

I hope you can understand what I'm trying to do

scenic forge
#

So you want a function that takes in:

  • an animation curve
  • a list of all the obstacles and their bounding boxes
  • the character bounding box
    And output a new animation curve that guarantees the character won't collide with any of obstacles when moving through it?
dusty glacier
#

it should take in an array of heights

#

Actualy sorry, it should take in the curve i already made

scenic forge
#

I mean your obstacles clearly have thickness, you can't just take only the height.

dusty glacier
#

it samples mny points

#

these are boxcasts

#

they dont overlap

#

btw, the foot should never go down betwen the obstacles, as you can see there is a dip betwen the obstacles but the path goes over them

scenic forge
#

But honestly depends on what you are using the output animation curve for, I wouldn't care that much and just cut corners and output an animation curve that's "good enough"

#

Player won't notice if front of their foot collides with corner of the wall for one frame anyways.

dusty glacier
#

i want to publish it as a paid asset, so i want to make it as good as i can

dusty glacier
scenic forge
#

Well good luck, there's no trivial solution to it unless you impose some contraint on what the animaiton curve is like.

#

You can Google keywords such as "image rendering stroke curve algorithm" and you will hit lots of results.

dusty glacier
#

Thanks

scenic forge
#

Seems like the formal term is called "offset algorithm for curves."

smoky heron
#

Hi, I'm trying to disable and enable buttons. If I do playButton.interactable = false; it works well, but when I do playButton.interactable = true; it doesnt work.

Here's the full code if needed
https://pastebin.com/CsvHAXWN

dusk plaza
#

I am new to Await/Task things.
How do I make an threaded task 'return to' the main thread to schedule a job and then go back to 'threaded' to wait for the job to be over?

#

Alternatively, launch a task that will run in main thread and wait for that would also work

tiny pewter
#

impossible, once the thread is "return" to main thread the os will destroy it, but the thread can wait the main thread

scenic forge
stiff hornet
#

(Or if you are using Unity 2023 there is Awaitable built in but UniTask has some other functionality you might want)

misty glade
# smoky heron Hi, I'm trying to disable and enable buttons. If I do `playButton.interactable =...

A few things (and this isn't an advanced question, btw) unrelated to your problem:

  • Don't name things action - Action is a built in class and is gonna cause you headaches if you confuse it.
  • Don't name parameters the same as your methods. This is just confusing. Make your method names verbs - DoAction or ExecuteAction or DelegateAction with a parameter (int actionType).
  • Learn up on enums and use an enum for your parameter here, not an int. We don't do that in C#.

Now on to your actual problem (maybe). Code looks fine, but you have some issues:

  • Instantiate creates a copy of the object in the first parameter. Destroy() on line 43 doesn't do anything if you've linked a prefab, and if you've linked a real object in your scene then it destroys that. You probably meant to do this:
[SerializeField] private GameObject QuitWindowPrefab;
private GameObject _quitWindow;

...

_quitWindow = Instantiate(QuitWindowPrefab, ...);

...

Destroy(_quitWindow);

Now, if I'm guessing correctly, you didn't do it this way, you linked the Play, Settings and Quit Game Button in the actual quit window and you're not using a prefab like I described above. So... you just want to show the quit window:

[SerializeField] private GameObject QuitWindow;
private void OnEnable() => QuitWindow.SetActive(false); // hide it at startup

public void DoAction(int actionType)
{
  switch (actionType)
  {
    ...
    case 2:
      QuitWindow.SetActive(true); // turn on the quit window
      break;
    case 3:
      QuitWindow.SetActive(false); // turn if off
      break;
  }
}
smoky heron
misty glade
#

Well.. I'm telling you that your way of instantiate and destroy won't work more than once. 🙂

#

How are you calling action()?

#

The problem is likely more with how you're calling it since it seems as if the code in this switch statement is fine (if the buttons aren't nested under the QuitWindow)

#

Oh, I bet I know what it is.. Are you wiring up the buttons to this script's action method? If so... then obviously they won't work after you set them to interactable = false. 🙂

smoky heron
misty glade
#

yeah - so you're disabling the buttons in one call which means they can't trigger on the next button press

#

(and the int is fine for this instead of an enum, I didn't realize you were linking it up to unity that way)

misty glade
smoky heron
misty glade
#

not if that other button is disabled too..

smoky heron
#

it isnt

misty glade
#

put some debug code in your method then:

public void DoAction(int actionType)
{
Debug.Log($"DoAction called with actionType:{actionType}.");
}

and at least make sure you're getting it called

smoky heron
#

can i send videos here?

misty glade
#

Sure, send video.. make sure to include the whole screen (+ inspector)

smoky heron
#

its without the debug this

#

but you can see it works too

misty glade
#

ok so back to my original statement.. the issue is that you're instantiate()-ing the new window. This is going to create a new instance of the window, and this new instance of the window isn't going to have correct pointers to the existing buttons

#

You don't want to use instantiate

#

When you create that new quit dialog, yes, it has a component of Buttons on it, but the references to your main screen buttons is.. incorrect

smoky heron
misty glade
#

Yes.. A good way of thinking about a prefab is that it's the design of an object, not the actual object. The design of the object isn't going to have references to the actual buttons in your scene (unless you link them)

#

What you really want to do here is create a quit dialog in your scene, and show/hide it using SetActive(true/false) each time you want to show it.. and in that dialog, make sure that the button is linked to the parent DoAction() script you made

#

I'm not sure how to explain it better - but basically you're creating a new instance of the quit dialog, which won't point to the buttons you're trying to enable/disable

smoky heron
misty glade
#

did you add it to your scene and link it in the inspector?

smoky heron
#

yes

misty glade
#

(to each button)

smoky heron
#

yes

misty glade
#

video it and show me

smoky heron
misty glade
#

you linked to the prefab, not the instance in your scene

#

quitWindow shouldn't be a prefab

#

in general, don't create prefabs unless you're making more than one of something .. I can see that this is sort of confusing you, so you might just be better off not making any prefabs at all

smoky heron
misty glade
#

Video again

#

In any case, I think you can figure this out - but you need to get up to speed on what an instance is, what a prefab is, and make sure that your scripts are "pointing at" the correct objects, because your bug right now is that they aren't.. I'd even stay away from using prefabs and Instantiate() entirely until you understand this a bit better.. You can find more help in #archived-code-general or #💻┃code-beginner , we're clogging this channel up a bit and this is definitely not an advanced question. 🙂

smoky heron
#

the buttons also shouldnt be a prefab?

smoky heron
misty glade
#

They could be but not until you understand prefabs better 🙂 Putting all of your logic in one script called Buttons isn't correct

smoky heron
urban warren
#

I have a large mesh (could be concave or convex), with two 'random' points on it. I am trying to figure out how to get a path along the surface of the mesh from one point to the other.
Any thoughts of a good way to approach this?

#

For added context, the mesh will be cliffs, overhangs, etc. And I want to place objects along the path for the player to walk on to traverse the cliffs/etc.

devout coyote
#

Well a naive solution would be to just have a line above the mesh

#

And then raycast down every X amount of units

#

Depends on how precise you want your path to be

#

Oh that wouldn't work for the overhangs

#

Maybe if you get a lil bit fancier with the raycasts it would still work

sleek terrace
#

I am using graphics.Rendermesh to draw, 4 mesh chunks.

However, the chunks positioning seems to be off. If you take a look at the picture the chunks positions are suppose to be at the position of the green sprites you see.
Anyone know why they are so far off?

#

nvm, figured it out 🙂

misty glade
#

Anyone have any ideas for tweening a nice little "drop" in 2d (don't have access to gravity/physics because I'm doing this in the UI layer)? I tried an animation curve with a parabola but it looks pretty janky to me.

#

linear x and animationcurve y (from 0 to 1 at 0.5 back to 0 at 1)

#

maybe i just EaseIn it in a random circular direction

dusty wigeon
# misty glade Anyone have any ideas for tweening a nice little "drop" in 2d (don't have access...

The sudden stop of the animation is jarring. It also does not feel right. I would try to find an alternative for that:

  • Make the object go all the way. (Then maybe add a secondary window for the object that has been accumulated)
  • Add particles effect to ground the object.
  • Make the object fall in between the cells.
  • Maybe try to have a more isometric view or have a more top down view/movement. At the moment, the movement feel out of place with the rest of the esthetic.
regal olive
misty glade
#

I already have a tweening library.. I was more asking for some good looking tweens since I'm an animationoob. 😛

#

Here's what I settled on for now:

#

just straight out on unit circle with OutQuint over 0.6 sec

regal olive
misty glade
#

thanks.. pretty old piece of code that I use in almost all my projects.. happy to share if you want it

regal olive
#

sure share it why not

misty glade
#
    public class HitText : BetterMonoBehaviour
    {
        public Color StartColor;
        public Color EndColor;
        public TextMeshProUGUI Text;
        public int MinX = -30;
        public int MaxX = 30;
        public int MinY = 50;
        public int MaxY = 70;

        public void ShowAndDestroy(string text, float duration)
        {
            gameObject.SetActive(true); // in case the a renderer is using a disabled prefab in the scene for color customization etc
            Text.text = text;
            Text.color = StartColor;
            Vector2 newPos = new(transform.localPosition.x + NumberUtils.Next(MinX, MaxX), transform.localPosition.y + NumberUtils.Next(MinY, MaxY));
            Sequence seq = DOTween.Sequence();
            seq.Insert(0, transform.DOLocalMove(newPos, duration));
            seq.Insert(0, Text.DOColor(EndColor, duration));
            seq.AppendCallback(() => Destroy(gameObject));
            seq.Play();
        }
    }

NumberUtils.Next() just gets a random float between min/max, so you'll have to replace that with however you get randoms

#

(I feed all my calls through my own numberutils for seeding/testing reasons)

#

oh also, change BetterMonoBehaviour to MonoBehaviour.. i have my own stuff in there

regal olive
misty glade
#

heh, yeah

regal olive
#

thanks 🙂 il have a look

misty glade
#

i overrode Destroy() because I wanted it to fail if I used it on a component instead of a gameobject (I never destroy components, so if I do, it's a bug)

regal olive
misty glade
#

No, because I just .. don't really assemble my gameobjects at runtime, so I don't use Destroy that way

#

if I call Destroy on something, I want it to kill the GO, not the component

regal olive
#

oooh didnt see "is not GO

misty glade
#

like this would be a bug for me:

private HitText MyHitText;


private void SomeMethod()
{
  Destroy(MyHitText); // doesn't actually destroy the GO - just removes the component from the GO
}
#

with my code, the above will throw an assertion failure

regal olive
#

well good thing u can do stuff like that to customize it for urself, i honestly always test everything even if i just added a new particle system so i know if something is wrong

austere jewel
#

It'd probably be better to make an analyser that detects this instead of having a method and required inheritance

misty glade
#

Hm, that's an idea. I've never written my own analyzer. Good evening project, I think.

austere jewel
#

Neither have I, it seems like a good usecase though

misty glade
#

I also have some other stuff in that class.. extension method DestroyAllChildren() too since it's something I do often-ish

austere jewel
#

You can move that stuff to actual extension methods or static methods

misty glade
#

oh, fair.. I actually don't think I have anything else (anymore) in my MonoBehaviour so if I wrote an analyzer for the Destroy() thing and then moved all the extension methods just to MonoBehaviour I'd be done

austere jewel
#

Imo it'd make sense for DestroyAllChildren to be an extension of Transform, and the All is probably redundant

misty glade
#

hm, perhaps.. I tend to not think of a transform as separate from a GO though.. like, to me, the GO is "the thing".. I don't think of children as properties of the GO's transform, if that makes sense? It's just my own mental model

#

I mean, my code knows 😛

#
        public static void DestroyAllChildren(this GameObject gameObject)
        {
            if (gameObject == null) return;
            for (int i = gameObject.transform.childCount - 1; i >= 0; i--)
            {
                UnityEngine.Object.Destroy(gameObject.transform.GetChild(i).gameObject);
            }
        }
#

probably not the best function since I imagine internally childCount needs to enumerate them

#

but I don't do anything with millions of GOs so my O(n^2) loop is insulated with the Power Of Small Data Sets

sleek terrace
#

reducing triangles count results in zero gains in FPS?

tiny pewter
#

unsafelist cannot use pointer as generic parameter but i realized that i can cast the pointer to ulong.... have anyone did this before? i wonder if it is safe

orchid marsh
tiny pewter
#

and i try to wrap the pointer into a struct, work...

untold moth
sly grove
sage radish
random spruce
#

I have an AnimationCurve variable on a ScriptableObject exposed to the inspector, once I edit it in the inspector, how do I copy the values as code? I can only get them in a JSON format. Any help is appreciated thanks!

upbeat path
random spruce
# upbeat path What are you trying to do exactly?

Once I define a AnimationCurve variable in a script, I edit it in the inspector using the graph editor. What I want to do is be able to copy the values of the graph as code so that I can define it graph in the script itself.

public AnimationCurve curve = new AnimationCurve(the curve value that I can paste as C# code in the script);

upbeat path
#

what do you mean by 'as code' an Animation Curve is data not code

random spruce
# upbeat path what do you mean by 'as code' an Animation Curve is data not code

by code I mean data essentially that is compatible with the c# script. For example if I define a vector2 and edit it in the inspector and I right click the variable and copy, I get this

Vector2(0,0.660000026)

I can paste this directly into the code for the variable value and it works (with a few modifications)
public Vector2 vec2 = new Vector2(0,0.660000026);

the AnimationCurve is copied as JSON data which I doubt can be used to set the variable's value

AnimationCurve JSON data below

UnityEditor.AnimationCurveWrapperJSON:{"curve":{"serializedVersion":"2","m_Curve":[{"serializedVersion":"3","time":0.0,"value":0.0,"inSlope":34.68950653076172,"outSlope":34.68950653076172,"tangentMode":0,"weightedMode":0,"inWeight":0.0,"outWeight":0.031713906675577167},{"serializedVersion":"3","time":0.105804443359375,"value":1.0,"inSlope":0.8033333420753479,"outSlope":0.8033333420753479,"tangentMode":0,"weightedMode":0,"inWeight":0.08614794164896012,"outWeight":0.0}],"m_PreInfinity":2,"m_PostInfinity":2,"m_RotationOrder":4}}
upbeat path
upbeat path
#

still not sure why you need this. The AnimationCurve is in your SO so just reference or copy it from there

random spruce
#

I need to hard code it into the script because the AnimationCurve value is not retained when copying to new projects (or publishing as a draft in publisher portal as an asset)

upbeat path
random spruce
upbeat path
#

make a SO with a public KeyFrame[] and copy the keyframes from your animationcurve into it

tiny pewter
#

if DoSomething have to read the z property of the void*, i have three options to do this:

  1. cast the someStrust pointer to (int*)(someStruct+(k<<2)), fastest way but no one use it since you have to guarantee the z property must at fieldoffset k<<2
  2. declare interface and change the DoSomething into DoSomething<T>where T: someInterface
  3. pass copy z to it but not work if the function will write the z property.
    obviously 2 is an easier way to this but i hate function call just for few lines of code (getter setter are function calls to only one line of code in this case), though AggressiveInling can prevent it but you cant guarantee the compiler must inline the code.
scenic forge
#

You can just do (*(A*)someStruct).z, no?

tiny pewter
#

yes, i miss it, thank

#

though it internally is same as one

scenic forge
#

Yeah, but you don't need to deal with field offset.

sleek terrace
#

I had a friend pull this off

#

why cant I?

obsidian coyote
#

Looks like all ur time is currently being spent rendering, based on the screens shot I can't tell really what your rendering, but there is likely a more performant way, like gpu instances, or merging static meshes, etc.

sleek terrace
#

im using Graphics.rendermesh

obsidian coyote
sleek terrace
#

they are all going to be different

obsidian coyote
#

You can get really fancy ans provided what your trying to render works with it, using a compute shader then a custom material that renders the output buffer of it directly can be insanely fast, like I'm taking 10,000,000+ particles in real time, or creating huge marching cubes rendered scenes at 500+ fps, etc. But that solution won't work for all usecases

#

If they are all different you may need to look into other performance fixes like culling if possible, or using more basic shaders

sleek terrace
#

I have the most basic shader atm

#

its a simple color shader

#

😦

obsidian coyote
#

What are you rendering?

sleek terrace
#

just hexes

#

500 x 500

#

I have tried combining them

#

used gpu instancing

#

etc

obsidian coyote
#

Are they all on a flat plane?

sleek terrace
#

for now yes

obsidian coyote
#

Creating a tile able hexagon texture then using a texture that packs the type of hex into rgb channels or something would probably render really fast. Depending on how many unique materials your using, you could probably render it this way quite efficiently

sleek terrace
#

huh

obsidian coyote
#

If each hexagon is of some type, like for example if it's being used for terrain, u could make a sprite sheet with each type of material in a square, grass, lava, rock,etc like how minwcraft does it, then just have each hex color point to the material in the sprite sheet

sleek terrace
#

hmmm

#

so is the bottleneck caused by my material?

#

or rendering

obsidian coyote
#

Well it seeing caused by rendering in the profiler graph you showed, like 90% of the frame time was rendering

sleek terrace
obsidian coyote
#

Oh in this graph ur rendering is only like 10% of the frame time

#

Looks currently cpu bound based in a higher cpu time than gpu time

sleek terrace
#

Here is the only code running

#

I cant multithread* render jobs

obsidian coyote
#

If you reduce the hex count until you can render at around 100 fps, then turn on deep profiling it'll give you a better breakdown as to where your cpu is spending its time. The reason for first reducing the hex count is that deep profiling is very taxing and causes everything to run really slow, and if your already at 30 fps, if will be super slow and not very usable

sleek terrace
#

ok

#

Very few scripts being ran

#

mostly just editor loops

sleek terrace
obsidian coyote
#

Tbh in that video I didn't know what I was looking at, but if it's cpu bound, doesn't matter what your drawing you can still have low fps

brisk spruce
# random spruce I need to hard code it into the script because the AnimationCurve value is not r...

that json should work, specifically that array you copied inside, this part

[{"serializedVersion":"3","time":0.0,"value":0.0,"inSlope":34.68950653076172,"outSlope":34.68950653076172,"tangentMode":0,"weightedMode":0,"inWeight":0.0,"outWeight":0.031713906675577167},{"serializedVersion":"3","time":0.105804443359375,"value":1.0,"inSlope":0.8033333420753479,"outSlope":0.8033333420753479,"tangentMode":0,"weightedMode":0,"inWeight":0.08614794164896012,"outWeight":0.0}]

Should be able to serialize that, I think, to an array of KeyFrames, but Im not sure if Keyframe has a paramaterless constructor

sleek terrace
obsidian coyote
# sleek terrace that was a 500 x 500 hex being rendered, its just zoomed out

Oh gotcha, one easy tweak would be to render the hexes to a render texture, then just render it as a cheap set of quads. You could update the render texture if one of the hexes within it changes, and to support an infinity sized world, you could recycle the render textures so you only keep a handful of them allocated, and as the hex grid pans off the edge of the screen use that same texture for the hexagons coming onto the other side of the screen, etc.

#

Rendering every single hex every single frame even with gpu instances, etc sounds sub optimal if they can easily be represented by a much easier to render method like a render texture

sleek terrace
#

Ok

sly grove
sly grove
#

Look into Graphics.DrawMeshInstanced / Indirect

sleek terrace
brisk spruce
#

So I have a large pseudo INotifyPropertyChanged class implemented, its actually multiple classes nested in a tree. These represent my game state.

And example of one of their properties looks like this:

private int _roundCount;
public int RoundCount
{
    get => _roundCount;
    set => Mutate(ref _roundCount, value);
}

the Mutate method both sets the value of the backing field and automatically fires off the PropertyChanged event that is being listed to be subscribers.

Current challenge: I want to be able to deserialize saved game data to this class. Aside from having to manually go through and write a bunch of code that sets every single property, what other options do I have? Roslyn Postprocessor perhaps?

I havent chosen what I want to serialize to yet, could be protobuf, json, or a sqlite DB locally saved, its not important.

The big challenge is I need to "load" all that data into this game state, but then I still need to actually fire off all of those "PropertyChanged" events so all of my listeners will actually load the data

#

One thing I have considered is, perhaps, adding 1 additional event that everyone can hook into that is an overarching "total reload" event, and all the subscribers know to just do a total reload with their respective methods when that one fires off

#

Just as an example of one of my services, this is how my subscribers function atm:

public void Initialize()
{
    BindGamestate();
    RedrawActionButtons();
}

private void BindGamestate()
{
    GameState.BindTo(s => s.RoundCount, OnRoundCount);
    GameState.BindTo(s => s.UI, RedrawActionButtons);
    GameState.BindTo(s => s.Abilities, RedrawActionButtons);
    
    GameState.BindTo(s => s.SceneState, ClearHighlights);
    GameState.BindTo(s => s.UI.SelectedAbility, RedrawPlayerHighlights);
    GameState.BindTo(s => s.UI.HoveredAbility, RedrawPlayerHighlights);
    GameState.BindTo(s => s.UI.SelectedTile, RedrawPlayerHighlights);
    GameState.BindTo(s => s.UI.Submitting, RedrawPlayerHighlights);
}
#

I could perhaps add one more listener thats along the lines of simply

GameState.Reloaded += OnGameStateReload;

Which will call both RedrawActionButtons and RedrawPlayerHighlights, as an example

scenic forge
#

My game has a different reactivity system, which is modeled closely after Vue’s. Perhaps you can find some idea from it.

#

The atomic unit of reactivity is Dep<T> and T could be anything, an int, a Texture2D, a GameState, whatever. It doesn’t need to implement any special interface or anything.

brisk spruce
#

That part is fine, the reactivity works.

Issue us when I load data from file, applying the model to the viewmodel and triggering all the "property changed" triggers

scenic forge
#

A Dep<T> could be watched (when the value changes, notify subscribers), could be derived into another Dep<T>.
A level above is Ref<T>, which allows you to change the value, and causes Dep<T> to notify all the subscribers.

jolly token
#

Make your deserializer use property setters 😄

scenic forge
#

So for game state, it would be managed like this:

private Ref<GameState> _state = …;
public Dep<GameState> State => _state;

(So that outside cannot mutate the game state, only this class can)
And if an exp bar UI for example, only cares about the exp, they could write:

Game.State
    .Computed(state => state.exp)
    .Watch(exp =>
    {
        // Exp changed, do something
    });
#

Here’s the critical difference between this reactivity system versus yours: data owner does not determine what events exist and when they need to be raised, all data owner does is just changing the value.
Subscribers decide what part of the data they care about and derive new Dep<T> to represent it, and watch it.

#

This means your original problem doesn’t even exist in this reactivity system: the game will deserialize the entire game state at once without triggering any subscribers, and just set it:

var newState = LoadGameSave(…);
_state.Set(newState);

At the point of setting the new state, exp bar will be notified if exp changed, and nothing if not. Your subscribers will never run into issues such as “game state is in a partially deserialized state and contains illegal conflicting information.”

#

(This reactivity system is also nice that there’s zero boilerplate writing all the property change events)

brisk spruce
scenic forge
#

Because Dep<T> keeps track of a list of subscribers, when you write:

Game.State.Watch(state => …);

That lambda is added to the subscriber list. And when state is changed:

_state.Set(newState);

It runs all the subscribed lambdas.

gaunt whale
#

does anyone know any good videos to learn how to code and do stuff on unity

#

it doesnt have to be videos

#

but i prefere them

vast shale
#

What's the norm when people are using addressables but wanting to do non-async loads and instantiations? Would it be OK practice to for example load a prefab via addressables that has a bunch of serialised asset references (e.g. EnemyAssets.prefab) and using that reference doing regular:
EnemyTypeA = Instantiate<EnemyTypeA>(EnemyAssets.TypeA);
?

Trying to update my oldschool Resources.Load habits (not that they don't work fine in small games), but doing every tiny non directly serialized instantiation via an async workflow seems crazy.

scenic forge
# scenic forge So for game state, it would be managed like this: ```cs private Ref<GameState> _...

This reactivity system isn’t just limited to managing game state either, you can very well make one single dep for managing the game time:

private Ref<float> _time = new();
public Dep<float> Time => _time;

private void Update()
{
    _time.Set(UnityEngine.Time.time);
}

And everywhere else that needs to update every frame can just watch this and use it to drive logic. In fact, those code don’t even need to know they are in a Unity game, all they need is just the Dep<float>.

#

If you wan something to happen only once per two seconds?

Game.Time
    .Computed(t => (int)(t / 2))
    .Watch(() =>
    {
        // Triggers once per two seconds
    });
grave jackal
#

Hello everyone, I am creating a weapons system for an fps game that I am making, my idea is to create a weapon stats tool that allows generating a recoil with a curve, I have solved that part a bit, but I have a specific question It's that I want to be able to make the weapon move with code and not with animations, I want that when configuring a curve the weapon moves forwards and backwards depending on the curve settings, that's possible, I'm not saying give me the code , only if you have any information that can help me that would be great.

dusty wigeon
#

What is your current issue ?* Why can you not implement it ?

old harness
#

is there some who can help me

grave jackal
grave jackal
# dusty wigeon Yes.

Do you have any information, guide or video that can help give me an idea of where to start?

dusty wigeon
#

Why arent you able to simply "code" the recoil ?

#

Ideally, you would use Inverse Kinematic to make your gun. The recoil can simply be a change on the target of the IK.

grave jackal
dusty wigeon
#

You could even not use IK, and simply code the offset of the trajectory.

dusty wigeon
dusty wigeon
grave jackal
brisk spruce
#

I also have the issue where I can have multiple of the same method subscribed to various property changes, as it depends on many of them.

IE:

GameState.BindTo(s => s.UI.SelectedAbility, RedrawPlayerHighlights);
GameState.BindTo(s => s.UI.HoveredAbility, RedrawPlayerHighlights);
GameState.BindTo(s => s.UI.SelectedTile, RedrawPlayerHighlights);
GameState.BindTo(s => s.UI.Submitting, RedrawPlayerHighlights);

This would call RedrawPlayerHighlights four times if I just blindly fired off every lambda repeatedly D:

scenic forge
#

🤔 Not sure that’s the issue, my watch has 4 overloads, one takes a plain action, one takes an action with one parameter of current value, one with current and old value, and last one with both values + a bool indicating whether it’s first invocation or not.

#

For your second issue though, in mine I just make a new computed that just returns a tuple of those 4 values, and watch that so it’s only triggered once.

#

But really, your reactivity system is equivalent to mine just with different code organization.

#

I believe the core issue is that your game state being split up into multiple properties even though those properties are inherently linked together, causes subscribers to run at times when your game state is only half way updated and in an invalid state.

sly grove
brisk spruce
#

@scenic forge So I think for now though my plan is to just have 1 extra simple event that can be subscribed to, that is simply "Game Loaded", and leave it up to the consumers to handle what to do when that occurs.

scenic forge
#

Yeah, that’s effectively bundling the entire game state as one reactive unit.

wary blaze
#

I don't know if this is the right place for this, but looking through the channels I don't anywhere else.

I am simply trying to diagnose a startup crash in a built project (Windows). I have enabled a dev build with PDB files and script debugging, and set the application to wait for me to attach the debugger. I am using Visual Studio for the debugging environment.

Attaching the Unity Debugger to the process is simply not working. I can see the application and attach the debugger, but once I press OK on the popup asking me to attach a debugger, the game simply crashes as normal and the debugger detatches itself.

I know that a breakpoint exist in Unity's code because I can use Visual Studios Attach to Process option and it picks up the breakpoint. However, with this I don't get any useful information from the call stack such as local values or parameter values. I was hoping using the Unity Debugger would rectify this issue (but maybe I am mistaken).

Here is a link to a video showing the issue.

https://youtu.be/nsXYlzyazgw

sleek terrace
# sly grove You said they were hexes

I should have been more clear,
The hexes are made of meshes, then they are combined into chunks ...sometimes 100 x 100
then these chunks are rendered

tender ingot
#

Just an update to my enquiry few days ago about adding something to my game to allow me to add 500+ zombie prefabs to my game with smooth fps in WebGL.

I was able to do so and runs a good 60fps + 😀.

untold moth
wary blaze
untold moth
wary blaze
# untold moth It could be due to optimizations or the code you're inspecting not having proper...

Okay, so here's a little video showing what I'm doing. First, you can see the Symbol Paths I've defined in Visual Studio. Perhaps I've done something wrong here, however the module that all of the methods in the call stack are from (UnityPlayer.dll) has symbols loaded (can be seen towards the end of the video). I added the other folders where some of the PDB files for third party DLLs and other DLLs are stored, but I don't know if I did this wrong. As far as I can tell, the debugger never loads these modules, like they aren't needed (maybe the crash is happening before they are needed?).

With the methods in the call stack there's not much I can do. It seems like this might be a serialization issue but I don't know what field from what class is causing issues. I would expect to be able to find that somewhere in the call stack. I'm very new to debugging however and fully expect I am doing something wrong or missing something.

https://youtu.be/t-WZXm4swUM

It's pretty late where I am, so I look forward to seeing what you think in the morning. Thanks so much for the help!

#

Posted the above and then realized I need to double click the call stack methods to see the names and values of the parameters . . . still, the values I see don't seem to make much sense.

untold moth
wary blaze
#

Hmm, okay, that makes sense.

#

The log files just says the scene is corrupted. I was hoping to get more information about what is actually corrupted using the debugger.

untold moth
#

Does it open in the editor?

wary blaze
#

Yes

untold moth
#

Were there any errors during the build?

#

Perhaps just rebuilding the game would fix it.🤔

wary blaze
#

Unfornately I've done several rebuilds. There are three errors during the build but they don't provide much information, and the build always succeeds still. I'll re-do the build so I can see what those errrors are again.

wary blaze
#

Assertion failed on expression: 's.buildTarget.platform >= kFirstValidStandaloneTarget'

untold moth
#

Any more details to the error?

wary blaze
#

no, but I did notice that the error occurs 30 times

#

it's called from UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

untold moth
#

What's the actual stack trace?

wary blaze
#

it only shows in the Editor Log, not the console, but it's:

#

Assertion failed on expression: 'buildTarget.platform >= kFirstValidStandaloneTarget'
UnityEngine.StackTraceUtility:ExtractStackTrace ()
UnityEditor.BuildPlayerWindow/DefaultBuildMethods:BuildPlayer (UnityEditor.BuildPlayerOptions)
UnityEditor.BuildPlayerWindow:CallBuildMethods (bool,UnityEditor.BuildOptions)
UnityEditor.BuildPlayerWindow:GUIBuildButtons (UnityEditor.Modules.IBuildWindowExtension,bool,bool,bool,UnityEditor.Build.BuildPlatform,UnityEditor.Modules.IBuildPostprocessor)
UnityEditor.BuildPlayerWindow:ShowBuildTargetSettings ()
UnityEditor.BuildPlayerWindow:OnGUI ()
UnityEditor.HostView:InvokeOnGUI (UnityEngine.Rect)
UnityEditor.DockArea:DrawView (UnityEngine.Rect)
UnityEditor.DockArea:OldOnGUI ()

#

UnityEngine.UIElements.IMGUIContainer:DoOnGUI (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect,bool,UnityEngine.Rect,System.Action,bool)
UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,UnityEngine.Matrix4x4,UnityEngine.Rect,System.Action,bool)
UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,System.Action,bool)
UnityEngine.UIElements.IMGUIContainer:HandleIMGUIEvent (UnityEngine.Event,bool)
UnityEngine.UIElements.IMGUIContainer:SendEventToIMGUIRaw (UnityEngine.UIElements.EventBase,bool,bool)
UnityEngine.UIElements.IMGUIContainer:SendEventToIMGUI (UnityEngine.UIElements.EventBase,bool,bool)
UnityEngine.UIElements.IMGUIContainer:HandleEvent (UnityEngine.UIElements.EventBase)
UnityEngine.UIElements.CallbackEventHandler:HandleEventAtTargetPhase (UnityEngine.UIElements.EventBase)
UnityEngine.UIElements.MouseCaptureDispatchingStrategy:DispatchEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel)
UnityEngine.UIElements.EventDispatcher:ApplyDispatchingStrategies (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel,bool)
UnityEngine.UIElements.EventDispatcher:ProcessEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel)
UnityEngine.UIElements.EventDispatcher:ProcessEventQueue ()
UnityEngine.UIElements.EventDispatcher:OpenGate ()
UnityEngine.UIElements.EventDispatcherGate:Dispose ()

#

UnityEngine.UIElements.EventDispatcher:ProcessEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel)
UnityEngine.UIElements.EventDispatcher:Dispatch (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.IPanel,UnityEngine.UIElements.DispatchMode)
UnityEngine.UIElements.BaseVisualElementPanel:SendEvent (UnityEngine.UIElements.EventBase,UnityEngine.UIElements.DispatchMode)
UnityEngine.UIElements.UIElementsUtility:DoDispatch (UnityEngine.UIElements.BaseVisualElementPanel)
UnityEngine.UIElements.UIElementsUtility:UnityEngine.UIElements.IUIElementsUtility.ProcessEvent (int,intptr,bool&)
UnityEngine.UIElements.UIEventRegistration:ProcessEvent (int,intptr)
UnityEngine.UIElements.UIEventRegistration/<>c:<.cctor>b__1_2 (int,intptr)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

untold moth
#

weird. Try deleting the library folder and rebuilding. Perhaps there's some corrupted cache.

wary blaze
#

I tried that once before and it didn't work, but will try again. I think the project might be corrupted. At some points I am able to do builds, then I'll change a single script, rebuild, and it starts crashing again.

#

I appreciate the help.

#

I've got some other avenues to check; I was mainly trying to figure out the debugging stuff to figure out what I was doing wrong.

#

Now I know debugging is probably not the best avenue to approach this particular problem. That's appreciated!! Night!

dusty wigeon
wooden cedar
#

What it thinks, for some reason, is that the platform you are building for is invalid

#

If I'm reading that log right

misty glade
misty glade
bronze lark
#

Question: If I multiply a vector with the Camera View Matrix (eitherprojectionMatrix * worldToLocalMatrix or worldToCameraMatrix), what is in w of the resulting vector? I'm getting weird values. I thought it was negative depth into the screen, but I get positive and negative values, all strewn about. It feels like clip space, but I'm not sure.

#

I see examples dividing by w, I need to divide by -w to get viewport coordinates that make sense.

#

Huh, an example uses _camera.projectionMatrix * _camera.worldToCameraMatrix , that's weird.

sly grove
tawdry crypt
#

I'm not sure if this qualifies as advanced but I haven't been able to find anything online, in beginner, general, or the input system. I'm trying to get local coop to work with 2 xbox controllers specifically. I have each controller moving their respective player but only one controller is able to send input at a time. So if I hold fire on both controllers only the one that was pressed first will work. Any idea of there's a setting or something that needs to be done to be able to accept the input from both controllers simultaneously?

sly grove
tawdry crypt
#

when I tried using that before I wasn't able to find a way to get 2 gamepads working with it. I'll try to look through the docs again

sly grove
#

the types of input devices don't really matter

tawdry crypt
#

before I did all this and was using the input manager it each gamepad would just move both players. I could get that to stop if I used like the keyboard and 1 gamepad @sly grove

sly grove
tawdry crypt
sly grove
tawdry crypt
#

cool point me in the direction of some good info then because I've tried looking through the docs and following a few different tutoorials and have had 0 success

#

this is the closest i've come to it

sly grove
#

the second player shouldn't even exist until you press a button on the second device or explcitly joined them based on your code

tawdry crypt
#

yeah that's what happens

sly grove
#

did you set up your control schemes

tawdry crypt
#

same as if I were to spawn it with the start button using the input manager

#

when I was using the input mananger yes

sly grove
#

If you're writing Gamepad.current, that's not using the system properly

tawdry crypt
#

okay this is what I did after I stopped using the input manger

sly grove
#

you'd have to show what you did before

tawdry crypt
#

lol ok

bronze lark
# sly grove What kind of vector are you multiplying? multiplying two matrices together "comp...

World Space vector, want screen space position in normalized device coordinates [-1..1], at a time where I can't call managed code. I almost got it, but if the item is somewhat close to the camera (still about 2.5-5 units away from the near plane), I seem to get unexpected values for w (flips to negative early)
I'm aware of how matrices / affine mappings work, just... not exactly sure about what Unity keeps in these matrices. (and difficult to read apart from the trivial cases)

sly grove
bronze lark
# sly grove There is no `w` for a world space position vector. It should be a Vector3

You need to make it a float4/Vector4, you can't multiply a Vector3 with a 4x4 matrix. You feed in a Vector4 (set the last component to 1), then, you get a Vector4 back, where the w is normally known as the perspective correction; to get normalized coords, you divide by w. (only usually makes sense if one of the matrices is a projection matrix)

bronze lark
#

Manual says it should be negative, OpenGL style. It's only negative if I use the first matrix concatenation I gave, but not the newest one (which I took from another example - gives me nicer, positive values, based allegedly on Unity's internal code - but w still flips)

#

Positive or negative DX/OpenGL aside, I always thought w=0 means object is at the camera position.

#

Now I'm not so sure 😄

bronze lark
#

That doesn't work though, I have a 4x4 matrix. View matrix is always 4x4 i believe, and you can't leave a column or row off. 🙂

sly grove
#

that's literally the docs for Matrix4x4?

bronze lark
#

Ah, I see. I can't call these, either - I have a float4x4, would love to see what they do. I'm sure they just append the w=1.

I can try to load a Matrix4x4

bronze lark
#

My decompiler said it was injected and I thought that meant it was in the C++ code.

#

Thanks, you're the MVP 🙂

#

Interestinggg. I think that's the same thing.

#

Oh, it's not. I should write down the 4*4x4 formula...

#

I think then "w" would be what w is here... + 1

dusty wigeon
bronze lark
wary blaze
dawn kettle
#

Alright. I have a very specific inventory system I want to create so if anyone is willing to do some one on one assistance with me I would be very grateful. DM me if you are willing to help.

austere jewel
golden mist
#

hey, anyone know of any issues with C# boolean functions not playing nice with arrays>

#

im trying to play with some arrays inside of a bool function and im consistently getting null object exceptions when simply trying to access arrays that are working elsewhere in the script

#

im running this in an if function: itemModifier[0] != null

brisk pasture
#

you will need to show a example

#

also this is not really a advanced thing

golden mist
#

and getting an out of bounds exception from that

brisk pasture
#

which makes sense

#

what if the array is empty

#

0 would be out of bounds

golden mist
#

lol its not

#

I agree that under normal circumstances it wouldnt be but at this point im wondering if this isnt something deeper which is why its in here

#

Ive looked around the entire internet and ive found nothing.

brisk pasture
#

its going to be a simple error

#

would just show the logic

golden mist
#

probably lol

#

okay never mind Ig

brisk spruce
#

Anyone here familiar with building unity projects using a docker image for CI/CD use case? Have a docker image they would recommend using?

Mostly for building targetting android

brisk spruce
spark tartan
#

Hey, I'm working on a Unity plugin and during the import process we add a scripting define symbol using
PlayerSettings.SetScriptingDefineSymbolsForGroup()
https://docs.unity3d.com/Manual/CustomScriptingSymbols.html
However, it seems that Unity/scripts don't recognize the define symbol until you close and reopen the editor. As a result some scripts don't work until you restart the editor.

I have tried a few things to trigger recompilation such as:
CompilationPipeline.RequestScriptCompilation();

Any ideas on how to approach fixing this?

devout coyote
brisk spruce
# devout coyote We use that as a base as well

thanks, I have discovered that unity doesnt have an ARM64 version of their editor, so its gonna be a bit more of a pain for me to get it working with my kubernetes cluster build pipeline, smh

pulsar crane
#

Hello everyone.

I want to add a "hook" before an attack to get the damage, as in, for example:

Attack comand -> GetDamage(from the player stats) -> run the hook passing the currentDamage (for things like damage amplifiers) -> execute the attack.

Right now I've set up a List of actions that ake in the information of the attack (Basically the currentDamage and if it's a crit):

public List<Action<float, bool>> beforeAttackHooks = new List<Action<float, bool>>();

Where if something needs to modify the attack damage it will basically add the modifying function in this action list.
Then, in the GetDamage function i run through all the actions:

bool isCrit = IsCrit();
        float damage = characterStats.atackDamage.Value;

        foreach(Action<float, bool> action in beforeAttackHooks)
        {
            damage = action(damage, isCrit);
        }

My issue is that I can't seem to find any way to define these actions as floats intead of voids. Any ideas on how to make this work? I'm open to hear about enterily new aproaches, since I'm bringing the concept of hooks from web development and I'm not sure it's the best method to apply here.

brisk spruce
#

You probably want Func<float, bool, float> looks like

#

Action is specifically a void, Func is the one that has a return value 🙂

pulsar crane
#

Oh man I feel so dumb xdd thank you

trim aspen
#

What is this?

pulsar crane
#

my guess is that the AddForce function asks for a ForceMode and not a ForceMode2D

trim aspen
#

but it is a 2d game

flint sage
#

But you're using a 3d rigidbody

trim aspen
#

no

flint sage
#

Yes?

trim aspen
#

my game is a 2d game and i am using rigidbody2d

flint sage
#

If it was then you wouldn't get this error

trim aspen
#

oooooooooooh

#

thank you very much

pulsar crane
#

hahaha

pulsar crane
prime mist
real blaze
# pulsar crane Btw, for anyone that might have a similar issue or will in the futrure. The obio...

right 👍 events are great for this. very neat and intuitive. it does come with a problem however, and that is the ordering of the executing subsriptions. a

A += i => i * 2;
A += i => i + 1;

yields a different result than

A += i => i + 1;
A += i => i * 2;

so we'd need to implement some ordering ourselves if we want to have fine control over it

  • also beware that if you pass an event itself as a subscription, (A += a;), you're subscribing a copy of a. so, further modification to a will no longer account for A. you can however pass a true reference of a by doing A += i => a(i)
tall ferry
gray frigate
#

Heya folks, here's a doozy I just hit in my game.

The setup:
The save system for my game consists of creating a json-formatted string, salting it, converting it to bytes with Encoding.UTF8.GetBytes(), converting it again with Convert.ToBase64String(), salting that string and saving it to a file. When the game loads, it unsalts, does Convert.FromBase64String(), does Encoding.UTF8.GetString(), unsalts again, and reads the json data.

The problem:
It appears that at some point in the loading process, Russian-language operating systems (this is reproducible on my own machine, even) have a problem and create a corrupted save. I have a couple ideas for how to further debug and may likely end up having to create some kind of sanitizer but I would like to know if anybody has thoughts on why this happens and a decent way of fixing it. Are there known issues with the functions I've mentioned and is there any way to set up Unity's Localization package to allow me to debug this without having to keep changing my Windows language back and forth.

real blaze
devout coyote
flint sage
#

It really is not, depending on your scale

devout coyote
#

I dont know the scale at which you are working at but for us where we work on a single game as a fairly small group it rarely happens that multiple builds are queued

flint sage
#

100+ people, multiple platforms, sometimes multiple platform configurations, tests, validation, probably more

devout coyote
#

Then it does not longer sound overkill

flint sage
#

All those can be in parallel

devout coyote
#

But I don't think it's fair to assume the majority of people asking questions about game-ci in this discord do that

flint sage
#

Possibly 😛

real blaze
#

well yeah but the OP mentioned it themselves

sage radish
flint sage
#

Also dockerized builds can be really useful to deal with all those native SDK versions

devout coyote
flint sage
#

I know

#

Just putting it out there

devout coyote
#

Bless, thought something got lost in translation somewhere x)

gray frigate
#

I can guarantee if the hashing was the issue, this problem would be happening in English too

sage radish
#

You're not hashing here though, just encoding

gray frigate
#

It's just a single alphanumeric being added at the start

#

er, I meant salting

flint sage
gray frigate
#

nah it corrupts the whole thing

#

but, again, pretend it's gone, I'll just let people figure it out

devout coyote
#

I dont think you should prevent single player cheating, you should maybe even encourage it

sage radish
#

I guess depending on the character, it might mess with the UTF-8 encoding. But the first salt before encoding to UTF-8 does nothing.

devout coyote
#

Some players might think your game is too difficult or harsh and they might make it a little bit easier on themselves

#

Or the progression is too slow for them

gray frigate
#

well I have a DLC that makes it easier

devout coyote
#

So they skip ahead

gray frigate
#

if they really want to hack they can just cheatengine

#

but people buy the DLC so why not

#

none of this is answering my question though

#

But if the only answers anyone has available are "get rid of the salt" then gosh darn I sure hope that's what solves the issue and it'll be the first thing I try tonight. I just really, really doubt it's the issue.

devout coyote
#

I suspect it has to do with the conversion from and to UTF-8

flint sage
#

I haven't really seen json serialization errors in the RU language, I guess it's possible but seems unlikely

devout coyote
#

as UTF-8 characters can be multiple bytes, so maybe it is messing up the conversion back to string values

flint sage
#

Also, specifying a locale wherever you can is useful

gray frigate
#

I have no localization in this game and don't plan on managing it either. I did try to specify the (ru) locale using the Localization package but it did not reproduce the bug.

devout coyote
#

But that would mean the built-in utf 8 encoder / decoder is broken.. That doesnt make sense either

gray frigate
#

I had to change my windows language to russian to get a repro to occur

devout coyote
#

Is it just russian? or other languages as well; uk/us english use different decimal points

gray frigate
#

I have yet to test other languages and the only person reporting this bug is russian

#

I would like to test other languages but if it requires changing my windows language to do so, that's a bit rough! Would really appreciate unity's localization package to do the work needed

devout coyote
#

Perhaps it is a keyboard layout issue and not a language issue?

gray frigate
#

That would be interesting since I don't pull input for any part of the save/load process

devout coyote
#

That doesnt matter

sage radish
gray frigate
#

Okay good to know, thanks!

devout coyote
#

just doing a float.toString() uses the computers locale to do so

#

which means either , or .

#

depending on language

flint sage
#

I doubt it's keyboard layout, it's probably locale which you can change for your app

#

That might get you to repro it without changing windows language

gray frigate
#

I will give that a shot right now, thank you!

sage radish
#

You need to step through the whole process in both locales and see at which point the string differs.

pulsar crane
# real blaze right 👍 events are great for this. very neat and intuitive. it does come with a...

For sure, I've already thought about this. I ended up creating a class called "Attack". Ended up using the Action<Attack> list for the hook and a BeforeAttack(Attack attack) for the delegate void of the attack.

Now if soe script wants to modify an atack before it's shot they can do thriough the Attack class, wich holds the info asweel as 2 methos: Damage from base, which does the damage modification, but allways parting from the base damage of the attack (hence eliminating the order problem) and the Damage from currrent, which is order sensitive, but I don't even think I'll even use.

Finally when the atack is actually shot it takes the damage stored in this class.

I'm a lil worried about memory alocaiton, since this class is usefull for exactly 1 fame, and never used or stored, is there a way to improve this?

gray frigate
#

@flint sage Thank you so much, that's exactly what I needed. Can now repro instantly.

devout coyote
gray frigate
#

After I solve the problem, I'll have to shove all the locales I can through this, that'll be fun...

flint sage
#

So since it's locale, it's probably your salt since I doubt the serializer breaks on RU

#

You might also want ot look whether youcan pass a locale to your serializer

#

And just pass the same to it so that it is consistent

gray frigate
#

Someone managed to reply to my forum thread with the suggestion I use myInt.ToString(CultureInfo.InvariantCulture) so now I've got something to try :)

#

Before I do anything I'm getting rid of the salt to see if that's really it hahaha

#

Had the dang thing since late 2000 it's so hard to believe it's taken this long for people to report issues

scenic forge
#

I always set the current culture to invariant

devout coyote
gray frigate
#

I never even knew this stuff existed until today

scenic forge
#

There have been too many games that run into issues with de/serializing because they don't do it, and the bugs typically manifest on cultures that use a different decimal separator than .

#

I've seen some high profile games getting hit by it.

gray frigate
#

Then I'm in good company haha

flint sage
#

That's generally only an issue if you write custom serialization/converters

#

Bigger libraries tend to handle it by default if you use their api correctly

devout coyote
#

Given you use their API correctly yeah

scenic forge
#

It might not be the de/serializing step directly before saving/after loading a save, all it takes is one float.TryParse without the appropriate culture and you can have a bug sneak in, but yeah.

gray frigate
#

Confirmed, it's not the salting causing the issue.

#

But I'll just keep it off anyway.

#

It appears changing the culture to invariant fixes the problem

#

So is there any reason I shouldn't just consider that the fix?

#

Force invariant on everyone?

sage radish
#

That would be the fix, but why are you encoding your own ints if you're using a JSON serializer?

gray frigate
#

So people can't look at their save file and immediately hack it

#

It doesn't take a lot of effort to hack but at least 1 step of obfuscation stops some subset of people

sage radish
#

So are you using a json serializer, or not?

gray frigate
#

and if you missed it: the game has iap/dlc for skipping ahead and people pay for it, so preventing some level of save file hacking is needed

#

yes, I am

real blaze
# pulsar crane For sure, I've already thought about this. I ended up creating a class called "A...

sounds nice. you can reuse the class to eliminate memory problem (maybe just add a Reset function), or make it a struct so it won't bother the garbage collector.

as for the algorithm itself, I think if all the expressions you'll use are multiplication and addition, then you can have like AttackBase, AttackAddition and AttackMultiplication, or even better, a new type just for this (so reusable for other buffs too)

public class BuffsCalculation
{
  float _base, _add, _multip;
  public void SetBase(float value) => _base = value;
  public void Add(float value) => _add += value;
  public void Multip(float value) => _multip *= value;
  public float GetResult() => (_base + _add) * _multip; 
  // or
  public float GetResult() => (_base * _multip) + _add;
}

and then instead of things subscribing to an event, they can just modify this right away. when they used to subscribe, they can Add(val), and when they used to unsubscribe, they can Add(-val)

#

(you can expand that to have like AddSpecialMultip etc for special expressions. like, in Witcher some skills indicate that they multiply over any previous calculations)

pulsar crane
#

Hmm, really smart, I'll give it a try. Even if i'm goiung to just refact all of it I'm having an issue with it now I'df like to understand.
For some reason, having changed nothing, unity is giving me a NullReferenceException: Object reference not set to an instance of an object error with it.

This is not all the code, but the relevant part. (I can add more if necessary):

The line giving the error is the event call one:

//Event devlaration
 public delegate void BeforeAttack(AutoAttack auto);
 public event BeforeAttack OnBeforeAttackFired;


//In the auto fire method
bool isCrit = IsCrit();
float damage = characterStats.atackDamage.Value;

AutoAttack auto = new AutoAttack(damage, isCrit);
//Line that's giving the issue. Where auto is the said class.
OnBeforeAttackFired(auto);

Is the issue the event, or is it most probably the parameter auto that's missing or something?

real blaze
#

even though OnBeforeAttackFired is not technically a field, it can still be null. it's always better if you do a nullcheck just in case

pulsar crane
#

how could it be null tho, it's clearly defined no?

real blaze
#

defined, but never been assigned anything. you can assign by subscribing something to it (OnBeforeAttackFired += someMethod)

pulsar crane
#

aaah, okay, nevermind, I did comment that code to test somthing else ahaha, thank you very much

real blaze
#

np ^-^ glad it's working

pulsar crane
#

I've refactored it so it is only 1 autoattack that other scripts can add and remove damage, but I have added an event for onHit events since more than 1 auto can be out at the same time, with sufficient attack speed xd

#

Thank you so muich for the help!

#

clear

#

HAHAHAHHA

#

NO WAY

#

I should take a break lel

junior stone
#

Hello! I've got a bit of a pickle, wondering if anyone has solved it in an elegant way

#

In unity 2021 I'm doing this during an SRP, because I need to check and do logic based on a mesh renderers shadowcasting flag
MeshRenderer[] meshRenderers = GameObject.FindObjectsOfType<MeshRenderer>();

#

This is kinda terrible. Is there a better way to keep track of all the mesh renderers in a scene (better still all the mesh renderers visible to a camera) so I can avoid the FindObjectsOfType?

sage radish
junior stone
#

The unity documentation suggests creating a singleton instead of FindObjectsOfType, but I don't control the lifecycle on them (gameplay people do gameplay stuff)

junior stone
sage radish
#

Yes, it's either FindObjectsOfType or putting your own component on all the renderers to keep track of them.

junior stone
#

Okiedokie. SRP is nice but it feels oddly limited in some ways

#

eg: Im having to do some hairy layer shenanigans to render out my own shadowmaps

sage radish
junior stone
#

Yeah, it relies on the magic "make me a shadowmap" API

#

which unfortunately doesnt suit my needs

#

s'ok though, thankyou for confirming for me

plucky trellis
junior stone
#

Yah, my issue is I'm using my own lights and light class, so I can't call context.DrawShadows(), it has to be a regular rendering pass

#

so that means setting up my own culling and filtering

#

oh well, it's not too bad, I've followed MentallyStables suggestion of looping over an attached component instead

plucky trellis
junior stone
#

I have one of those, but I didnt think I could use CreateShadowRendererList because I am not using any lights in my scene

#

SRP seems to have this concept of lightIndex integers. I might have to create proxy light objects so I can use that functionality.

#

too much for me to tackle right at this moment ^_^

plucky trellis
#

As far as I can tell, the lightindex integer is nothing more than an index for CullingResults . That means you should be able to fabricate both the array it's referring to, and the index yourself without problems.

junior stone
#

oh! is that so hmm...

junior stone
#

Ah, no, I dont think that can work, because the cullingResults comes back from my shadow casting camera. It has a NativeArray of lights, which I can't call ResizeArray on, nor can I just set it to a new array.

#

ah well >_<' I guess if I wanted to go that route I could make a proxy light object, but I'm okay using renderingLayerMask shenanigans for now to remove the non shadow casters from the shadow rendering. (and material shader passes too)

#

the real issue was walking the whole scene every frame to map the cast shadows flags to renderingLayerMask flags, but thats been eliminated now

brisk spruce
#

kubernetes is one of those things that is a decent bit of work to get up and running, but once it is running its super easy to add more stuff to it to run. If it has a docker image its usually just a couple minutes of effort to toss it onto the cluster and stand it up

#

so yeh, Im gonna take a crack at it and see if its possible for me to easily or not get a simple minimalist unity build server image to work, that just compiles the unity project APK and spits it out into an artifacts folder, which is conveniently also the folder a seperate FDroid server will be hosting so I can just click the update button on my phone to pull the latest install as I need

devout coyote
#

Why am I not surprised 😄

desert grove
#

is it possible to change the texture between two points on an object?

#

so I'm trying to make a kind of torch where the area in between the rays that form the cone of light has another texture to the rest of the object

#

how could I go about doing this? would appreciate any help 😊

sly grove
desert grove
sly grove
# desert grove could you elaborate on this a little? really appreciate your reply!

Start you SKILLSHARE Free Trial Today:
https://fxo.co/Dblx

3d modeling & animation is all fun and games till you realize that you have to though a process called Uv unwrapping, I don’t think that a lot of 3d artists like it but it has to be done for the most part.


Visit our Website:
https://inspirationtuts.com/

in...

▶ Play video
#

this really isn't a code question btw

desert grove
#

oh ok sorry about that then

dusty wigeon
#

It might also be something else then building.

heavy salmon
#

how can I make the input return like a full 360 degree angle? because this returns 8 directions only (1,0,0), (1,.0,1), etc.

dusty wigeon
heavy salmon
dusty wigeon
#

You are using a keyboad arent you ?

heavy salmon
#

I'm using a ps4 controller

#

forgot to mention this

dusty wigeon
#

Then, I do not know. You better look at resource for the input system directly.

brisk pasture
#

is there some sort of processor on the action

#

also would it not be a Vector2?

#

stick is only 2 axis

cerulean peak
#

Is there way to call internal static method of public struct of package from my code?

Unity.Physics.ConvexCollider.CreateInternal
thin mesa
#

no, internal means it can only be accessed from within the assembly the type is declared in

cerulean peak
#

what about reflection?

upbeat path
#

yes, you can do it with reflection

fast perch
# heavy salmon

possibly something to do with your Inputs, provide us with the full script that is attached to your Player

gray frigate
#

@flint sage I just thought you might like to know that the problems I had are all solved and the crux of the issue came down to a float.TryParse call on the application's version number (which sent the code off to act like the save was from an earlier version, aka had a different format) so in the end, it's float.Parse (or tryparse) that breaks when locale is different!

velvet rock
#

Hey all. I am trying to work with the Localization package for unity, but can't seem to find how to do it for the newest version.

public LocalizedStringTable localizedTextTable;

So i am assigning the table I setup, but can't figure out how to get a specific string, using the active locality of course.

#

Do I have to do GetTable() and then get an entry from that?

burnt hamlet
#

Is it possible to create a variable type similar to Vector2 but instead of position numbers lets you enter a string and an an int?

brisk minnow
#

alrighty so i got a weird problem i ran into.

even though i've set my texture2d to be readable, the sprite in the gameobject refuses to be readable.
im assuming the texture that it's using is elsewhere i cant see.

is there anyway i can change the sprite renderer's sprite to be readable while using code?

#

perhaps it's a duplicate in ram somewhere?

long ivy
#

my guess is it's in a sprite atlas

pulsar crane
pulsar crane
warm karma
#

Hi. Has anyone ever used a PID controller in Unity before please? Because I'm having a problem where I want to like lerp the value it outputs (so it feels like more smooth movement) but I don't know how to do it so the PID controller doesn't break and stops doing what it's supposed to do 😦

sage radish
warm karma
#

I don't give it back the smoothed position, I think that's the problem. Like, maybe explaining what it is for will make it more clear:

I have an aircraft with "realistic" physics (it rotates depending on the angle of the control surfaces and everything and not just by some simple torque applied), and I want it to like point towards a direction.

The values that the PID controller gets are the angles between the forward vector of the aircraft and the relative direction from the aircraft to the point I want it to look at, so that is something I can't smooth

#

The PID controller outputs the angles that the control surfaces have to be, so if I remove the lerping it kinda works fine, but once I add the lerping to smooth it out it stops working, and I'm guessing it's because the PID controller is guessing the control surfaces should be at for example 20 degrees when in reality they are at 10 degrees rotation because of the smoothing

#

I don't know if I'm explaining myself

sly grove
sly grove
warm karma
#

and how do I smooth it even more because they feel instantaneous?😅

sly grove
#

the control surface change is instantaneous but the aircraft's response to that is not, right?

warm karma
#

the control surface change shouldn't be instantaneous either, but the only way to make it work is if I set it to instantaneous (so remove the lerp/no smoothing)

sly grove
#

basically the PID controller needs to be reworked so it's aware of its limitations WRT how quickly the surface can be changed.

warm karma
#

and how can I do that please?😅

sly grove
#

right now your target variable is the orientation of the aircraft and the PID's input is the control surface angle.
You need to rework it so the target variable is the desired control surface angle and the input is the "voltage" it applies to change the surface angle. e.g. "tilt up/down" or whatever.

sly grove
#

It's not going to be super simple, it's kind of like - you're trying to achieve a certain thing but your input is two degrees of separation away from it

#

maybe it's just that you use two layers of PID controllers?

warm karma
#

This is basically the PID controller I'm using:

float AngleDifference(float a, float b)
    {
        return (a - b + 540) % 360 - 180;   //calculate modular difference, and remap to [-180, 180]
    }

    public float UpdateAngle(float dt, float currentAngle, float targetAngle)
    {
        if (dt <= 0) throw new ArgumentOutOfRangeException(nameof(dt));
        float error = AngleDifference(targetAngle, currentAngle);

        //calculate P term
        float P = proportionalGain * error;

        //calculate I term
        integrationStored = Mathf.Clamp(integrationStored + (error * dt), -integralSaturation, integralSaturation);
        float I = integralGain * integrationStored;

        //calculate both D terms
        float errorRateOfChange = AngleDifference(error, errorLast) / dt;
        errorLast = error;

        float valueRateOfChange = AngleDifference(currentAngle, valueLast) / dt;
        valueLast = currentAngle;
        velocity = valueRateOfChange;

        //choose D term to use
        float deriveMeasure = 0;

        if (derivativeInitialized)
        {
            if (derivativeMeasurement == DerivativeMeasurement.Velocity)
            {
                deriveMeasure = -valueRateOfChange;
            }
            else
            {
                deriveMeasure = errorRateOfChange;
            }
        }
        else
        {
            derivativeInitialized = true;
        }

        float D = derivativeGain * deriveMeasure;

        float result = P + I + D;

        return Mathf.Clamp(result, outputMin, outputMax);
    }
sly grove
#

So:
public float UpdateAngle(float dt, float currentAngle, float targetAngle) what are these inputs and outputs?

#

are these angles of the aircraft's orientation?

#

or of the control surfaces?

warm karma
#
pitch = X_PID_controller.UpdateAngle(Time.fixedDeltaTime, XcurrentAngle, 0)

they are angles of the aircraft's orientation

#

and then that pitch is what determines what the angle of the control surface is

sly grove
#

so the output is the new orientation of the aircraft?

#

and the control surface angle is determined by the difference between the current orientation and the new orientation?

warm karma
#

the input is the relative direction to the wanted point to look at and the PID output is a value from -1 to 1 that is later multiplied by the control surface max angle so it rotates what's needed. But the problem is that it has to rotate instantaneously in order for it to work

sly grove
#

right otherwise - it might be too slow to react

#

and the values are garbage

#

and you will get oscillation etc

warm karma
#

if only there was a way to like limit the max change rate of the PID values internally

warm karma
sly grove
#

ok so... video game question here

#

you want the control surface change to not be instantaneous for realism?

warm karma
#

exactly

sly grove
#

Would it be awful if you mechanically changed the control surfaces instantly but just added some visual interpolation?

warm karma
#

I mean I guess I could fake it and like set the physics control surface to change instantly and let the mesh object rotate smoothly, but idk

sly grove
#

yeah exactly

warm karma
#

the problem I encountered with that is sometimes it changes so quickly that it rotates the control surface so much that it becomes an airbrake😅

sly grove
#

ah yeah that will not feel very realistic

#

this is not an easy problem

#

I have no idea how the people who make real airplanes deal with this lmao

warm karma
#

and I've recently tried the visual interpolation but I'm not sure how to lerp the rotations as they are all local

sly grove
#

some math and physics PHDs needed

warm karma
#

yeah haha

sly grove
#

with transform.localRotation

warm karma
#

yeah but the problem is that the physics control surface doesn't have the same parent as the visual one, so I can't use the local rotation in order to get the physics control surface (I think), and there should be like a rotation offset because their rotations are not the same at the start

#

like I used to just use the parent constraint, but that doesn't smooth it😅

warm karma
#

~~okay fixed the visual thing after a lot of trial and error because I still don't understand quaternions at all: ```c
transform.rotation = Quaternion.Lerp(transform.rotation, RotationFollowPart.rotation*Quaternion.Euler(StartRot), Time.deltaTime * LerpSpeed);

the startRot is the rotationOffset and the RotationFollowPart is the physics control surface~~

Edit: Nvm it doesn't work lol
tall ferry
warm karma
#

Everything works except the rotation offset. It does rotate as it should with smooth movement and all, but the offset is incorrect for most control surfaces

Edit: Now it works, the problem was the rotation offset because I was getting it with euler angles and not with quaternions lol

dusk plaza
#

How do I make sure two assets don't go into the build no matter what? Those are generated on runtime and they only exist in editor time to save time
They are already in an editor folder
Used Assets and files from the Resources folder, sorted by uncompressed size:
122.7 mb 6.7% Assets/Editor/GeneratedAtlas/atlas NRSM.asset
122.7 mb 6.7% Assets/Editor/GeneratedAtlas/atlas ALBH.asset

sly grove
jolly token
dusk plaza
# jolly token Try `HideFlags.DontSaveInBuild`

Does not work unfortunately, it complains instead of omiting it from the build
An asset is marked with HideFlags.DontSave but is included in the build: Asset: 'Assets/Editor/GeneratedAtlas/atlas NRSM.asset' Asset name: atlas NRSM

#

despite being saved with HideFlags.DontSaveInBuild rather than HideFlags.DontSave

cerulean wasp
#

I think i need to use a source generator to do something I'm thinking about, but some microsoft websites say to use Incremental generators. Does anyone know about using these in unity?

dawn kettle
#

does anyone know how to fix a problem where my walking animations is preventing my character from rotating?

jolly token
umbral trail
#

2022.2+ for 4.0.1+

jolly token
#

Why are they not updating documentation 🤦‍♂️

umbral trail
#

What can I do about this massive time spent in Physics.UpdateCloth? This is for 6 horse reigns (with some capsule colliders for their necks/heads

cerulean wasp
#

Follow-up question: If I use a SourceGenerator instead of an IncrementalGenerator, will my build times take a lot longer?

wary blaze
#

I have the following scenario:

On Day 1, I create a Windows Build of my project. I can launch the Player without issue. I shut down my computer and the next day (Day 2), start it, open the project, and rebuild the project, having changed absolutely nothing (I cleared the output build folder before rebuilding). Now when I launch the Player, it immediately crashes.

My question is, where should I be looking to diagnose this crash? What could possibly change between a project from one day to the next from simply shutting the computer down!? Because I promise that I have not made any modifications to the project at all on Day 2.

sly grove
#

like the unity editor crashes?

wary blaze
#

No, this is in a build when launching the game's .exe

sly grove
#

so again

wary blaze
#

Player log says level0 is corrupted

sly grove
#

what kind of crash

#

the app jsut hard crashes and quits?

#

It freezes?

#

It runs but brokenly?

wary blaze
#

yes, it hard crashes, the crash handler is displayed for a second

sly grove
#

check the player logs

#

first make sure you're making a development build

#

and then check the player log

wary blaze
#

it usually happens on the splash screen

sly grove
wary blaze
#

I have already checked the logs, as I said it says level0 is corrupted

sly grove
#

what exactly is the message?

#

And what is level0?
is that one of your scenes?

wary blaze
#

The file 'E:/Bird_Sliced_New/Skara_Birdmen_Data/level0' is corrupted! Remove it and launch unity again!
[Position out of bounds!]
Crash!!!

#

Yes, level0 is the first scene in a build

#

but it happens with different scenes, so I don't believe there is actually a problem with the scene

#

as I said, one day it works, one day it crashes, without any changes

#

so I really don't think there is an issue in the scene

sly grove
#

I would do this:

  • open the scene in question in the editor and test it.
  • if it works there, delete your old build and make a fresh build and test again
wary blaze
#

And yes, I did try to rebuild after testing in the editor.

#

using the Clean Build option even.

#

It's a really strange error. Yesterday I thought I was honing in on it because I could successfully go from a working build to a crashing build by simply removing/adding a specific third party DLL. However, after a final successfull build last night, I shut down the computer. Today, I restarted it and opened the project, still without the offending DLL, and retested the build. And it's crashing. So now it looks like the DLL was not the problem.

#

are we allowed to tag the Admins? Judging by the facepalm reaction I guess that's a no. Sorry! I just don't see a normal user having the required knowledge of the engine to answer my particular question.

remote pumice
# wary blaze The file 'E:/Bird_Sliced_New/Skara_Birdmen_Data/level0' is corrupted! Remove it ...

If it doesn't take too long, you could begin with deactivating some Scripts in different Builds and check if one of them is the source of your issue.

If the project itself isn't too big, you could create a copy of it or import its contents into a clean one, just to check if the issue still persists.

Also, it says [position out of bounds]?
Are you accidently moving something by an unexpected amount?

If you create a Build with just your Level0 Scene, with all Scripts deactivated, does it still crash?

wary blaze
# remote pumice If it doesn't take too long, you could begin with deactivating some Scripts in d...

Hi, thanks for trying to help! The problem is that I have already tried removing stuff, and have gotten successful builds doing so. That is where I left off last night. I removed a single DLL and was able to make a successfull build. The issue is, I have changed nothing in the project, yet today when I did another build, that build crashed.

So at this point I do not think the issue is a script, or a game object. I think the project may somehow be getting corrupted, which is why I'm particularly wondering what could possibly change between one day and the next within a Unity Project (when there are no user initiated changes). The build should be exactly the same, yet it is not.

#

And this is actually a crash from one of my users (I'm an Asset Store Publisher), so it's not local to my computer.

remote pumice
# wary blaze And this is actually a crash from one of my users (I'm an Asset Store Publisher)...

So, a User informed you about that, and you are able to reproduce it on your machine in a clean project?

Or did the user send you the seemingly corrupted project to try fix it?
If that's the case and you aren't able to reproduce in a clean project, then it is possibly an error on the consumers side.

You are sure that DLL didn't accidently get included into the new Build you made today? You already said that it doesn't, but better check twice.

I'd still try to activate/deactivate more scripts, or to just make a Build with Level0 without Scripts, or to try import your Asset into a new project and check if the issue persists, those things are (probably) done quite fast and will give you some important information if they do or do not crash

The worst case would be to ask support / open a ticket

wary blaze
#
  1. I am testing their (probably) corrupted project. I haven't seen the issue on any of my projects with my product, which is why I actually told the user I don't think this is an issue with my product. However, I then tested removing my product completely and did a build and it worked, so I was left scratching my head. However, now after going from not crashing/crashing between one day and the next, I'm back to believing it's not an issue with my product.

Still, I was trying to use the project as a learning experience for how to debug crash reports, however that ended up being a mostly dead end.

  1. The DLL was not in the project at all on the Day 2 build when it started crashing again. I checked the Data/Managed folder on the build to make sure as well.

  2. I can try deactivating/activating, but the fact that I have been able to get working builds with all of the supposedly corrupted scenes at one point or another indicates there is no actual problem in the scenes.

#

In any case, thanks for the help!

remote pumice
# wary blaze 1) I am testing their (probably) corrupted project. I haven't seen the issue on ...

You shouldn't have to work on the consumers project in my opinion, instead he should give you a list of steps you need to take to reproduce the error.

Instead of removing your product from the consumers project, could you instead check if the user is even using it properly?

Also, is your product even able to cause a [position out of bounds] message? I'd take that one serious.
Maybe there's a corrupted art asset or prefab or something, which uses your product, but has an error in another of it's components

wary blaze
#

Thank you. As I said, this is more of a learning experience about how to debug crashes, it's not necessarily about helping the user fix their project. I only mentioned the user to say that the crash is not just local to my machine.

#

You are asbolutely right that it is not my responsibility to help the user as I am doing, especially since all evidence points to it not being an issue with my product.

heavy salmon
#

Hi everyone, this code doesn't apply the rotation correctly, the desiredRotation is what I want it to be when its debugged to the console but it's not applied to the player correctly. So when the desiredRotation is 180 the player is rotated -126 degrees

wary blaze
#

They are just the benefactors of my own curiosity

remote pumice
high dock
#

hey, how can i go about merging two arrays of samples from different audio clips into one single audio clip?

wary blaze
#

Thank you for your time!

remote pumice
#

You're welcome! I'm out of ideas, sadly, I hope you'll succeed and find the cause of the problem!
Would be curious to hear the solution, if you find it 😄

wary blaze
earnest heron
#

Hey,
So I have an issue with Zenject/Extenject.
I have Player gameObject and it instantiate Character prefab by factory method and as a child of Player.
Also Player has GameObject Context component. And bind PlayerId in its installer.
In Character, injection happens for injecting PlayerId but unfortunately it throws an error about it can't recognise that.
So my question is, Does Zenject/Extenject support injection on child from GameObject Context or I have to inject it manually after instantiation ?

pulsar crane
#

I have an issue with an event fiereing where unity complains about a missing object, but I don't understand why it's happening. I feel like it's something obv that I'm not seeing, hope y'all can spot it

#

Basically the error line 18 is called as soon as I spawn, but I don't get what's missing, the event? The error of line 84 is called when ReadyAuto is executed

pulsar crane
real sequoia
#

hey im trying to make a system where the longer you hold down a button the faster a projectile goes with the new unity input sytem but instead of the projectile fling when you release it flys once you press how may I fix this

pulsar crane
#

try Input.GetButtonUp no?

real sequoia
#

does that work with controller?

pulsar crane
real sequoia
#

well its the left mouse on pc and back triggers on controllers

pulsar crane
#

I mean that ctx class

real sequoia
#

Ill just give a screen shot with everything'

pulsar crane
#

can you show me the whole else if

#

because from this screenshot the else case never happens since it's an elseif with the same conditions

real sequoia
pulsar crane
#

My man clean this code, just have an if with all them conditions and then have an if gunChosen != 6 inside it, with the logic for that and a return. then you place the normal logic. This is not the problem solution, but clean code is much easier to debug. I'm guessing you do not see the print statement right?

real sequoia
#

yes

#

I do not see the inputacted

pulsar crane
#

Idk, mayb try ctx.performed, so if(ctx.performed) and fire in that if

grave jackal
#

Hello, I have an FPS character, as you can see in the hierarchy, the camera and the character model share the same parent, but inside the model I have ik constraints that allow me to move the body up and down with the camera flip up and down.

What I want to do is be able to have another camera inside the character's head so that even though the main camera stays in the same place, the other camera that is the child of the head moves with the body and I want that to be the one that renders, The problem is that when I add a new camera as the daughter of my character's head, the movement of the main one is cancelled, can someone please help me?

graceful hollow
#

Hello! I'm having trouble wrapping my head around this particular problem. I'm sorry if this isn't the right channel. I'm also sorry if I'm not using the right terms.
The problem I have is that I need to drag a prefab into a script's public GameObject variable. But that prefab comes from an AssetBundle that is loaded in during runtime.
Is it possible for the script to remember the dragged in prefab?

grave jackal
graceful hollow
grave jackal
# graceful hollow That's what I thought too. I was just wondering if there was something about Uni...

Try this to see if it's what you're looking for ```public class MyScript : MonoBehaviour {
public GameObject myPrefab;

IEnumerator Start () {
    AssetBundle myLoadedAssetBundle = null; // Load your AssetBundle here
    yield return StartCoroutine(LoadMyAssetBundleCoroutine((loadedAssetBundle) => {
        myLoadedAssetBundle = loadedAssetBundle;
    }));

    if (myLoadedAssetBundle != null) {
        myPrefab = myLoadedAssetBundle.LoadAsset<GameObject>("PrefabName");
    }
}

IEnumerator LoadMyAssetBundleCoroutine(System.Action<AssetBundle> result) {
    // Load your AssetBundle here and then pass the loaded AssetBundle to 'result'
    yield return null;
}

}

graceful hollow
grave jackal
shadow grotto
#

It keeps getting lost in general and might be a more advanced question anyway, I'd love some guidance/advice/reading materials related to this if anyone gets the chance: #archived-code-general message

scenic forge
#

Btw SGs don't just run during build, it runs in your IDE literally every key stroke you make, so it has the advantage over editor script that whatever code changes you make, SGs are instantly aware of them and regenerate new code without you having to tab in and out of IDE to Unity Editor.
If you don't need that capability, consider good old editor scripts.

#

For reference my project is around 80k LoC and it runs two SGs (which scan for attributes to generate code), even on my bad laptop it's instantaneous.

scenic forge
high dock
hallow elk
#

ArgumentException: Arial.ttf is no longer a valid built in font. Please use LegacyRuntime.ttf

This change appears to have happened in 2022.0.b3. Currently this is the workaround I'm working with. Is there a way to directly get whatever the default font is, regardless of version?

// Known bug: This may cause errors for some 2022 beta versions.
#if UNITY_2020_2_OR_NEWER
lbl.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
#else
lbl.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
#endif```
#

The Unity Documentation appears to be outdated for 2022 versions on this matter:

cerulean wasp
scenic forge
#

Yes, that's one of the good use cases of SG, especially if you are going to have many of these classes/edit them a lot.

cerulean wasp
#

i only plan on one for now, but I am working on learning to do these things properly.

#

the code for them just seems complicated, since all the examples are so dissimilar from what I’m trying to do.

scenic forge
#

General idea is, create your own ISyntaxReceiver and register it. In the receiver, collect all the information you need in order to generate all the code.
Then in ISourceGenerator.Execute, use the information collected by the receiver to generate the sources.

quartz nymph
#

Can someone help me out? I upgraded from 2022 to 2023 and the following code stopped working.
Goal: I have no source texture. Just want to put output from custom shader to renderTexture.
Problem: It seems that the render texture is now just blank...

    void Update()
    {
        backgroundMaterial.SetFloat("_UnscaledTime", Time.unscaledTime);
        Graphics.Blit(null, renderTexture, backgroundMaterial);
    }

This was working before. I'm hoping there's an alternative to get this working. I'm not suprised it stopped working as it didn't quite seem intended.

frosty patrol
#

this link is somthing someone else uploaded

heavy salmon
pulsar crane
#

nooo, hahah

frosty patrol
#

where do I get IUnityInterface.h and other headers ?

austere jewel
#

You should be able to find them in Unity\Editor\Data\PluginAPI

hardy nymph
#

Hi , I want to attach a component to an object based on a string name

#

How can I do that ?

#

For-example I have a variable storing a random component's name

var componentName = "Transform";
#

I've tried Type.GetType but it returns null, even with UnityEngine.Transform as the name.

sharp stag
#

Hey people, I've got a question that's eating me for quite some time now and wanted your feedback.
What's the requirements to be a lead unity programmer?
I've been senior for quire some time and wanted to take a leap forwards but I'm questioning if I've got what it takes because... I'm not sure what it takes. I've got a lead in my team to ask, but wanted some more feedback. What's your experience?

real blaze
#

hey. this is about Android builds. is it possible anymore to build for x86 architectures? Is see ARMv7 and ARM64 in the Player settings when IL2CPP is selected. but when I build and try to install to some android 6 (emulated) it says incompatible architecture (The APK failed to install. Error. INSTALL FAILED NO MATCHING ABIS) and after some Googling I figured it means the emulator's running as a x86 and the APK doesn't support that.
so, in short:

  1. is it even possible to run a Unity game inside a Android Studio's emulator?
  2. if so, how can I get either:
  • Unity to build for x86 arc
  • or Android Studio to emulate a x64 arc
real blaze
tribal pivot
#

Any code not in an assembly def seems to automatically have a reference to my asmdef, but not the other way around.

Is there any way to inverse this? I want to access things from the main assembly in my assembly def, and not be accessible from main

cloud crag
#

Hey. This coroutine freezes unity for 0.5 seconds, it is really annoying, can you give any advice what to do?

real blaze
#

a workaround is to put everything in a separate assembly, but that comes with some prices

tribal pivot
real blaze
#

if you want the proj to be super organized, ideally your tests should be written for separate systems, and each system would have it's own assembly. by system I mean very different systems or modules (purchase/advertizement/IO etc.)
this will allow for a separate Test assembly for each system/module

tribal pivot
#

Thats a very large change for us, not one i am interested in. Thanks for helping anyway!

real blaze
cloud crag
#

Ok, thanks, I will

#

I am suspicious

#

that this one frreezes unity:

#

Can you give any idea how to fix?

tribal pivot
cloud crag
real blaze
cloud crag
#

Ok, can creating AudioClip be expensive operation?

#

I will check it. okay thanks

tribal pivot
cloud crag
#

Desktop

tribal pivot
#

That first comment says something about it no

cloud crag
#

I checked with prfiler

#

and this code takes 500 ms

#

creating audio

#


            var audioClip = AudioClip.Create(
                "Speech",
                SampleRate * 600, // Can speak 10mins audio as maximum
                1,
                SampleRate,
                true,
                (float[] audioChunk) =>
                {
                    var chunkSize = audioChunk.Length;
                    var audioChunkBytes = new byte[chunkSize * 2];
                    var readBytes = audioDataStream.ReadData(audioChunkBytes);
                    if (isFirstAudioChunk && readBytes > 0)
                    {
                        var endTime = DateTime.Now;
                        var latency = endTime.Subtract(startTime).TotalMilliseconds;
                        newMessage = $"Speech synthesis succeeded!\nLatency: {latency} ms.";
                        isFirstAudioChunk = false;
                    }

                    for (int i = 0; i < chunkSize; ++i)
                    {
                        if (i < readBytes / 2)
                        {
                            audioChunk[i] = (short)(audioChunkBytes[i * 2 + 1] << 8 | audioChunkBytes[i * 2]) / 32768.0F;
                        }
                        else
                        {
                            audioChunk[i] = 0.0f;
                        }
                    }

                    if (readBytes == 0)
                    {
                        Thread.Sleep(200); // Leave some time for the audioSource to finish playback
                        audioSourceNeedStop = true;

                    }
                });
tribal pivot
#

Why not use native playback, since your comment says thats supported

#

Oh i have an idea to take off 200ms off of that

cloud crag
#

Comment that thread sleep?

#

I did that but

#

Still 300

#

remaining

#

This code is not mine. I copied it from Microsoft's text to speech sdk

#

but it has some problems

real blaze
#

this has a 200ms thread sleep call? that's clearly meant for multithreading

cloud crag
#

Yeah

#

there are many stuff going on there

#

lock ing for syncrhonisation too

#

I have no idea why they needed to use that

cloud crag
#

asyncly

#

I do not think that thing is thread-safe

#

but. can unity Job System help?

#

Ah shit

#

it now took around 1.6 seconds

#

I have to get rid of it somehow.

scenic forge
#

StartSpeakingTextAsync is already async.

cloud crag
#

this one?

#

As it says it is but. this code freezes unity

#

I commented Thread.Sleep but still

real blaze
#

you're not using await on it

cloud crag
#

Nah, it is microsoft's sdk

real blaze
#

ah

cloud crag
#

text to speech

#

this one. but very weird it has so many problems

ashen yoke
scenic forge
cloud crag
#

I tried that

#

that is not causing problem

#

But still. how can I make it work asyncly?

#

Maybe that can help too

ashen yoke
#

Is Microsoft.CognitiveServices.Speech capable of good speech creation (sideways question)?

cloud crag
#

If you are interested in audio, I can show you

#

Look, this is problem + Audio in video