#archived-code-advanced

1 messages Β· Page 80 of 1

burnt hamlet
#

how would gravity start again if being still is what triggers it to not be applied? that feels like it would cause a feedback loop

untold moth
#

It's called "dormant state" of the rb.

#

Or sleep state

tiny pewter
#

Unity physics engine will sleep the rb if the velocity below some threshold
But I believe the ground is continuously colliding with the box you show so the rb of box cant sleep

untold moth
#

It sleeps after becoming completely still

burnt hamlet
#

would reaching the peak of a jump count as a sleeping moment or would it still be active?

#

like, the moment its not going up or down, but about to go down

untold moth
#

I think it takes a few frame for it to sleep.

#

So it shouldn't go into that state in the mid air. Unless it's not moving at all(no gravity applied).

#

I don't see how that's relevant to your initial question though.

burnt hamlet
#

I dont currently have it taking collisions into account for calculating velocity, but that shouldnt effect gravity, everything else happening there is normal Unity physics, gravity is the only force being applied differently

#

unless linear drag does more than just slow down over time

untold moth
#

So it should go to a halt eventually.

untold moth
#

You don't need to change gravity to stop an object.

burnt hamlet
#

another observation I've made is that the object with my code loses its bouncing height much faster but then stabilizes at a very small bouncing height that it continues doing forever

hardy jacinth
#

there is also a type of "step" you use to update velocities and accelerations etc.

#

for example Verlet integration vs Euler integration

#

so depending on how you calculate and update velocities you may get systems that loose energy, conserve energy or gain energy

pine topaz
#

can we add new animations to animatorOverrideController by script, or to animator of it ? (runtime)

dusty wigeon
sharp monolith
#

Hi im having a problem with my ai character for my vr game. the NavMeshAgent means the character cant be grabbed as it doesnt let it be picked up off the floor, ive written code to turn on a collider and turn off the NavMeshAgent when the players hand is close enough to grab the ai, but insted it just makes it launch itself downwards, ive even tried turning off gravity so the thing cant fall but then it just teleports to the furthest down it can go
Hi im having a problem with my ai character for my vr game. the NavMeshAgent means the character cant be grabbed as it doesnt let it be picked up off the floor, ive written code to turn on a collider and turn off the NavMeshAgent when the players hand is close enough to grab the ai, but insted it just makes it launch itself downwards, ive even tried turning off gravity so the thing cant fall but then it just teleports to the furthest down it can go

pine topaz
dusty wigeon
pine topaz
dusty wigeon
#

It was waived at the end.

#

And, you also need to sync the state of the controller before and after the apply. (If it has not changed)

lament salmon
dusty wigeon
#

That given said, we had a really, really large amount of animation to override.

#

Like 200-300 hundred.

#

We had weapon with 50-100 unique animation.

lament salmon
#

Oh boy.

dusty wigeon
#

So yeah, I guess a normal usage is fine.

#

The sync of the animator is also an issue, but performance wise it didnt seem to be that bad.

upbeat path
# dusty wigeon

I would say that perhaps Animation is the wrong approach to this

dusty wigeon
#

Was not really my choice. I felt like it should have been limited. Like having a maximum of animation per weapon that is reasonabe.

upbeat path
#

2D or 3D?

dusty wigeon
#

3D

upbeat path
#

ouch

dusty wigeon
#

It is not the only feature that we struggle with the animator at the moment.

upbeat path
#

I'd be tempted to make a kind of stop motion database and just run through it

dusty wigeon
#

By example, our animator want to be able to add animation inbetween state instead of relaying on animation blending.

#

We also stuggle with adding additive blending per bone.

#

We are able to do it, but only on the result of the animator, which means that we cannot blend between animation that has additive blend per bone.

lament salmon
upbeat path
#

Yep, I think you will be better off taking it all out of the hands of Unity and writing your own custom system

#

it'll be the only way to make it performant

dusty wigeon
#

Yeah, we are looking at the way unreal does things and other solution.

upbeat path
#

best of luck, that is a heavy, heavy task to get just right

sudden rapids
#

Hi guys, I wish to recreate the voxel slicing effect from the game Clone Drone In The Danger Zone, but am unsure as to what is the best way to go about it. Creating models from instantiated unity cubes acting as voxels would probably be horribly inefficient, but I'm unsure as to how to go about creating the model and destroying voxels within it in a passable way that wouldn't tank the fps.

Suggestions for approaches and tips would be much appreciated! πŸ˜„

The provided image shows the effect I'm trying to recreate:

lilac lantern
#

yea mesh particle system is probably the best.

bronze summit
#

Is there a way to pass data like build version from the prebuild script to use in runtime? I calculate the version number in prebuild, and would like to use it during runtime

#

Would it be possible to write this to UnityCloudBuildManifest.json?

sudden rapids
#

Could I create a destructible voxel model using it?

sullen gate
stuck onyx
sullen gate
thick rapids
upbeat path
#

Async runs on the same thread that started the Task

sullen gate
#

Maybe something is actually running on a different thread that I'm not aware of

upbeat path
#

Then your Task is being run on a different Thread

sullen gate
#

Is there a way to check what thread I'm on?

sullen gate
upbeat path
#

you're using the new Unity Async-Await?

sullen gate
#

Don't think so

#

I'm using c# built-in BeginReceive on a socket

upbeat path
#

so how do you start your Task?

#

TCP Client?

sullen gate
#

yes

upbeat path
#

show code

#

That's empty

sullen gate
#

oh lol

upbeat path
sullen gate
#

nothing fancy

upbeat path
#

show code

sullen gate
# upbeat path show code
public class UserSession : MonoBehaviour {
    public Socket connection;
    
    public UserSession() {
        connection = new Socket(SocketType.Stream, ProtocolType.Tcp);
    }

    public void connect(string hostname, int port) {
        this.connection.Connect(hostname, port);
    }

    public void close() {
        this.connection.Close();
    }
}
upbeat path
sullen gate
#

Ok :/
thank you anyways

upbeat path
# sullen gate Ok :/ thank you anyways

wait one, it may well be that, because you are using Async, the Async callback is done on a different thread, this is platform independent behaviour, so maybe or maybe not

sullen gate
#

I'll look into that

upbeat path
#

this only happens with Socket, not with TCPListener and TCPClient (TCP Tunneling)

sullen gate
#

Yeah I'm using a socket because the end point is a Python server

upbeat path
#

btw Socket is really slow becaue it is using the ws:/// protocol

sullen gate
#

And I want to switch to ReceiveAsync instead of BeginReceive anyways, so maybe the behaviour changes

sullen gate
upbeat path
#

could well be, I generally run all network in it's own Thread and then use Coroutines to pick up the result on the main Thread, hacky I know but it works

sullen gate
#

Yeah I use the main thread dispatcher because I can't be bothered to design it differently

tired basin
#

Error: Both modules 'base' and 'UnityDataAssetPack' contain asset entry,
has anyone face this issue ?

#

while building Android App Bundle with splitBinaryApplications

spiral rune
#

so I'm trying to use a nuGet package in nity, so I installed this package https://github.com/GlitchEnzo/NuGetForUnity, I also changed to .NET framework in the unity settings, I don't really like this way of doing stuff but I need to use this package somehow (I'd also thought about making a dll but Idk how to import the dependences), anyway the projects runs but I get this error: Burst internal compiler error: Burst.Compiler.IL.CompilerExceptionAssemblyResolution: Unable to resolve type System.Runtime.CompilerServices.IsReadOnlyAttribute. Reason: Unknown.

zealous hare
#

How are character controllers implemented when they have a large amount of abilities modifiers and states? What design patterns do modern games use? I'm most familiar creating character controllers with a state machine but I feel like there has to be a more modern approach.

shy wasp
#

Hi everyone! I'm working on a boat game with controllable NavMeshAgents. I know dynamic NavMeshSurfaces arent supported yet, but I'm doing my best to work around it. I've implemented what I thought would be a good work around, but there's still some agent slip on the surfaces. Any advice would be much appreciated.

dusty wigeon
obsidian coyote
#

You could make a sort of context system where when a character jumps off thr boat, it updates the parent to a global one, and when they get on a boat, it updates it again. Maybe use trigger regions or something to handle the parent swapping

shy wasp
obsidian coyote
#

Might be a pain to implement, but what about baking the nav mesh in a static location somewhere offscreen, then when calculating a path on the ship, it would use the other static mesh for path finding.

shy wasp
quick rose
#

i need a paper/description on transform predictions over a network.... or whatever it's called to hide rubberbanding, etc...thanks

#

specifically in realtion to a space dog fight simulation

dusty wigeon
glacial wedge
#

Help pls. I'm getting crazy

#

It say missingrefenceexception

#

but I set it to the correct animator

sly grove
#

as it says in the error

glacial wedge
#

loading

sly grove
#

Yes you are changing scene so if the animator is in the old scene it will of course have been destroyed

#

this is not really an advanced coding topic btw

glacial wedge
#

the error is from the new player

#

oh.. maybe i have an idea

#

the missingreference is from a listener that i open onstateenter and close onstateexit, but when i change the scene it doesn't exit the state before destroy the animator

#

Ok. solved

bleak citrus
#

I am switching to using RaycastCommand to perform a large batch of raycasts against level geometry.

However, it looks like trying to move a CharacterController causes all pending physics batches to be completed immediately.

Is there anything I can do about that, or should I just arrange things so that raycasts only execute after the controllers are done moving?

#

perhaps I should be making a separate physics scene that holds all of the level geometry I care about

bleak citrus
#

that sorts it right out.

#

executing the batch in LateUpdate after everyone else is done monkeying with the physics scene works great

#

and unity just crashed. splendid.

bleak citrus
#

Spoke too soon. Now it looks like running the raycasts at the end of LateUpdate means they crash into stuff in PostLateUpdate.

hardy jacinth
#

with C# syntax generators, is it possible to make file generate like "in a directory"? Filename hint is a unique string that cannot contain / so I have to use something like namespaceA.namespaceB.classname.g.cs to generate files

scenic forge
#

Why though, are you trying to output them to physical files rather than in memory?

bleak citrus
#

that's unfortunate; I was hoping I could do a ton of spherecasting in the background

hardy jacinth
#

so is generating unique name from nested namespaces and nested classes

scenic forge
#

Ah.

#

I mean namespace and class name should uniquely identify it, and attach the generator's name if you are using multiple SGs for the same class

#

But yeah doesn't really help with the issue of having massive amount of generated files, although I suppose I also don't look into them often.

sharp monolith
#

Hi, ive been working on code to throw an ai in vr. its working now, but when you thow the ai and it lands, it messes up the navmesh and cant track and move back to the player, it just spins while moving around randomly. anyone know why?

upbeat path
fickle mango
#

To convert a float value between 0-1 to a AudioMixer volume value I use

Mathf.Log(value) * 20;

How would I return that value back to a float that is between 0-1?

fresh salmon
sharp monolith
thorn flintBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

sharp monolith
#

!code

thorn flintBOT
#
Posting code

πŸ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

πŸ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

sharp monolith
upbeat path
sharp monolith
#

oh how would i do that then? cus i thought i was doing it when it was deciding if the slime or player was closer?

upbeat path
#

man, look at your code. you are doing agent.destination = instead of agent.SetDestination();

sharp monolith
#

ohhhhh

#

ok thx

#

sorry ive only been coding for a week, so still new

upbeat path
#

thewn you are in way over your head and should take a step back and look at
!learn

sharp monolith
#

alright thanks!

upbeat path
#

!learn

thorn flintBOT
#

πŸ§‘β€πŸ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

plucky laurel
#

you would expect destination and SetDestination to do the same exact thing

upbeat path
#

not at all

plucky laurel
#

but

#
        [MethodImpl(MethodImplOptions.InternalCall)]
        private extern void set_destination_Injected(ref Vector3 value);
        [MethodImpl(MethodImplOptions.InternalCall)]
        private extern bool SetDestination_Injected(ref Vector3 target);
bleak citrus
#

I'd expect that too. Interesting.

upbeat path
#

.destination does not calculate a path, SetDestination does

plucky laurel
#

that doesnt seem to be true

upbeat path
#

unless it's changed in recent versions, that has always been the case

sharp monolith
#

yea no the ai still moves to the player

plucky laurel
sharp monolith
#

its after the first throw where it just moves all over the place, it still tries to track the player but cant seem to find its way

plucky laurel
#

its impossible to tell without seeing your actual case with navmesh gizmo and all

sharp monolith
grave raft
#

hello, im having problem making thruster dampener
i have a single object with rigid body that has gravity, i need to use force to push it up and keep it into one place, raycasts not allowed

stoic otter
#

is there a way to make a attribute that give the values when there is a specific delegate called or something

#

so i can do for example

#
[SaveAble]
public Vector3 position
Action<T> SaveAll;
#
//Get all Attributes and save it?
flint sage
#

TypeCache

#

There's no built in language support

#

So just get all attributes > use refleciton > savedata

stoic otter
#

thats not the best way right how would you guys save it?

#

because reflection is expensive

flint sage
#

Depends how often you do it really

#

It's not that bad and if you do it on properties, you can generate an optimized action that is only 10% slower than native accessors

stoic otter
#

everytime a checkpoint is triggered i want to save alot of values so i need to track multiple values

#

can i save a certain variable adres so that the game just track it without worrying about it

flint sage
#

I mean you can just keep a pointer if you want to do it that πŸ˜›

#

But there's no automagic way to keep track of random variables

stoic otter
#

as in can you give with a attribute a pointer back or something?

#

so that you can do [SaveAble] and then its automatically a pointerish ref?

flint sage
#

I mean you still need a reference to the instance, which an attribute knows nothing about

#

So you'll need some system around it

dusty wigeon
novel plinth
dusty wigeon
dusty wigeon
# novel plinth

I would be curious to know how much overhead we are talking.

real blaze
dusty wigeon
#

Because, I have used reflection in multiple project in runtime and had no performance issue whatever.

real blaze
#

source gen is black magic.

dusty wigeon
#

There is also IL Weaving

real blaze
#

people tend to stay away from it

scenic forge
#

Source generator is hardly black magic though, they are just a bit painful to setup yourself (and especially worse in Unity because, Unity)

#

In the wider C# world, SGs are very well utilized even if you are not aware of it.

#

STJ has SG, there are DI with SG, object mappers with SG, MVVM with SG, etc.

#

Even things like Enum.TryParse has SG based libraries that you can use to hugely improve performance and lower allocation (because Enum.TryParse and friends use reflection under the hood)

finite merlin
#

I want to download audio from api so I am using "DownloadHandlerAudioClip".GetContent()" but it is returning small audio then original source.

#

If I write audio clip to file then it is writing full length audio file.

#

Any idea what causes audio file cut issue, it cuts almost 10% of audio.

#

Please help thanks

scenic forge
#

What's the expected length and what are you actually getting?

#

And just to make sure, AudioClip#length returns the audio length in seconds, not file size.

finite merlin
#

Expected length 20 sec and getting 15 sec

scenic forge
#

Hmm, what's the audio format?

finite merlin
#

Mp3 formate

scenic forge
#

I wouldn't be surprised if Unity's decoding just can't handle it, it's very limited.

finite merlin
#

But when I save the file to disk it is the exact size

#

Just issue with this method's audio clip

scenic forge
#

Tbh I'm not surprised, I've had user uploaded audio that get incorrectly decoded into different lengths before (most commonly half/double the actual length)

#

If you have control over the audio, you can try messing around with the formats, or use asset bundles.

#

If you don't have control, your best bet would be to include audio decoding with your game (mine embeds FFmpeg).

finite merlin
#

No i can not, I am getting it from text to speech API

scenic forge
#

Not familiar with those, maybe state the API you are using and someone knows can help.

finite merlin
#

Ya thanks for your time

rotund citrus
#

is there any possibility that awake will get called after onEnable()?
I have 2 scripts on the same gameobject at the start of the scene,

the first is a singleton (implemented in awake)
the second has some functionallity in onEnabled that needs the first script.

for some reason, the first script is null when calling onEnabled at the second script.

I tested some things, and it only seems to be null at onEnabled.
if I check this on the update of the second script, the first one is good to go.

here is the awake of the first script:

    private void Awake()
    {
        if (inputDirector._instance == null)
            inputDirector._instance = this;
        else
        {
            Debug.Log("input director already exists. destroying self");
            Destroy(gameObject);
        }

        _playerInput = new ActionsMaster();
    }

and onenabled of the second script:

    private void OnEnable()
    {
        if (inputDirector._instance == null)
        {
            Debug.Log("inputDirector._instance is null");
        }
        else
        {
            inputDirector._instance.OnInputReady += onInputEnabled;
        }
    }
fresh salmon
#

Log a message in both script's Awake. The singleton might be disabled at first and then enabled later on

#

Check that the messages come in the right order

tiny pewter
#

onenable sometime will be called right after awake iirc
ie A awake->A onenable->B awake->B onenable

fresh salmon
#

There's that too

fresh salmon
#

The code in the second script should be in Start

rotund citrus
fresh salmon
#

After

#

Awake - OnEnable - Start [ - Update * ]

rotund citrus
#

yea, awake for the second is getting called before the first.

#

but that is weird, why would one onenable come before the other awake?

rotund citrus
#

putting the code in start instead of onEnable fixes the issue. thank you!

tiny pewter
nova summit
#

Can we simplify this further?
I need to apply a rotation (Q2) to an object in relative to another rotation (Q1)

var delta = Q2 * Quaternion.Inverse(Q1);
transform.rotation =  Q1 * delta; //Moving first by delta and by Q1

effectively,
Q1 * Q2 * Quaternion.Inverse(Q1);

#

Ouch! The above seems to be wrong too 😐

dusty wigeon
#

Quaternion are not commutative

nova summit
dusty wigeon
#

My bad, that would be associative

spiral zenith
#

Yes, I believe quaternion multiplication is associative (but not commutative).
So you can replace delta with Q2 * Quaternion.Inverse(Q1) πŸ™‚

dusty wigeon
#

Yeah, I fuckup commutative and associative

woeful kraken
rotund citrus
#

But still it only makes sense that all object's awake will be called before all object's start and onenable.

woeful kraken
dusty wigeon
#

Before start

#

And after awake

tiny pewter
#

onenable is not guaranteed to be executed after all awake but start is

rotund citrus
#

Amazing graph

dusty wigeon
#

I still believe that OnEnable should be called after start though

#

I do not understand why they went that way.

rotund citrus
#

Agreed

#

Actually

#

Maybe not

#

OnEnabled is generally meant to be called when "enabling" a new object

#

Awake will still get called even when the object is disabled

#

So it does make sense the onEnabled will act as the "awake" of runtime initiated objects

dusty wigeon
#

If the object start disabled, Awake will not be called

rotund citrus
#

And start will still get called after it

rotund citrus
dusty wigeon
#

As far as I remember

tiny pewter
#

tested in 2021.3.16

rotund citrus
nova summit
# nova summit Can we simplify this further? I need to apply a rotation (Q2) to an object in re...

transform.rotation = Q1 * delta; //Moving first by delta and by Q1

This actually nullifies the Q1 part which I want to retain.
For example:
Consider Right foot (Ankle) with 0 rotation. It points the toes to the ground.
I want to face the toes forward, so my bind pose will be 90 degrees in x-axis.

Now, I want to apply a rotation of 135 degrees in y-axis. (Hope you are following till now :D)
I need the final rotation to be in relative to the initial bind pose not from identity.

How to achieve this?

dusty wigeon
#

Did you try the inverse ? delta * Q1. If I remember correctly, quaternion operation are right to left

#

(Hope I am right this time)

nova summit
#

delta * Q1 => Q2 * Quaternion.Inverse(Q1) * Q1 => Q2 😐, Not the one I wanted as it totally ignores Q1

I mean
delta * Q1 => Q2 * Quaternion.Inverse(Q1) * Q1 => Q2 * (Quaternion.Inverse(Q1) * Q1) => Q2

tiny pewter
#

manually enable and disable a go (disabled in edit mode) few time (by reentering play mode..) awake is called before enable and awake is called when i enable the go

dusty wigeon
spiral zenith
spiral zenith
#

Ok. Sorry I think I didn't follow πŸ˜…

#

But actually, what's your question?

rotund citrus
# dusty wigeon If you enable an object that was never enabled, Awake will be called then onenab...

start gets called once as well.
onenabled is supposed to be the "awake" for enabling and disabling object.
which sounds dumb to me, because anyways start wont get called after re-enabling an object.

also I remember everyone usually puts their input subscribing events (from the new input system) in onEnable and de-subscribing in onDisable?
that sounds like bad practice now, sinse start/awake will anyways wake for the object to be enabled. so why not just do it once in start and again at onDestroy?
they even do that on their documentation:
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/manual/Actions.html

dusty wigeon
nova summit
spiral zenith
#

πŸ˜…
I don't see the difference between 1 and 3 though

nova summit
#

This will be delta. Agreed?
Applying 45 degrees in X to the inverse of Bind pose.

spiral zenith
rotund citrus
spiral zenith
#

If so, you would do transform.rotation *= transform.rotation * rotation_you_want * Quaternion.Inverse(transform.rotation) I think

nova summit
#

Let me explain. Not considering local rotations anywhere.
If you see the above first image, the bind pose. It has 90 degrees in X + 90 degrees in y rotation.
Now if I have a rotation (global one) 45 degrees in X, I need to apply this in relation to the above bind pose.
so the final rotation should be 45 degrees in X + 90 degrees in y rotation-> I'm trying to get this.

nova summit
spiral zenith
#

I'm sorry I don't understand and I have to go.
But basically when you multiply an orientation by a quaternion, it applies the rotation with respect to the local space of the object (so if you take a quaternion that rotates 90 degrees around the x axis, it will rotate the object 90 degrees around its x axis).
And if you have a quaternion q and you want to convert it to a quaternion with respect to a local space, and if the rotation of that space is p, you do p * q * Inverse(p). (so if object A's orientation is p and you want to rotate A 90 degrees around the global x axis, you have to multiply A's orientation by p * q * Inverse(p) if q is the quaternion to rotate 90 degrees around the x axis)
Hopefully you can combine this to get what you want πŸ™‚
(And hopefully my explanation and vocabulary wasn't terrible πŸ₯² )

nova summit
#

in p * q * Inverse(p)

q * Inverse(p) is what I'm calling as delta.
If I apply P on the delta, it actually cancels out the rotation in y (as it already has the inverse rotation of 90 degrees y-axis in my case)
Thats what the problem is.

nova summit
spiral zenith
#

But I think I'm terrible at explaining math in english, sorry 😭

nova summit
#

And btw, your comment is wrong I think, Q1 * delta means rotating first with Q1 and then with delta.
No no. It's proper. Multiplication happens from right to left with quaternions. So its fine.

#

That will rotate by Q2 rotated by Q1 πŸ™‚
I don't think so.
transform.rotation = Q1 * Q2 * Quaternion.Inverse(Q1); //Moving first by inverse of Q1, followed by Q2 and then by Q1

spiral zenith
#

That's why when you want to apply a rotation, you do transform.rotation *= new Quaternion();
Which is equivalent to transform.rotation = transform.rotation * new Quaternion();
So first transform.rotation, then new Quaternion()

spiral zenith
#

Ooh wait I think I've just realised something!

If you multiply from left to right, it applies the rotations one by one with respect to the new frame every time.
So if Q1 is 90 degrees around y and Q2 is 90 degrees around z, Q1 * Q2 will be 90 degrees around the object's y axis and then 90 degrees around the object's new z axis (after applying the first rotation).
That's what I've always used.

But from what I've just tested (I got the idea from you, thanks πŸ™‚ ), it looks like multiplying from right to left applies the rotations with respect to the world's frame.
So Q1 * Q2 is also 90 degrees around the world's z axis and then 90 degrees around the world's y axis.

Is this right? Again, I'm pretty sure about the 1st one but not about the 2nd one, I've only done a few tests so it might be wrong πŸ˜…

drifting jolt
#

Hello, I need help coming up with a solution. So I have a game that involves the player equpping a candle and in one stage there could be multiple candles. So I used a Prefab to Generate these candles. When the player equips the candle, the lifetime of the candle would decrease. and when it is unequipped, the remaining lifetime would then be assign into the prefab. I noticed that all the candle prefabs in the end are sharing the same data from one another. Is there another solution to this?

nova summit
#

But from what I've just tested (I got the idea from you, thanks πŸ™‚ ), it looks like multiplying from right to left applies the rotations with respect to the world's frame.
I visualise as rotation Q1 applied followed* by Q2 where Q2 is applied "over" Q1 to give an addition as a final result.

devout hare
#

That's a #πŸ’»β”ƒcode-beginner issue but either don't destroy/instantiate the candle but deactivate/activate instead or have a separate manager that tracks the lifetime

drifting jolt
tough summit
#

I just finished refactoring my code and testing it. I can edit the prefab inventory from the GUI, it works great with my factory and it gives me great performance checking if I have prefabs for the key in question. Just perfect! Thank you for your suggestion!!

nova summit
# nova summit Can we simplify this further? I need to apply a rotation (Q2) to an object in re...

I realised, I shouldn't actually do inverse anytime in this situation.
Reason is if I do inverse, the rotation that bind pose offers will be nullified which I actually don't want.

Instead, I need to do this.

  1. Find the rotation of a point(other end of the bone) when rotated with Bind Pose Quaternion (here Q1) -> Let's say this gave V1 vector
  2. Find the rotation of the same point when rotated with New Quaternion (here Q2) -> Lets say it gave V2 vector
  3. Now find the relative rotation required from V1 to V2 (With Quaternion.FromToRotation) -> Let's say Q3
  4. Apply transform.rotation = Q3 * Q1; //Apply initial bind pose followed by the relative rotation required to move V1 to V2.
    The key here is using that vectors (as points) so that, it still maintains the bind pose perfectly!
    Let me try implementing it! 😎
earnest heron
#

Hey guys, I'm stuck on something about Zenject/Extenject. Any one has any idea how I can fix that ?

I have Player gameObject with Game Object Context which instantiate Character prefab by factory and Charcater has Game Object Context. In CharacterController which is a facade class on Character I instantiate a few Scriptable Objects in this way:

private readonly DiContainer _container;

public ZenjectResourceFactory(DiContainer container)
{
    _container = container;
}
public Object Instantiate(Object @object)
{
    Object instance = Object.Instantiate(@object);
    _container.QueueForInject(instance);
    return instance;
}

In the Character Installer CharacterBehavior and CharacterPowerup are bound by Container.Bind<CharacterBehaviorContext>().AsSingle().NonLazy(); and Container.Bind<CharacterPowerupContext>().AsSingle().NonLazy();

But the issue is CharacterBehavior and CharacterPowerup are not injected into those Scriptable Objects [Inject] methods.

regal olive
#

@undone coral Could you help me?

stiff hornet
fresh salmon
#

(also that user has left the server)

regal olive
#

@stiff hornet thanks

#

@stiff hornet Could you help me?

fresh salmon
#

lmao

regal olive
#

@fresh salmon lol, Could you help me?

fresh salmon
#

Can you read mate?

#

Doesn't seem like it

#

Do not ping or reply to people who are not already talking to you

#

ie. don't ping specific people for helping with your question

regal olive
#

okay, i see

gritty python
#

Does anyone knows how do i rotate bow towards left hand?

I want to rotate it for the string to always stay on left hand but only on local z axis

#

Is it possible?

#

Maybe using Quaternion.LookRotation?

devout coyote
drifting jolt
#

The reference hmmmmm

dusty wigeon
gritty python
#

But if bow rotation does not match then string is not straight

#

at some frames

#

this is what i want to fix

#

If i rotate bow a little it will look better

dusty wigeon
#

That is why I say you can use inverse kinematic

#

It will make the adjustment for you

#

Welcome to this in-depth Unity tutorial on utilizing the powerful Two Bone IK Constraint for advanced animation rigging in #game development! In this tutorial, we will delve into the world of #Unity, focusing specifically on Animation Rigging and how to effectively use the Two Bone IK Constraint to create realistic and dynamic character animatio...

β–Ά Play video
gritty python
#

with IK

#

it will move the string

#

at same position where arrow is

#

the string will look wrong

dusty wigeon
#

The arm move, not the string

gritty python
#

like that

dusty wigeon
#

Bro, the arm move

#

Why are you moving the string

gritty python
#

I`m using animaation rigging package

dusty wigeon
#

Yes, then set up it to move the arm, not the string

tough summit
earnest heron
timber shadow
#

So I was trying to do some benchmarking and was seeing some odd results in my specific test, so I created a super slimmed down test. In my case, I had two separate tests running inside a function X times and was spitting out the elapsed time from diagnostic stopwatches. The weird thing I'm seeing is the second one is consistently 3 to 5 times faster than the first one and in my test it's super strange as it's the same code in both now.

#

Seeing as this makes me doubt any tests I write to generate comparison, what is the failure in my construction which would cause this?

#

Considering it could simple be the batches are too small so it's simple error in resolution.

#

Any ideas?

tall ferry
timber shadow
#

This makes sense

heavy sky
#

am currently done with my project and I have tried to build it and put it online. I use playerPrefs to make sure that everytime the player hits the finish on the current level he is playing, the button to the next level becomes interactable. In the editor everything works fine, no errors, but every time I build my game I get this "unable to find player assambly : library/playerscriptassemblies/unityengine.testrunner.dll" warning and when I open my build everything seems fine until I play the game and the playerprefs arent working, so the buttons stay uninteractable, even though i hit the finish. I have spend a whole day trying to fix this but i cant find nothing. I have no idea how to fix it. Can someone help me?

untold moth
dusty wigeon
#

To be honest, the usuage of PlayerPrefs for save data is not a good idea.

#

However, it should work.

untold moth
# heavy sky

Try deleting your library folder.
Also, I'm not sure what that assembly is for and why it needs it. Is it the unity built-in tests package?πŸ€”

#

Why is it in player assembly?

#

Kinda feels like something is wrong with your solution setup.

heavy sky
untold moth
heavy sky
dusty wigeon
#

What package do you have installed ?

untold moth
dusty wigeon
#

Also, it seem that the antivirus might have prevented the download of the package.

#

You might want to get it manually. Some people are saying that it can be found in Temp/

#

However, you might just as well remove the test package

#

There is also some people that point out that you might have been infected with a virus and that the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor does not point to a valid command processor. (try to open a command prompt)

twilit grove
#

Everytime i open up visual studio it lags out my computer a frick ton. Its only using about 2-3gb of ram and i have like 10 available, and the CPU barely goes above like 30%, but it keeps lagging everything the **** out, to the point where i usually end up quittin my project after my computer freezes for like 2-3 minutes, and im just barley allowed to end the task from task manager. POTENTIAL CAUSES:

I recently deleted a lot of junk scripts which werent needed, but they are still referenced in the scene so theres a lot of warnings popping up whenever i load the scene, is there a way to automatically delete all of these? cause theres like 80 sumthing warnings and i really dont want to go through ALL of them.

I added my first script assmbly Project.Extern to the project.

The visual studio didnt even connect to unity correctly at first, i had to do some shenangans to get correct sytax highlighting.

Anyways, if you can help me, im down to help you out in return, as this has stopped my passion project from being worked on and its a real bummer.

haughty rapids
#

How can I go from A to B?

Currently, I have a script to generate a cone mesh, and a shader for the material which does the ground intercept, and a fresnel, with a light opacity on top, which I'm pretty happy with, but I just realised I also have to deal with culling as well.

Not sure if this is easily achievable? I don't need a collision mesh, since I can just raycast anything in the original cone

scenic forge
dusty wigeon
# haughty rapids How can I go from A to B? Currently, I have a script to generate a cone mesh, a...

You can, try to simulate the visibility like a light, with something similar to shadowmapping. (Render the scene at the position of the view point - record depth value - for each pixel, sample the texture than decide if it is either seen or not)

An other approach would be to raycast on every vertex from the point of view and create the appropriate geometry that represent the zone.

And, you could also divide your play ground in multiple little tile to simplify the problem and check if the tile is visible.

https://en.wikipedia.org/wiki/Shadow_mapping

#

There is also a ton of asset on the asset store.

wheat patio
#

How do I get a GameObject into an editor window?

novel plinth
wheat patio
#

I meant, like being able to get a reference to a GameObject in something like this:

novel plinth
#

most runtime apis work just fine in edit-mode. yo can just get the gameObject with Find

#

or if you're using 2023 you can use var someT = (T)FindFirstObjectByType(typeof(T));
depends on your use case the latter may not what you want

wheat patio
#

Well, I kind of want to be able to drag and drop the GameObject reference in the editor window itself. Any way to do that?

novel plinth
#

With uitoolkit you can use ObjectField for that then define the objetType then enable the sceneObject property

#

can't say much if it's imgui

real blaze
frozen flax
#
    [ClientRpc]
    private void InvokeClientRpc()
    {
        foreach (var client in NetworkManager.Singleton.ConnectedClients.Values)
        {
            if (client.PlayerObject != null)
            {
                MyPlayerScript playerScript = client.PlayerObject.GetComponent<MyPlayerScript>();
                if (playerScript != null)
                {
                    playerScript.MyMethod();
                }
            }
        }
    }``` 
Will this work? On each client function mymethod will be called? I can later use this on stuff like red zone is moving!
dusty wigeon
frozen flax
dusty wigeon
#

You literaly just need to call the RPC.

frozen flax
#

They just use debug log

dusty wigeon
#
[ClientRpc]
void PongClientRpc(int somenumber, string sometext) { /* ... */ }

void Update()
{
    if (Input.GetKeyDown(KeyCode.P))
    {
        PongClientRpc(Time.frameCount, "hello, world"); // Server -> Client
    }
}
#

It cannot be more clear

frozen flax
#

I mean accessing player script rather than just debugs

dusty wigeon
#

I have no idea what you are talking about.

frozen flax
#

From beginning

#

Server call client rpc with debug log red zone advancing

#

Now rather than debugging I want to get client's script

dusty wigeon
#

Then do GetComponent

#

You can do anything that you do normally without the client/server architecture.

frozen flax
dusty wigeon
#
[ClientRpc]
void PongClientRpc(int somenumber, string sometext) { 
  Player player = GetComponent<Player>();
}
#

Considering that you have a player component at the same place of your networkcomponent

frozen flax
#

Ah, I forgot to mention that the script is on red zone not player. That's why it is harder

dusty wigeon
#

This has nothing to do with networking. Simply get the player of the game. There is an infinity of possibility to do that.

#

You can use [SerializedField], Singleton Pattern, GameObject.Find, etc.

frozen flax
dusty wigeon
#

And ?

frozen flax
#

Just simply find objects of type and then call function?

dusty wigeon
#

Basically.

#

Not really the best practice, however it should work.

frozen flax
balmy sentinel
#

Need some help with this, can't find the solution:
Canvas can't be seen and searched about the graphic rebuild loop, and i don't use any plugins, connections or databases, just a unity project. Maybe the OnValidate used incorrectly can cause this problem?

dull kestrel
balmy sentinel
#

Well actually didn't use it, gonna check it, but it solves some of this problems with the main thread?

#

Just to know

dull kestrel
#

It would be wrong to falsely guess

patent bear
#

I believe the UI Toolkit performance benefits are in Editor over imgui and not necessarily over Canvas/uGUI

scenic forge
#

Overall the tech just seems like it’s not quite there yet.

burnt hamlet
#

to my understanding this should create a 2D array of this datatype, right?

dull kestrel
#

Thought I'd recommend using a single dimension array

burnt hamlet
#

its for a grid hence the need for a 2D array

#

so that, for example, if I want it to check a tile to each side of it, all that need be done is using the position values of the list like x and y coordinates

dull kestrel
errant halo
#

I want to create a terrain/biome system for my game, and I just want to divide my terrain into square chunks and then texture each part of the terrain randomly. How would I assign these textures? (paint the terrain from code)

#

here is my current code, that im just drawing gizmos with: ```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class MapGeneration : MonoBehaviour
{
//Create a 25x25 map, each unit is 100 unity units
//2500 by 2500 terrain

public int gridSize = 10; // Number of divisions in each dimension
private Terrain terrain;
private Vector3 terrainSize;

void Start()
{
    terrain = GetComponent<Terrain>();
    terrainSize = terrain.terrainData.size;

    DivideTerrain();
}

void DivideTerrain()
{
    float squareSizeX = terrainSize.x / gridSize;
    float squareSizeZ = terrainSize.z / gridSize;

    for (int i = 0; i < gridSize; i++)
    {
        for (int j = 0; j < gridSize; j++)
        {
            float startX = i * squareSizeX;
            float startZ = j * squareSizeZ;

            // Draw Gizmo for each square
            DrawGizmoSquare(new Vector3(startX, 0, startZ), squareSizeX, squareSizeZ);
        }
    }
}

void DrawGizmoSquare(Vector3 position, float width, float height)
{
    Gizmos.color = Color.red; // You can change the gizmo color to your preference.
    Gizmos.DrawWireCube(position + new Vector3(width / 2, 0, height / 2), new Vector3(width, 0.1f, height));
}

// This gizmo will be drawn in the editor to visualize the grid
void OnDrawGizmos()
{
    if (terrain == null)
        terrain = GetComponent<Terrain>();

    terrainSize = terrain.terrainData.size;
    DivideTerrain();
}

}

dull kestrel
errant halo
#

the randomness logic i can figure out but for now i guess just do like a Random.Range(1,10) and each of those numbers should be assigned toa texture

tawny holly
#

has anyone had the situation where Network Object's are not removable from a game object (NGO). i accidentally added one, can't remove it now

wary vector
# errant halo I want to create a terrain/biome system for my game, and I just want to divide m...

Two ways i can think of: Set either a texture with multiple colors or vertex color in the mesh, send to the shader and them interpolates between input colors and output texture/pixels for the material/biome. Its kinda how Unity Terrain do it. You can have materials/colors interpolating smoothly.
Another way is more like minecraft like: set each mesh to use a material, split your mesh accordingly and combine meshes with the same materials. You can have a mesh with up to 32 submeshes with each using a different material.

errant halo
#

thanks! I started working on the second approach:

wary vector
#

You can use Mesh.CombineMeshes. First you create a single mesh per material, Mesh.CombineMeshes with "mergeSubMeshes" true. After you have all meshes per material, you combine them now with "mergeSubMeshes" false. This way each mesh will become a submesh, them you pass to the MeshRenderer.SetMaterials a ordered list with all the materials, the same order of your submeshes.

#

them you'll have a single meshfilter / meshrenderer, with one mesh (with multiple submeshes) and multiple materials. Its way less expensive to render. But i belive its not a single drawcall either, but is faster

burnt hamlet
#

does Application.persistentDataPathwork on every system Unity has support for?

burnt hamlet
#

I've encountered the issue that trying to create a file in that path gets denied because the folder is read only

#

it seems it wont let me even create a file inside the project itself

#

despite it having let me do so before

#

oh wait I see the issue now, for some reason it created a folder instead of a file

real blaze
#

is it bad practice to make a component resolve it's component dependencies in Awake with no prior RequireComponent?

#

I want to get a component of an interface, say, ITestThing but Unity can't expose an Object field of that type

hardy jacinth
#

I don't think so, Required Component is just a convenience field adding other components when you first add the component to the object iirc

#

Iirc it doesn't even work if you add it later to existing component on the object

#

It's good for anyone who is reading the code though

hardy jacinth
flint sage
#

It's just bad UX, just do proper error handling/warnings etc

real blaze
hardy jacinth
#

I believe when they describe the lifecycle events

#

You have to remember though that different lifecycle stages can do different things to components

real blaze
hardy jacinth
#

Can you describe in more detail what you want to do?

real blaze
flint sage
#

I think you pinged the wrong comment or you're reading way too far into my message πŸ˜›

real blaze
hardy jacinth
#

I don't think it will work.

flint sage
#

I'm saying it's fine to use interfaces, just throw a proper error if it's missing or write a custom editor that properly show it

hardy jacinth
#

GetComponent returns derives of components

#

Iirc

#

Check the return type. Doesn't GetComponent return objects of base class Component or MonoBehavior only ?

real blaze
real blaze
flint sage
#

Yeah it's fairly common

real blaze
#

yeah no constraints on T

proper rock
#

Hey there! I'm trying to translate an existing Unity game to my native language. The strings are stored in form of txt files within StreamingAssets folder so they can be easily modified without any patching of game assets but the issue is that when I open the game, the cyrillic letters are being displayed in different font and some language specific letters are displayed as squares. I've managed to identify and extract the font file and confirmed that all the required characters are actually present in the font itself so it has something to do with Unity font asset. I've done some digging in the internet and seems like TextMeshPro requires to specify either dynamic font type or explicit character range that should be supported and I think that's the case, because I've used UnityExplorer by sinai-dev to modify some menu labels directly in game at runtime and as soon as I've replaced latin characters with cyrillic ones, I've noticed that font changed automatically. Has someone had experience with translating existing Unity games including font adjustment? What could be my options? There is some way to create a new unity font asset and override the original one either by loading it using injected DLL or by somehow overriding it with config file of TMP but I didn't found some described ways of doing that sadly.

dusty wigeon
scenic forge
#

A related question, how do you deal with user generated content in CJK, with TMP?

flint sage
#

You don't use an SDF πŸ˜›

dusty wigeon
#

Like if people can see every language ?

scenic forge
scenic forge
dusty wigeon
#

You can use dynamic font, this was made for that.

flint sage
#

IT also has dynamic atlassing now

#

So it's generated at runtime for whatever you need

dusty wigeon
#

It is better for user content generated I believe.

scenic forge
#

Cool, I'll give it another shot sometime, it was the blocker for me moving to TMP.

dusty wigeon
#

Oh yeah, it might have been the text component.

scenic forge
#

The gist of the forum exchange was that I want to use the exact system font without specifying anything about the font face, but the reply seems to imply that TMP dynamic font was designed in a way that you need to specify some properties of the font face so it searches the system fonts to find one with closest match, which is not what I want.

dusty wigeon
#

Anyway, as stated by the post, this is not a good practice for quality reason.

scenic forge
#

Eh I agree it's a bit unusual of a use case, as for most games you do want precise control of the font so it fits your game's visual design.

#

My game is very heavy on user generated content to the degree that it's almost like a social media app, so I suppose it's not unreasonable that this use case isn't supported.

dusty wigeon
#

Why would you want to use the user system font ?

#

Is it because you want to capture all the possible character ?

#

Also, wouldnt that means that in some case, people wouldnt be able to see all the character, by example, if the system font does not include Chinese characters.

scenic forge
#

It's very heavy on texts and it makes the most sense for user to be able to use their system font for comfortable reading (customizing system font is pretty popular in CJK speaking regions, especially Android)

#

As for the latter concern, on my iOS and Android devices at least they are able to display CJK just fine even with system language set to English.

twin sinew
#

Hey guys,
Any recommendations as to how one might go about implementing pathfinding in a non-grid-based game, but still on a 2D surface?

dusty wigeon
tiny pewter
#

nav mesh

scenic forge
fallow patio
#

So I have an unusual issue that couldn't be solved in #πŸ’»β”ƒcode-beginner last night. It's a 2D isometric Z-as-Y grid with 4 tilemaps in it, each with their own render order. Terrain is 0, highlight is 1, improvements is 2, and structures is 3. My intent is that when I hover over a tile, that it sets the tile at that location in the highlight tilemap to the highlight tile, clearing the previously highlighted tile.

The problem I had was that it rendered nothing in the highlight tilemap. I double-checked that I could draw to it with the palette, which worked fine and rendered fine during runtime. Someone suggested manually setting the Z, which I set to 0, and it finally rendered... 10 tiles above the map. I could drop the Z all the way to -9, and it would only be overlapping a half-diamond, or 1 tile height, but when I dropped it to -10 (which it turns out was the previous default), it wouldn't render at all. Furthermore, upon adding a feature where I could destroy or place tiles with left or right click, it worked up until -10, at which point it would do absolutely nothing while not highlighting anything.

It is worth noting that the camera transform location is, by default, set to Z = -10. When I set this to -11, I can render my highlight at -10 but it is again a half-diamond off of the tile I am hovering. For this reason I believe it to be directly related.

The World container is all 0's for position. The Grid inside it is the same, as well are the 4 tilemaps inside the grid.

#

My code is as follows:

void Update()
{
    Vector3 mouseOrigin = Input.mousePosition;
    Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(mouseOrigin);
    Vector3Int tileCoordinate = highlightMap.WorldToCell(mouseWorldPos);
    tileCoordinate.z = 0;
     if(tileCoordinate != previousTileCoordinate)
    {
        Debug.Log("Coords: "+tileCoordinate);
        highlightMap.SetTile(previousTileCoordinate, null);
     highlightMap.SetTile(tileCoordinate, highlightTile);
        previousTileCoordinate = tileCoordinate;
    }
    if(Input.GetButtonDown("Fire1")) {
        terrainMap.SetTile(tileCoordinate, null);
    }else if(Input.GetButtonDown("Fire2")) {
        terrainMap.SetTile(tileCoordinate, grassTile);
    }
}```
What am I missing that is causing this vertical offset?
scenic forge
# scenic forge Ah TIL universal font is a thing.

I suppose I'll dwell on it for a bit, right now I'm still using legacy text because of the ability to always use system font. Fortunately I can fairly easily migrate to TMP, mostly just not sure about the loss of being able to use system font.

fallow patio
nova summit
heavy sky
#

i have a problem again. so i just uploaded my game to gamejolt and itch.io but when i try to download it on other devices, it says that there is a virus detected in exe, but when i download it on my laptop I just get a warning and then i could download it with no problem. i have already checked on mallwares and other stuff but i cant find anything. how can i fix this?

regal olive
#

How does unity takes that info at PlayerLog.txt? And how can i take them too? I searched about it and found out this could be a Native Plugin that acts like a logger. Or maybe the CrashHandler does that its unclear. Maybe someone has a knowledge for that?

Note: Do not tell me Application.logMessageReceived please. We are talking about a log that actually logs even hard crashes~~ and not Debug.Log's except the Debug.LogException()~~

Initialize engine version: 2022.3.7f1 (b16b3b16c7a0)
[Subsystems] Discovering subsystems at path D:/Test/UnitySubsystems
GfxDevice: creating device client; threaded=1; jobified=1
Direct3D:
    Version:  Direct3D 11.0 [level 11.1]
    Renderer: XX
    Vendor:   XX
    VRAM:     XX MB
    Driver:   XX
Begin MonoManager ReloadAssembly
- Loaded All Assemblies, in  -0.129 seconds
- Finished resetting the current domain, in  -0.0000000000000000001 seconds
D3D11 device created for Microsoft Media Foundation video decoding.
<RI> Initializing input.

New input system (experimental) initialized
Using Windows.Gaming.Input
<RI> Initialized touch support.

UnloadTime: -0.682900 ms
Unloading 4 Unused Serialized files (Serialized files now loaded: 4)
UnloadTime: 1.161000 ms`
lilac lantern
#

Takes what info? You mean sends output messages?

#

Because to my knowledge unity just directs the console output to a file so stack-traces and exceptions and such are printed there before application exits in the case of a crash.

regal olive
# lilac lantern Because to my knowledge unity just directs the console output to a file so stac...

You're right normal logs and exceptions do goes to log with Stack Trace. Today i did some tests on Crashes, Exceptions and normal Logs. From there, a crash wont be sent to a normal log somehow. I also hope the same thing as you before searching about those. Sending a crash report before exiting app would be perfect but maybe that is not possible because a crash is literally shutdown the app proccess even if the app is sending crash report to log. But i see no examples, no documentations for that. I saw that a signal is goes to somewhere after a crash occurs. There is a operation called Crash Chain for Android builds. After a crash occurs, it goes to desired CrashHandler first. After that, it goes to next until there is no more. I dont know how other platforms do that but i do know it is done by UnityCrashHandler64.exe for them. I think i will search this even more deeper.

lilac lantern
#

so your build is crashing without a log?

regal olive
#

No no it goes to Player Log. I just dont know how will i know if a crash occurs and get logs from them. If i know how Player Log is getting those logs, i will be good to go. Player Log is currently not working for Android so that is why i need that. I dont know if they did some improvement on 2023

tender gust
#

what would be faster for handling a lot of AI mobs? Using Awaitable type or Jobs?

#

I kind of like the flexibility Awaitable offers by allowing you to jump in between threads

sly grove
#

You won't be able to access any Unity objects from other threads.

#

C#'s await async stuff does nothing to alleviate this.

upbeat path
tender gust
tender gust
upbeat path
#

ah, lazy, got it

tender gust
sly grove
sly grove
#

well it depends exactly what you want to do with them.

tender gust
#

well like update position, play animations

sly grove
tender gust
#

thanks

proper rock
#

is there any ingame method to call in order to reload StreamingAssets directory content without closing the game? I'm translating it so it would be handly to get changes picked up live by calling some method instead of restarting game completely

quasi bluff
sly grove
quasi bluff
#

"* What went wrong:
Execution failed for task ':launcher:packageRelease'.

A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
com.android.ide.common.signing.KeytoolException: Failed to read key AndroidDebugKey from store "C:\Users\changeditonpurpose.android\debug.keystore": Invalid keystore format"
I do not have an android debug key

quasi bluff
#

No i definitely have not

#

Im gonna search how rq

quasi bluff
#

Got it working my friend ty

stoic otter
#

so i have a few structs what i want to save but if i save one there isnt a framedrop only when im writing 2 stucts the game will lag for a good second

#

is writing to application.persistdatapath not good for preformance of something?

#

this is how i write to the path

tall ferry
spiral zenith
#

And if all three take too much time, than you need to save less data 🀷

clever urchin
#

Ideally you'd use something like UniTask but regular threads work fine too

stoic otter
novel plinth
clever urchin
#

Implementation details πŸ˜…

sly grove
stoic otter
#

aa alright didnt knew that

twin sinew
#

How can I prevent the "Reloading script assemblies" occuring every time a change is made to a script?

sharp monolith
#

Hi, i am making a vr game where an ai is attached to a rope you can swing around. i have made both the ai and the rope (blender so it is dymaic) as seperate entities, but when i try to join them together using joints, the ai glitches and cant be picked up. i need any forces enacted on the rope to affect the goblin (like it being spun) and vise versa (when the goblin is picked up, the rope will dangle). my only other thought is making both as a single object in blender, but i dont really have the skills for that, so im wondering if anyone knows any other ways to attack the objects. ive tried joints, using an empty game object as a go between, parenting, and even a rope renderer, so im all out of ideas, thanks!

stoic otter
#

but be aware

twin sinew
#

Oh great, thanks! The internet said there were some side effects to this?

#

Ahh here we go

stoic otter
#

reset all the static variables in your script

#

because static variables will not be resetted when you do this

#

things like singletons

twin sinew
#

Alrighty, thanks for that(:

stoic otter
#

no problem πŸ™‚

#

is there a function that will be called when you put a component in the editor on a gameobject

#

like a constructor or something?

sly grove
#

though you may consider Awake() the runtime "constructor" for your component

stoic otter
#

thats only when you change variables in the editor right?>

sly grove
#

it runs when you create the thing, when you draw the inspector, and when you change variables

stoic otter
#

aa alright

sly grove
#

maybe that's what you want

stoic otter
#

well close but not what i wanna do

#

i have a checkpoint system with UniqueIdentifiers which would be generated when you add it to a gameobject in the editor

sly grove
#

Reset sounds like a perfect place for that tbh

#

potentially also some logic in awake to cover those created at runtime

stoic otter
#

well i dont want to generate it in runtime

#

but in editor

#

when you add a component to a gameobject

sly grove
#

it does exactly that

stoic otter
#

well no it doesnt

#

when i add the checkpoint script to it

#

it doesnt generate it

#

?

sly grove
#

Reset is called when the user hits the Reset button in the Inspector's context menu or when adding the component the first time.

stoic otter
#

thats really strange wait

#

sorry im a idiot

#

i get it haha

solar condor
#

Hey there!
I'm trying to understand some Compute shaders concepts, so I made this:

#pragma kernel CSMain 

RWStructuredBuffer<float> _Positions;
RWStructuredBuffer<float4> _Out;

Texture2D<float4> _InputTexture;
SamplerState _Sampler_InputTexture;

int _CubesPerAxis; 
float _Time;

bool IdBelongsToGrid(uint3 id : SV_DispatchThreadID)
{
    return !(id.x > _CubesPerAxis - 1 || id.y > _CubesPerAxis - 1);
}

int indexFromId(uint3 id)
{
    return id.x + _CubesPerAxis * (id.y + _CubesPerAxis * id.z);
}

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    if(!IdBelongsToGrid(id))
    {
        return;
    }

    // Assign random value
    _Positions[indexFromId(id)] = sin(3.0f * _Time + (id.x + id.y) / 7.0f );

    uint width, height;
    _InputTexture.GetDimensions(width, height);

    //float2 uv = float2(id.x / float(width), id.y / float(height));
    //float2 uv = float2(id.x, id.y);
    float2 uv = float2(id.x / float(_CubesPerAxis - 1), id.y / float(_CubesPerAxis - 1));

    //_Out[id.x + _CubesPerAxis * id.y] = _InputTexture.Sample(_Sampler_InputTexture, uv);
    _Out[id.x + _CubesPerAxis * id.y] = _InputTexture[uv.x + 512 * uv.y];
}
#

This runs without compiler errors

#

but I expected it to read from a texture and then use the values which were cached by the last line:
_Out[id.x + _CubesPerAxis * id.y] = _InputTexture[uv.x + 512 * uv.y];
To then recolour some objects on runtime

#

sadly though, it seems like all the vector4 values read (0,0,0,0)

#

and I'm wondering if it's because my uv's are incorrect

spiral zenith
solar condor
# spiral zenith I'm not sure but when using a Texture2D, shouldn't you pass an int2 to access an...

I changed it to this:

#pragma kernel CSMain 

RWStructuredBuffer<float> _Positions;
RWStructuredBuffer<float4> _Out;

Texture2D<float4> _InputTexture;
SamplerState _Sampler_InputTexture;

int _CubesPerAxis; 
float _Time;

bool IdBelongsToGrid(uint3 id : SV_DispatchThreadID)
{
    return !(id.x > _CubesPerAxis - 1 || id.y > _CubesPerAxis - 1);
}

int indexFromId(uint3 id)
{
    return id.x + _CubesPerAxis * (id.y + _CubesPerAxis * id.z);
}

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    if(!IdBelongsToGrid(id))
    {
        return;
    }

    // Assign random value
    _Positions[indexFromId(id)] = sin(3.0f * _Time + (id.x + id.y) / 7.0f );

    uint width, height;
    _InputTexture.GetDimensions(width, height);

    float2 uv = float2(id.x, id.y) * 4;
    _Out[indexFromId(id)] = _InputTexture[uv] * 2.0f;

}

And now it works, kinda

spiral zenith
solar condor
#

I'm not sure, but I get the feeling that my colours are darker than they should be (hence that 2.0f * at the bottom)

#

but it could just be that the lighting is playing tricks on me

#

this is the resulting shitpost from that xD

#

and this is the texture i'm sampling

#

the cubes have lit materials from URP

#

which is what I think is causing this illusion of "darkening" the result

spiral zenith
#

Well I'm not sure but I don't see anything wrong in your code πŸ™‚

wooden cedar
#

@solar condor you can put both pictures into say Gimp and look at the histogram. But from where I'm sitting the top image has double the contrast of the bottom one (brighter brights, darker darks)

#

I find you'll get contrast from multiplication, and brightness from addition

#

You can also of course do a ratio to high-low values, to let you kind of clamp in the range if you like. Not sure if that helps any. But the top does look darker to me

wet burrow
#

What happens if you try to add a duplicate product to Unity's IAP system? Does it create another product with the same data, overwrite the original, or just do nothing? I'm planning a system that downloads product data from a database and automatically adds them to the purchase list, but I need to figure out if I have to make my own check system to prevent duplicate products being created if the same retrieval API is run multiple times.

slender stag
#

what's the best approach to create an "app library" project on unity? I'm trying to accomplish a project that can execute another projects that were made on unity, I thought about addressables and asset bundles but I guess they can't build scripts that the scene has

sly grove
slender stag
#

it seems exactly what I need, and I see that works on Android, this would also work on Oculus/VR platforms too?

#

I will try so, thanks

worthy rose
#

Yeah so I have an oculus app written in native and was considering making a unity companion app to configure settings. Could I instead just wrap the entire app inside unity 🀯

upbeat path
#

no, you would wrap UnityPlayer inside your native app

worthy rose
#

So I could use that as like an imgui alternative for example

upbeat path
#

yes

worthy rose
#

Sick that makes my life a lot easier ty

tender crest
#

Hey, would anyone want to help with some rotations and a bit of gimbal lock?

stoic peak
#

I asked this over in networking but figured I'd ask here as well. Anyone know an efficient encryption algorithm to be used in multiplayer networking? It seems like ECDSA (ECC) is pretty efficient, but idk if it's fast enough for constant encryption/decryption for a unity mulitplayer transport

tender crest
#

I'm making a "module-based" procedural generator. Each prefab (module) has some anchor components that I place at the desired connections for a module to have. This class just exposes a reference to a Transform (usually itself) that will tell what rotation an anchor has and where it is within the prefab.

#

When instantiating a new module coming from another I need to:

  1. Gather the other's anchors
  2. Position the new module so that anchors align
  3. Test for collision/bounds-check with already placed stuff

If step 3 is satisfied, we need not to test more positions and rotations and we are done

#

Figuring out the relative position from an anchor to its root to match with adjacent modules is easy

#

But when it comes to rotation, although I thought I had successfully tested against all tricky rotations (I only did for planar rotations, oops), it failed when i tilted the "exiting/entering" anchor downwards

#

I'll post the snippet of what I calculate to get rotations

#
Vector3 anchorNormalAxis = Vector3.Cross(_connectionAnchor.Transform.forward, connectionAnchor.Transform.forward);

float anchorAngleDifference = Vector3.SignedAngle(_connectionAnchor.Transform.forward, connectionAnchor.Transform.forward, anchorNormalAxis);

instanceRoot.transform.RotateAround(connectionAnchor.Transform.position, anchorNormalAxis, -anchorAngleDifference);
tender crest
tender crest
#

Nvm, this guy's drawing skills are awesome enough (not joking) to have found an answer: https://gamedev.stackexchange.com/questions/142441/how-can-i-change-the-parents-rotation-so-the-childs-rotation-is-looking-at-a-spe

real blaze
#

hey. the model has fine depth in scene view, but in game it's sometimes wrong, like in this picture. any idea why, and how to fix it?

flint sage
#

Write a better shader?

real blaze
#

just checked, they're using the standard shader

thin mesa
#

this is a code channel

real blaze
#

I'm making the camera render to a renderTexture

// set rt to camera
if (camera.targetTexture != m_renderTexture)
    camera.targetTexture = m_renderTexture;

then using that texture in my UI. that's the part I'm suspected about

real blaze
#

because the same model doesn't have any problem in normal camera with targetTexture set to null

real blaze
#

alright solved.
problem was I as passing in 0 as depthBuffer argument to RenderTexture.GetTemporary(...) as a result of a serialization issue

old swallow
#

Anyone here who managed to copy an image to the clipboard?

earnest heron
#

Hey guys,
I'm trying to replace Zenject/Extenject with VContainer.
Anyone knows what are the equivalents of these lines in VContainer ?
Container.Bind<IState>().To<Idle>().FromResolve().When(context => string.Equals("startState", context.MemberName)
Container.BindInstance(_debugStateMachine).WithId("debug")

jolly token
#

Zenject is like C++, it tries to let user do everything, even if it is verbose and not really IoC container’s responsibility.

#

I’d advise to restructure your code to make DI relatively plain

earnest heron
earnest heron
strange ice
#

I'm trying to create a modular system where I can call a void on a script no matter which script it is

So there is a script specific to a certain class, with a void called "MainAbility"

I want to be able to call "MainAbility" on whichever class script is attached to the gameobject without referencing the script directly. I doubt this made any sense though because I'm not 100% sure how I would do this or what it's called

#

Like for examples there'll be a class called Overdrive, with its own Overdrive script to do its abilities

And another class called Chained

Both of them will have a void named "MainAbility" that will act differently to do their specific skills. But I want to be able to call it from another script called "ClassManager" which will always be on the same gameobject no matter which class it is. So the ClassManager would just have a function that calls the "MainAbility" void on whatever class script is attached to it at the moment

#

ScriptableObjects might be able to do this but I don't know how to store a void in a SO then call it from the ClassManager script. I'm kinda lost with this system I'm trying to do

half swan
#

You may want Interfaces

Also, they are called methods. Void just means a method that return nothing

#
strange ice
#

k i'll look into that

#

and thanks

keen glade
celest socket
#

Hi, I'm in the process of creating a procedural tile system, and I'm trying to figure out how to do cell blending. Currently my plans for the tile mesh is looking like this, and as far as I'm aware, extruded edges is a must for blending with vertex colors. My question is, is there any way of laying out the topology of the mesh more efficiently than this?

#

18 triangles per tile seems a bit extensive

sage radish
#

Usually extra vertices are cheaper than a heavier fragment shader, and it doesn't scale with screen resolution like the fragment shader does, but we are talking about 9 times as many triangles, and 4 times as many vertices.

celest socket
#

yeah it does seem expensive. I'll look into the shader approach, thanks

sage radish
#

But you could optimize that by only generating extra vertices where blending is actually needed between tiles.

limpid prairie
#

Anyone here worked with UniWebView?

I load a webpage with UniWebView, but my phone lets me scroll left and right on this webpage, but I don't want it to.
I want the webpage to condense or do whatever it needs to fit inside the UniWebView frame. Anyone know how to fix this?

ivory atlas
#

Hello!
I am getting diff's in meta files when I import a package.
It is a one-line change, that is just adding a line break on some random line in the meta file.

I am wondering there is some editor config that I'm not aware of that modifies how meta files are saved.

Example Diff

- lastHumanDescriptionAvatarSource: {fileID: 9000000, guid: 27c982f567720f244990071a534fbbe7, type: 3}
+ lastHumanDescriptionAvatarSource: {fileID: 9000000, guid: 27c982f567720f244990071a534fbbe7,
+    type: 3}
real blaze
ivory atlas
hardy jacinth
#

Maybe you have some formatter option in your IDE which does that for yaml files

#

And Ignoring meta files is disabled

#

Something like "break long lines"

real blaze
ivory atlas
ivory atlas
#

It happens consistently for others devs too

real blaze
#

@ivory atlas
that happens with every asset coming from artists' ? if that's the case, then since there are multiple editors acting, check that this setting is synced across all your editors

remote drift
#

Is there a way to add additional compiler defines to build when I build from Files-Build Settings button?

#

I don't want those defines to be inside Editor

#

only during build

ivory atlas
real blaze
remote drift
#

conditionally

#

if I'd create BuildPlayerOptions struct myself I'd do

                extraScriptingDefines = new[]
                {
                    BuildDefine, ClientDefine
                }
#

But instead I want to add additional defines to build which is called by built in build button

ivory atlas
#

Actually ignore me

real blaze
# remote drift if I'd create `BuildPlayerOptions` struct myself I'd do ```cs e...
#

if you can afford to, you can invest time on creating a custom build pipeline

remote drift
#

ah, just static method

#

but this is exactly what I was looking for, thanks

real blaze
#

oh, ok, glad it was helpful

remote drift
#

and it's also public, nice!

cerulean minnow
lean orbit
#

is it ok to ask questions about code relating to multiplayer implementation through steamworks.net here ?

tall ferry
tender crest
#

Hello. I can't do some profiling rn but does anybody know which part of these two for loading an image from memory is the most intensive? Is it ImageConversion.LoadImage or the I/O deserialization (e.g. FileStream.ReadAllBytes)?

sly grove
#

"intensive" might not be the right word though

#

More like "takes the longest amount of time", the CPU would likely be idle for most of the operation.

sleek terrace
#

I am making an instance shader

I have the following Instance Data struct,
How do I access the properties in the shader though, I am using the default code from unity website, but I have no idea what is going on

sly grove
sleek terrace
#

hmm

sly grove
#

I recommend reading this article to get you started. This really made instanced shaders (as well as compute shaders) click for me https://toqoz.fyi/thousands-of-meshes.html

sleek terrace
#

ive read this

#

he is using an array then changing its proper through material bloc

#

he is also usinmg the outdated drawmesh methods, im using rendermesh

upbeat path
void bluff
lean zealot
void bluff
#

so I am trying to make it so if the the text in this panel contains some of the words in the special phrase ask the correct question

#

the special phrase being the key

#

so you see how i place it is milk and it is banaana and then want to be able to ask the question

#

do you like banana and milk

#

see you how it has the special key

#

make sense?

#

this code snippet from dialogueTrigger is me trying to do the check

 if(!(string.IsNullOrEmpty(Clues_Combined_1_text.GetComponent<TMP_Text>().text)) && !(string.IsNullOrEmpty(Clues_Combined_2_text.GetComponent<TMP_Text>().text))) 
                {
                    if(line.Contains("[KEY"))
                    {
                        string special = line.Substring(0, line.IndexOf(']') + 1); // special = [KEY=Strawbery & Milk]
                        special.ToLower();
                        Debug.Log(special);
                        Debug.Log(Clues_Combined_1_text.GetComponent<TMP_Text>().text);
                        Debug.Log(Clues_Combined_2_text.GetComponent<TMP_Text>().text);

                        if (special.Contains(Clues_Combined_1_text.GetComponent<TMP_Text>().text) && special.Contains(Clues_Combined_2_text.GetComponent<TMP_Text>().text))
                        {
                            Debug.Log("Correct Question");
                            string curr = line.Substring(line.IndexOf(']') + 1); // curr = Do, ...
                            Debug.Log("curr is " + curr);
                            dialogue.Enqueue(curr);

                        }
                        else
                        {
                            Debug.Log("Wrong Question");
                        }
                        //string curr = line.Substring(line.IndexOf(']') + 1); // curr = Do, ...
                        //dialogue.Enqueue(special); // adds to the dialogue to be printed
                        //dialogue.Enqueue(curr);
                    }
lean zealot
#

I'm thinking maybe you should think of switching to using JSON? Using strings and txt files for this data seems difficult to deal with

void bluff
#

so create a json file that has the questions in it and read it in

lean zealot
#

It's easier to compare in a way I think

#

JSON structure should allow you to safely put everything in a list or something so you can easily access the data

void bluff
#

alright ill do that then try again

#

becuase look at the debug.logs everything works as intended

#

u see how the key is correct and it accesses the panels text

#

but the comparrisons dont work for some reason

lean zealot
void bluff
#

thx man

upbeat path
void bluff
upbeat path
#

no, that is not how it works

#

it is comparing the whole source string being contained in the destination string

lean zealot
#

Now SteveSmith pointed it out I see what's the issue

upbeat path
#

try this

string text = Clues_Combined_2_text.GetComponent<TMP_Text>().text;
string[] textArray = text.split(" ");
foreach (string s in textArray) {
if special.contains(s) { // found }
}
void bluff
#

ok will do thx

lean zealot
#

To explain what is happening exactly what you're doing is:
You're comparing "[KEY=Strawbery & Milk]" with "this is milk", which is not a valid comparison as "this is milk" will not contain "[KEY=Strawbery & Milk]"

void bluff
#

not in its individual words

void bluff
lean zealot
#

Yes, what you should have been doing is separating "[KEY=Strawbery & Milk]" into two separate words as "strawberry" and "milk" as two different words to compare

lean zealot
#

But I highly recommend you recode this with JSON, in the long run it's gonna be messy

void bluff
#

yes I shoud be able to but I also need to display the question and then print the answer

void bluff
void bluff
upbeat path
#

yes, of course you do, you don't expect me to do all the work for you do you?

void bluff
upbeat path
#

it's your code you should not need to check with me

lean zealot
void bluff
#

alright thanks

void bluff
upbeat path
#

Text or CSV files for unstructured data, Json or another format (XML) for structured data

#

if it needs to be user editable

lean zealot
#

πŸ‘†

void bluff
#

th

#

thx

lean zealot
#

Good luck with the game πŸ˜„

void bluff
#

thx

real blaze
#

hi. how do I access private variables of a Unity native class? Camera specifically

flint sage
#

Reflection

upbeat path
#

Reflection

real blaze
#

yeah doesn't work

upbeat path
#

oh yes it does

real blaze
#

i guess since it's native and calls c++

#

tyepof(Camera).GetFields(BindingFlags.Instance | BindingFlags.NonPublic) returns zero lengthed array

upbeat path
#

thats a typo

real blaze
#

still in the immediate window, can try new ideas

flint sage
#

Dude you provide no details and expect us to have a magical answer to a question we don't know

real blaze
#

question was how to access private fields of a Unity native class like Camera

upbeat path
real blaze
#

of course instead of typeof I have an instance and then GetType() on that instance

#

any solution is appreciated

upbeat path
#

Do you know why GetFields doesnt work?

real blaze
#

?

upbeat path
#

Because Unity implements almost all of their fields as Properties

real blaze
#

that's true, setters and getters goes to native code

upbeat path
#
PropertyInfo[] properties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
real blaze
#

appreciate the help mate, but I was looking for a way to access the FieldInfo, setting field values directly without calling to properties

flint sage
#

SerializedProperties

real blaze
#

that requires UnityEditor namespace

#

an example of a native field wrapper, a property in C#

#

since the MethodImpl knows how to link it, there must be a way for us too, I figured

#

but can't find any references online on how to do it

upbeat path
real blaze
#

thanks. will look into it

real blaze
#

is that an inside rule for your project?

upbeat path
#

I dont want them, but you do. The K_ fields are auto backing fields

#

I did try setting the m_ fields directly but ended up with very corrupt classes

#

Unity was not a happy bunny

real blaze
#

i see

real blaze
upbeat path
#

good point

real blaze
#

well, since we're on the topic of serialization, does the IsNotSerialized bool work for all Unity serializable properties, in your experience?

#

at line 24 of the pastebin

upbeat path
#

yes

real blaze
#

ah, thats good

#

thank you

sharp pond
#

i am trying to have an image output of my in game screenshot during runtime but my image shows darker than the sprite, anyone know what is the issue from my code? ``` RenderTexture renderTexture = myCamera.targetTexture;

        Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
        Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
        renderResult.ReadPixels(rect, 0, 0);

        byte[] byteArray = renderResult.EncodeToPNG();
        filePath = Application.dataPath + "/CameraScreenshot"+ System.DateTime.Now.ToString("yy-MM-dd") +".png";
        System.IO.File.WriteAllBytes(filePath, byteArray);
        Debug.Log("Saved CameraScreenshot.png");```
#

this is the sprite before screenshot

#

this is the output of the screenshot

#

i went to change the brightness but it looks different than the original image, hopefully anyone here would know what is the issue float brightnessFactor = 1.5f; Color[] pixels = renderResult.GetPixels(); for (int i = 0; i < pixels.Length; i++) { pixels[i] *= brightnessFactor; } renderResult.SetPixels(pixels); renderResult.Apply();

umbral trail
#

might be gamma

sharp pond
real blaze
sharp pond
#

output does not seem similar

umbral trail
# sharp pond where do i change the gamma setting?

When you create the texture one of the parameters is to use linear. I suspect what you're capturing is in linear space so that should match, or there may be a way to transform to sRGB space. If you have an advanced image viewer you might be able to view the current output as linear to test.

sharp pond
umbral trail
#

pass linear as true

sharp pond
umbral trail
#

in the Texture2D constructor

sharp pond
umbral trail
#

no in your code

sharp pond
sharp pond
# umbral trail no in your code

so i change this to true? Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, true);

upbeat path
#

<@&502884371011731486>

frozen imp
#

hmm bot being lazy didn't clean up

umbral trail
upbeat path
#

That was particularly nasty

sharp pond
umbral trail
#

maybe have a look at what the render target looks like in renderdoc

sharp pond
#

my target texture is empty in inspector though

real blaze
#

(you can hold Ctrl and left click the texture field's icon area (drag n drop area) to view it in a separate window)

halcyon pike
#

need help to rotate my player toward ik

#

duringplaymode

sharp pond
real blaze
sharp pond
#

nvm guess its wrong, got an error

sharp pond
#

nothing happen after i ctrl left click there

limpid prairie
scenic forge
#

Typically you want to see:

<meta name="viewport" content="width=device-width, initial-scale=1" />

In <head> section.

limpid prairie
#

The site I am embedding was created with React code.
Let's say I find the viewport, which of those properties do I have to ensure is correct?

limpid prairie
scenic forge
#

In your browser dev tool btw, not in the source code of that web project.

rare whale
#

Any youtube videos that you guys recommend to watch to learn unity?

real blaze
real blaze
real blaze
# sharp pond what do u mean?
/// <summary>
/// Captures screenshot and returns the texture as the result. Null if failed.
/// </summary>
static async Task<Texture2D> TakeScreenshot(MonoBehaviour owner, TextureFormat textureFormat = TextureFormat.RGB24)
{
    if (owner == null)
        throw new ArgumentNullException(nameof(owner));
    if (owner.gameObject.activeInHierarchy && !owner.gameObject.scene.IsValid())
        throw new ArgumentException("Owner must be in a valid scene.", nameof(owner));
    if (System.Threading.Thread.CurrentThread.ManagedThreadId != 1)
        throw new InvalidOperationException("Must be called from main thread.");



    Texture2D texture2D = null;
    var tcs = new TaskCompletionSource<bool>();
    owner.StartCoroutine(Coroutine());
    await tcs.Task;


    if (tcs.Task.Result)
        return texture2D;
    else
        return null;

    IEnumerator Coroutine()
    {
        yield return new WaitForEndOfFrame();
        try
        {
            texture2D = new Texture2D(Screen.width, Screen.height, textureFormat, false);
            texture2D.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
            texture2D.Apply();
        }
        catch (Exception e)
        {
            Debug.LogException(e);
            tcs.SetResult(false);
        }
        tcs.SetResult(true);
    }
}
sharp pond
real blaze
sharp pond
real blaze
sharp pond
# real blaze same way as before. encode to png and write all bytes to file

i did the same as well right? i encode my renderresult then writeallbytes with my byte array and filepath RenderTexture renderTexture = myCamera.targetTexture; Texture2D renderResult = new Texture2D(renderTexture.width,renderTexture.height,TextureFormat.ARGB32,false); Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height); renderResult.ReadPixels(rect, 0, 0); byte[] byteArray = renderResult.EncodeToPNG(); filePath = Application.dataPath + "/CameraScreenshot"+ System.DateTime.Now.ToString("yy-MM-dd") +".png"; System.IO.File.WriteAllBytes(filePath, byteArray); Debug.Log("Saved CameraScreenshot.png");

real blaze
real blaze
#

it's a static function, just paste it anywhere

sharp pond
real blaze
#

note the first parameter. needs a monobehaviour

#

for the coroutine

sharp pond
#

like how do i utilise it after i paste it

#

anyway this is my full code that is handling the screenshot ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;

public class ScreenshotHandler : MonoBehaviour
{
private static ScreenshotHandler instance;
private Camera myCamera;
private bool takeScreenshotOnNextFrame;
public string filePath;
private void Awake(){
instance = this;
myCamera = gameObject.GetComponent<Camera>();
myCamera.enabled = false;
}

private void OnPostRender(){
    if (takeScreenshotOnNextFrame){
        takeScreenshotOnNextFrame = false;
        RenderTexture renderTexture = myCamera.targetTexture;
        Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
        Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
        renderResult.ReadPixels(rect, 0, 0);
        byte[] byteArray = renderResult.EncodeToPNG();
        filePath = Application.dataPath + "/CameraScreenshot"+ System.DateTime.Now.ToString("yy-MM-dd") +".png";
        System.IO.File.WriteAllBytes(filePath, byteArray);
        Debug.Log("Saved CameraScreenshot.png");

        RenderTexture.ReleaseTemporary(renderTexture);
        myCamera.targetTexture = null;
        myCamera.enabled = false;
    }
}

private void TakeScreenshot(int width, int height){
    myCamera.targetTexture = RenderTexture.GetTemporary(width, height,16);
    takeScreenshotOnNextFrame = true;
    myCamera.enabled = true;
}

public static void TakeScreenshot_Static(int width, int height){
    instance.TakeScreenshot(width, height);
    
}

}```

#

so basically when TakeScreenshot_Static is called and given perimeters, the perimeters will go into Takescreenshot setting myCamera to get the area of captured image and setting my takescreenshotonnextframe to be true triggering OnpostRender() which the texture will get from mycamera, then thrown into texture2d then encode to png then writeallbytes and saved into filepath

#

so where do i add or change my code to make it work like yours?

#

@real blaze

real blaze
sharp pond
# real blaze paste it in this class and use it on `TakeScreenshot(int,int)` function. you can...

paste this right? ```/// <summary>
/// Captures screenshot and returns the texture as the result. Null if failed.
/// </summary>
static async Task<Texture2D> TakeScreenshot(MonoBehaviour owner, TextureFormat textureFormat = TextureFormat.RGB24)
{
if (owner == null)
throw new ArgumentNullException(nameof(owner));
if (owner.gameObject.activeInHierarchy && !owner.gameObject.scene.IsValid())
throw new ArgumentException("Owner must be in a valid scene.", nameof(owner));
if (System.Threading.Thread.CurrentThread.ManagedThreadId != 1)
throw new InvalidOperationException("Must be called from main thread.");

Texture2D texture2D = null;
var tcs = new TaskCompletionSource<bool>();
owner.StartCoroutine(Coroutine());
await tcs.Task;


if (tcs.Task.Result)
    return texture2D;
else
    return null;

IEnumerator Coroutine()
{
    yield return new WaitForEndOfFrame();
    try
    {
        texture2D = new Texture2D(Screen.width, Screen.height, textureFormat, false);
        texture2D.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        texture2D.Apply();
    }
    catch (Exception e)
    {
        Debug.LogException(e);
        tcs.SetResult(false);
    }
    tcs.SetResult(true);
}

}```

real blaze
#

yes

sharp pond
#

or paste this without the onpostrender into your script? ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;

public class ScreenshotHandler : MonoBehaviour
{
private static ScreenshotHandler instance;
private Camera myCamera;
private bool takeScreenshotOnNextFrame;
public string filePath;
private void Awake(){
instance = this;
myCamera = gameObject.GetComponent<Camera>();
myCamera.enabled = false;
}
private void TakeScreenshot(int width, int height){
myCamera.targetTexture = RenderTexture.GetTemporary(width, height,16);
takeScreenshotOnNextFrame = true;
myCamera.enabled = true;
}

public static void TakeScreenshot_Static(int width, int height){
    instance.TakeScreenshot(width, height);
    
}

}```

sharp pond
# real blaze yes

just to double check, like this? ```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;

public class ScreenshotHandler : MonoBehaviour
{
[SerializeField] Texture2D renderResult;
[SerializeField] RenderTexture renderTexture;
private static ScreenshotHandler instance;
private Camera myCamera;
private bool takeScreenshotOnNextFrame;
public string filePath;
private void Awake(){
instance = this;
myCamera = gameObject.GetComponent<Camera>();
myCamera.enabled = false;
}
/// <summary>
/// Captures screenshot and returns the texture as the result. Null if failed.
/// </summary>
static async Task<Texture2D> TakeScreenshot(MonoBehaviour owner, TextureFormat textureFormat = TextureFormat.RGB24)
{
if (owner == null)
throw new ArgumentNullException(nameof(owner));
if (owner.gameObject.activeInHierarchy && !owner.gameObject.scene.IsValid())
throw new ArgumentException("Owner must be in a valid scene.", nameof(owner));
if (System.Threading.Thread.CurrentThread.ManagedThreadId != 1)
throw new InvalidOperationException("Must be called from main thread.");
Texture2D texture2D = null;
var tcs = new TaskCompletionSource<bool>();
owner.StartCoroutine(Coroutine());
await tcs.Task;
if (tcs.Task.Result)
return texture2D;
else
return null;
IEnumerator Coroutine()
{
yield return new WaitForEndOfFrame();
try
{
texture2D = new Texture2D(Screen.width, Screen.height, textureFormat, false);
texture2D.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
texture2D.Apply();
}
catch (Exception e)
{
Debug.LogException(e);
tcs.SetResult(false);
}
tcs.SetResult(true);
}
}

#
        myCamera.targetTexture = RenderTexture.GetTemporary(width, height,16);
        takeScreenshotOnNextFrame = true;
        myCamera.enabled = true;
    }
    public static void TakeScreenshot_Static(int width, int height){
        instance.TakeScreenshot(width, height);
    }
}```
#

cause i got this error Type or namespace definition, or end-of-file expected

real blaze
#

that's another story. you can learn about C# indentations and blocks

sharp pond
#

nvm, thanks for your time, maybe we lack certain communication, gonna try asking around in #archived-code-general or someone till i can get my answer

upbeat path
sharp pond
upbeat path
#

no need to explain, you are both doing exactly the same thing just in different ways, he just uses a different TextureFormat

#

do you even understand your own code?

sharp pond
upbeat path
#

this is why you NEVER Copy/Paste

sharp pond
upbeat path
#

I already told you, twice

sharp pond
#

he did not have a filepath though, is that the difference? lol

upbeat path
#

no

sharp pond
#

found it

upbeat path
#

His code

TextureFormat textureFormat = TextureFormat.RGB24

your code

TextureFormat.ARGB32
```\
sharp pond
#

gonna try now

#

ya, saw it

#

hope it works, geez

upbeat path
#

that is the ONLY difference

sharp pond
#

nope, does not work, sigh

serene lynx
#

@here Anyone i have an issue with Unity itself!
didn't found any chat for that type/form of issue so i am msg here.
Sorry for pinging πŸ™‚

so the issue is more technical?
my laptop memory: 16GB ( should be enough for unity )
processor intel core i3
Graphics are built in Intel UHD Graphics
Disk capacity 1.3TB
available space 275 gb
OS: Linux ~Debian
OS Type: 64 bit

NOTES:
nothing was opened except for unity itself!
but before this incident i could easily open a few google windows , Vscode, discord and unity and nothing freezed!

and the issue:
backstory first - i was working on unity almost everyday and have never experience such stuff in years with the same laptop but one day something changed and when i opened my unity with the same LTS version as usual i was using it suddenly started freezing till my laptop completely becames unresponsive to anything. after few minutes (5-7 if be exact).

i checked out my Task Manager from the start of unity project and the graph of memory usage was like this πŸ“ˆ

feel free to DM or ping me here, would be really grateful if you guys experienced with such crap could help me out:)

~Cheers, Saul

flint sage
#

Sounds like a memory leak in a specific version, update to the next minor version

clever widget
serene lynx
#

maybe that's becuase of reg. expression built into your editor or unity itself?

serene lynx
#

but never hurts to try again

flint sage
#

Can always downgrade again

clever widget
stuck plinth
# serene lynx hmm, already tried that

idk if this will help but the project i work on has had a gigantic editor-only memory leak for several unity versions, we can't track it down (we suspect it might be related to URP but beyond that who knows), but for some reason leaving the profiler window open even docked in the background makes it vanish so that's our fix

half swan
void bluff
#

should I use json files to store player dialogue or is txt file just fine?

upbeat path
#

Strawberry&Milk

#

iirc

void bluff
void bluff
upbeat path
#

in your situation Json or XML are better suited to the task in hand

void bluff
#

alright thanks

shy wasp
inland knoll
steel snow
#

just found a huge flaw in my mesh generation system 😒 hitting vertex count limits

#

now i got to overhaul it to split the gen into multiple meshes

shy wasp
true coyote
#

I'm working on an open-world sandbox game using Unity and Marching Cubes for terrain generation. The terrain is divided into chunks, and I've implemented a terraforming feature.

I've been spending past 2 days on trying to debug what causes these gaps to occur in my terrain when I dig in between chunks (at their boundaries/edges).

The brush is able to affect 2 or more chunks at the same time and it does look for neighbouring chunks but it looks like it affects each chunk differently.

I do lack a lot of programming knowledge but I am doing my best to work with what I know, however I can't seem to fix this issue and it's very frustrating.

I only have a few scripts which could be responsible for the issue. If anyone wants to take a look I would really really appreciate it, and to make it as easy as possible for someone willing to help** I've included my scene into a package file into this message.** I'm using the latest Unity 2023 beta but it should work with older Unity versions as well.

The digging logic can be found in the Edit Weights method in Chunk.cs and in TerraformingCamera.cs. The chunk manager is outside the scripts folder, in the assets folder. The rest of the scripts and shaders I'm using is inside the scripts folder, including the shaders.

After you import the package make sure to navigate to the scene called "MyScene" and open it.

Controls are:

  • Zoom in/Zoom out with scroll wheel/touchpad
  • Space for jump, WASD for moving and shift for sprinting
  • Digging is done using left click (adding) and right click (substracting)

Gaps only occur when digging between chunk boundaries, otherwise it seems to work as expected.

Any help is greatly appreciated! VintageUnity πŸ™

dusty wigeon
true coyote
# dusty wigeon One of the chunk seem to not be updated. Also, I wouldn't dive into voxel if I w...

If you open the scene and try digging right in between 2 chunk you can see that both chunks get modified, usually, but the brush has to touch them both so you need to sort of aim for the middle of the chunks. However it still creates a gap.

In regards with the terrain, it's pretty optimised as it is right now as I'm pooling stuff as well, it's nearly there in terms of the basics, all I need right now is I need the digging to work as expected before moving further, I take everyhting in small little steps.

limpid prairie
#
<meta name="viewport" content="width=device-width, initial-scale=1" />
#

My problem is that: I load a webpage with UniWebView, but my phone lets me scroll left and right on this webpage, but I don't want it to.
I want the webpage to fit or do whatever it needs to fit inside the UniWebView frame, and not let me scroll left and right.

sly grove
#

That's kind of up to the web page TBH

sly grove
limpid prairie
#

The thing is, that W3schools page recommends to add this line of code to make the webpage auto-adjust on any device:

<meta name="viewport" content="width=device-width, initial-scale=1.0">
#

But I already did see this line of code on the webpage that I'm embedding into the UniWebView, but it doesn't fit neatly inside it.

limpid prairie
#

Although, my site shows:

<meta name="viewport" content="width=device-width, initial-scale=1" />

which is slightly different than the above, does the small difference matter?

inland knoll
scenic forge
#

IIRC UniWebView supports embedding HTML directly rather than a URL, you should try embed one that's known to work and see if the issue is with UniWebView or not.

#

You can use VS Code and type ! in an HTML file to get an empty template with it correctly set up.

ionic ivy
#

Anyone familiar with ffmpeg?

scenic forge
#

You should just ask the question directly. If someone knows and wants to answer, they will.

flint sage
#

Also not really the right discord to ask ffmpeg questions lol

ionic ivy
#

The thing is, there's no right discord to ask ffmpeg question

#

and because the video encoding thing that I am doing is related to my Unity job - I figured I would ask it here

#

ffmpeg -i input.mp4 -c:a copy -c:v copy -force_key_frames 0:00:53,0:00:58,00:01:00,00:01:10,00:01:17,00:01:18,00:02:21,00:02:24,00:02:26,00:02:33,00:02:37,00:02:34,00:02:39 out.mp4

I need to add keyframes at specific timestamps, but this doesn't work because when I debug the timestamps - the output file list is empty.

scenic forge
#

Oh I thought the question was going to be something about integrating FFmpeg into Unity or something.

#

Yeah this is not really the place for it, and you'd probably have much better luck elsewhere.

#

Pretty sure SO has a section dedicated to FFmpeg.

ionic ivy
scenic forge
#

StackOverflow.

ionic ivy
real blaze
lament ruin
#

Hey y'all - I have a question on VFX / Sprite Effects in the UI. My game is mostly UI based and I am struggling to make the effects appear. Currently they sometimes appear, and if they do they are weirdly stretched as to what they are supposed to look.

The code is called from my heroController in the TakeDamage method and then instantiates the prefab with the effect on it. The actual effects are stored on the ability scriptable object, which plays whenever a hero takes damage.

public void InstantiateAndPlayReceivedAbilityParticleEffect(Abilities_SO ability)
{
    GameObject particleEffectPrefab = Instantiate(ability.particleEffectPrefab, transform.Find("ParticleObject"));
    particleEffectPrefab.GetComponent<ParticleSystem>().Play();
    LeanTween.delayedCall(1f, () =>
    {
        //Destroy(particleEffectPrefab);
    });
}

public void TakeDamage(int damageToHero,  IEAbilityDamageType enemyAbilityDamageType, Abilities_SO ability = null, bool isDamageOverTime = false, int damageOverTime = 0) {
    int delta = Mathf.Abs(heroShield - damageToHero);
    if (ability.particleEffectPrefab != null)
    {
        Debug.Log("EffectPrefab is in place");
        InstantiateAndPlayReceivedAbilityParticleEffect(ability);
    }
    else
    {
        Debug.Log("No Effect Prefab in place");

    } ... rest of code

The prefab is instantiated correctly on the gameObject (see attached). At first the issue was that the scale was off and I set it to 300, instead of 1 to make it visible.

So two problems:

  1. Sometimes the effect doesn't trigger at all
  2. Other times it is weirdly stretched.

I've tried disabling the components that regulate position and size of the UI objects attached to the parents, for example the heroes are in a vertically aligned panel that controlls the childrens sizes. But that didn't help either.

Anyone got any recommendations on how to handle Effects in a UI based game?

limpid prairie
#

Cause I have another page on a different UniWebView (but the page is from the same website, but a different page), and that embeds tightly and cleanly.

scenic forge
#

Do you control the websites?

limpid prairie
#

I can change them a bit yes, they're a partnered site, I can request changes.

limpid prairie
scenic forge
#

Yeah I'm not sure either

#

Is it for mobile, or desktop?

#

Try opening the site on the same platform but with a browser and the same size, to double check if the issue is really on your end or the website's.

real grove
#

I was wondering if anyone would be interested in helping me create a game I alr started with 12 others and we need a 3d artist and another programmer which could help us just a little if someone wants to help me dm me

fresh salmon
#

!collab

thorn flintBOT
real grove
lament ruin
#

Or whichever is the layer on top of the canvas.

timber shadow
#

NavMeshSurface doesn't appear as an addable component in the editor in spite of being able to reference it in my code (Unity.AI.Navigation.NavMeshSurface). Is there a step I'm missing beyond installing the AI Navigation package?

#

Looks like it has to be created via the GameObject > AI >NavMesh Surface button

timber shadow
#

No, it just doesn't show up. I had to create via GameObject > AI >NavMesh Surface

#

It's not an addable component in the Add Component drop down it seems

keen temple
#

hey anyone know how to fix that ?
its show when i try to build the game

part of error 1:

> Task :launcher:preBuild UP-TO-DATE
> Task :unityLibrary:GoogleMobileAdsPlugin.androidlib:preBuild UP-TO-DATE
> Task :unityLibrary:preBuild UP-TO-DATE

part off error 2:

Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
D:\myWork\Project\Ninja run\Library\Bee\Android\Prj\IL2CPP\Gradle\unityLibrary\src\main\java\com\unity\androidnotifications\UnityNotificationManager.java:165: error: cannot find symbol
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)

part of error 3:

CommandInvokationFailure: Gradle build failed. 
D:\2022.3.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "D:\2022.3.7f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-7.2.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"

limpid prairie