#archived-code-general

1 messages ยท Page 348 of 1

thin aurora
#

Does the object you collide with have a collider? Are they both triggers?

#

Also please put a Debug.Log inside the methods and validate it's actually not called and not just the if statement not calling

hollow mesa
#

the collider (sphereColider) who is trigger do not work and is never call even when the player (tag with player tag) to inside

#

so the camera who normally can be change, can't in this case

thin aurora
#

So is the method actually not called or is it the if statement that doesn't work? please debug

hollow mesa
#

this is sus because i use the same system for a quest and the quest work

thin aurora
#

Considering your methods look fine it has to be related to the actual triggers. You haven't shared those so I suggest you validate those

hollow mesa
#

i am here

#

my player is in the colider but nothing hapend, i do not have any message on the Log

somber nacelle
#

and where is the component that should be receiving the physics message

hollow mesa
somber nacelle
#

is that just on a completely unrelated object?

#

because only the objects you screenshot before would receive the messages from the collision/trigger

hollow mesa
#

i juste put the script on the Left_Door_Final

rotund burrow
#

I'm working on a rigidbody character controller. When it falls off the slope it gets stuck in the ground for a moment, i dont want that (see image) . So to fix it i have a variable called velocityBeforeCollision i update every frame, expect OnCollisionEnter() frame. And then i set the velocity to projected velocityBeforeCollision when it hits the ground. Is there an easier fix?

lean sail
rotund burrow
lean sail
rotund burrow
wraith spear
#

For some reason, my Input Action Asset isn't found by Visual Studio. I have the Input Action "Player_Input.inputactions" and .cs files under Assets/Resources, but they don't show up in my Visual Studio project, and as such I can't reference them. Do I need to add them to my Assembly somehow?
It used to work until I added Animancer in, not sure why that broke everything.

somber nacelle
#

you're using assembly definitions and you don't have a reference to the assembly that generated class is in (likely due to it being directly in the Assembly-CSharp assembly)

wraith spear
#

Is it possible for me to "move" it to the standard Assembly?

somber nacelle
#

it is in the "standard" assembly which is the problem. you cannot reference that from your asmdef, you need to put it into an assembly and reference that assembly, or put it into the assembly you are working in. or use an asmref

wraith spear
#

I see, thanks!

#

I'll look into putting it into the assembly I'm currently working in

#

It worked! Thanks a lot boxfriend ๐Ÿ™‚

tawdry pecan
#

I'm having a problem with the way the code positions my character. I want it so that when the player interacts with the mounted LMG, their camera will be set to the LMG's cameraSit, the player model set to the playerModelSit and the player parent be set in playerSit. I have set the transforms correctly in the scene and inspector and yet the player just mounts wherever

Here's all the code associated:
FPSController https://hastebin.com/share/buyanakoda.csharp
MountedLMG https://hastebin.com/share/ocaxayohod.csharp

somber nacelle
dark sparrow
#

Anybody who knows a bit about the Kinematic Character Controller?
I have a question about making AI move through it's motor

kindred wyvern
#

Anyone know where i could look for some beginnerfriendly help when it comes to programming for like an android phone? I have been trying for hours now to just grab the stepcounter-information from my phone into a textfield in unity, but im getting absolutly nowhere ๐Ÿ˜ฆ

somber nacelle
dark sparrow
#

I just need to understand the function MoveCharacter in KCC.
Motor.MoveCharacter(new Vector3(Random.Range(0f, 10f), 0, Random.Range(0f, 10f)));

It basically just teleports the character instead of moving towards it, is that working as intended?

#

I have forgot the original KCC discord name so I cannot ask there

somber nacelle
#

that method does not move over time, it moves the KinematicCharacterMotor to that position the next time it updates

dark sparrow
#

Alright thanks for the answer

tacit vine
#

So i have a infinite loop somewhere in my code i cant find it so i question myself is there a way to check which line is executed in visual studio?

somber nacelle
#

yes, you need to attach the debugger, then break all. you'll be able to check what is happening on each thread, you'll need to find the main thread and see where it is getting stuck

tacit vine
#

break all where is that function?

somber nacelle
tacit vine
#

and youre sure this can also in vs?

somber nacelle
#

yes

tacit vine
#

because breakpoints are not what i meant

somber nacelle
#

i never said you need to use breakpoints. i told you to break all

spring creek
tacit vine
#

yeah sorry i couldnt find it but i found it thx

hollow shuttle
#

Hey, I'm currently trying to create a virtual Microphone that can record in-game audio during runtime in a project using SteamAudio and save it to a wav file on my PC. My current solution involves using OnAudioFilterRead, which, if I understand correctly, essentially lets me record the audio that also arrives at my headphones. This works fine for having just one virtual Microphone, but since I want to have 3 active at the same time, I have to find a different solution. Each Microphone should only record the audio that would be played through my headphones if it was the active AudioListener in that scene, but I haven't found a way to accomplish that. If anyone has some advice or could help me with this, it would be greatly appreciated!

late lion
hollow shuttle
#

I was told before that there could be a way to modify Unity's Audio pipeline somehow, sort of like adding filters or some other audio-component to the Microphone objects and saving whatever goes through. Either way, that FMOD thing sounds like a solid option, I'll check that out. Thank you!

late lion
# hollow shuttle I was told before that there could be a way to modify Unity's Audio pipeline som...

You can hook into various parts of Unity's audio system, but at best you can try to simulate multiple listeners with it by applying your own attenuation and 3D sound. But both Unity and Steam Audio will still work as if there's only one listener. I don't know for sure that Steam Audio will work with multiple FMOD audio listeners, only that Steam Audio has FMOD support and that FMOD supports 8 audio listeners.

hollow shuttle
#

Worst case scenario I guess I'll just have to let the simulation run 3 times to get the three Microphones' output, but it sound to me like FMOD is worth a shot

radiant marten
#

So I'm coding my own mouse cursor(for reasons) and I have the Cursor.State set to confined and Cursor.visible set to false. However my OS cursor is still visible until I click the window(at least in Unity Editor). Once I click the window everything works as intended until I press escape and my cursor becomes unlocked and I can move it outside the window..

This is working as I'd hoped, but my only issue is I don't know how to detect when the OS mouse has been taken over by Unity. When I launch, Cursor.State is confined and Cursor.visible is false, but neither are actually true until I click the window so that doesn't seem like an accurate method. Application.isFocused is also returning true initially so it doesn't seem to be a focus thing

thick terrace
radiant marten
thick terrace
#

yeah, it'd be easy to get stuck otherwise haha

marsh mesa
#

Can someone help me? it says the term is ambiguous, when its not....? since there's only a single thing named rb in the entity class

rancid frost
#

I just thought of something.
What is stopping you from generating a tilemap, saving it as a PNG and just working off the PNG picture instead? Thus saving drawcalls and fps?...

rancid frost
marsh mesa
#

thanks for helping tho

rigid island
#

always good to verify you are going into the class you think you are

somber nacelle
#

can also just right click and peek definition

rigid island
#

oh yeah thats neat trick without going into the whole file

marsh mesa
#

thanks for the tips!

karmic sand
#

anyone got any idea why my light is so dim, its the highest possible brightness it can go

hexed pecan
rigid island
#

also radius of 0 ? ๐Ÿค”

#

what exactly is this light supposed to bounce off with 0 distance oops

hexed pecan
#

It is the radius of the "bulb", larger radius gives softer light

steady moat
#

Unity generate the solution. You cannot use another one.

rigid island
steady moat
#

And yes, you can use "normal" C# in Unity.

rancid frost
#

does unity always build with the default shaders (sprites/default, diffuse, etc..)

leaden ice
fading hull
#

Hello, how can i make a button the interactable area when clicking/hovering/unhovering the image size of the button? i have searched a lot but haven't found anything useful, thanks a lot

#

no matter what i try its always using the transparent parts of the sprite when hovering over it, not using the sprite exactly (without the transparent parts of it)

fading hull
#

its like my image sprite but smaller the interaction area with that

#

so not sure what the issue is

knotty sun
swift falcon
#

im trying to make a fps game where you cans shoot, but i want the gun to be able to shoot real bullets, like spheres but i cant find a tutorial on it

fading hull
#

its just composed of red/black sprites, so it would be really visible if there were transparent pixels i don't see, maybe there is an option in the settings im missing? no idea

swift falcon
#

also i remmeber watching a video on how to shoot with real projectiles, but i dont know what it is now

spring creek
#

There are many physics based projectile tutorials out there

swift falcon
#

im new to coding, so how would i implemnent this?

spring creek
#

Use the words physics based and rigidbody when searching tutorials

swift falcon
#

ok

knotty sun
fading hull
swift falcon
#

i still cant find any tutorials

knotty sun
swift falcon
#

could you give me one?

mossy oyster
#

Hey, I recently added some trees to my game but adding 180k tris/vertices visible at anytime and 2400 prefabs is really bad for performances lol

#

Anys idea on how to fix this issue please? I thought of billboard but they'll look weird won't they?

#

I'll just make bigger trees so I have to spawn less

gloomy helm
#

can some one help rotate my ik target towards the floor when it is to far

hexed pecan
#

And how do these screenshots relate to your problem, is that what you want or what you currently have?

gloomy helm
#

nvm i will use another way

marsh mesa
#

Any ideas why asigning a float's value to Time.time might not working? This is inside my Timer struct, which is in an "Entity" class which is not a monobehaviour. This works fine with other times, but it doesnt work specifically inside the Entity class. Everything before and after seems to work fine, if Debug.Log's are something to go by

#

Here's the entirety of my Timer Struct, if that's helpful in any way

marsh mesa
#

The log that returns the Time.time value works as intended, the one that checks the timer start time always returns negative infinity

leaden ice
marsh mesa
#

even tho i cann ResetTimer() which should change it from negative infinity to Time.time

leaden ice
#

The logs don't have any kind of label

marsh mesa
leaden ice
naive swallow
leaden ice
#

Add labels to your logs

marsh mesa
naive swallow
#

Because if it is, both of those logs would collapse into the same one

naive swallow
#

instead of appearing twice

marsh mesa
#

Oh

#

well, im certain it returns negative infinity, since the counter rises

marsh mesa
naive swallow
marsh mesa
#

okay, lets try

naive swallow
#
Debug.Log($"{gameObject.name}'s invuln start time is {invulnTime.startTime}. Time.time is {Time.time}", this);
#

Use this log instead of the two separate ones

#

this gives both values in one line along with the object whose values they are

marsh mesa
#

Mhm, thanks

#

give me a second to add & check

#

Yeah, thats basically the same information i already had

#

it says negative infinity in russian now tho

naive swallow
# marsh mesa

Okay, now let's put a different log in ResetTimer, before you change startTime:

Debug.Log($"Resetting startTime, previous value {startTime}, new value {Time.time}");
marsh mesa
#

The timer struct exists in other places too, so i wont know for sure which one is from the box specifically

#

i guess i'll need to add a way to label it

naive swallow
#

You'll get a reset log, then one of the logs above

#

that'll show which object just called it

marsh mesa
#

oh okaye

#

Yep, same thing

#

no matter how much i perform the action

simple egret
#

The fact that it's a struct may have something to do with the problem, you're aware that you're copying the timers when you pass them around in/out of the methods, into other variables, right?

marsh mesa
#

Would changing it into a class help? i'll try

naive swallow
marsh mesa
#

Okay yeah, that actually helped

marsh mesa
#

I had a reason to turn it into a struct, but i guess i'll have to deal with that problem later

#

anyway, thanks, it works as intended now!

#

wonder what exactly was the problem tho, the conditions for it not working seem kinda arbitrary

naive swallow
marsh mesa
#

Okay, that makes sense

#

i am aware that structs are value types, and classes are reference types, but i guess i didnt grasp all the implications of that, heh

#

thanks for explaining

lime flower
#

Does anyone know why random range is always returning zero in my script? When I log both my min and max variables they return as zero. This shouldn't be the case though because when I load the player data it sets level to 0 so they should be changing to 1 and 4 but in the end report as 0 each

cold parrot
lime flower
hexed pecan
#

Have you logged level?

#

Also Debug.Log(min + max) just prints the sum of min and max, noth both separately

lime flower
#

Used the first level

#

Which is 4 - 8

#

No matter what level it's set to min and max aren't updating

hexed pecan
#

Have you confirmed that Update is getting called?

#

I don't know how these snippets relate to each other, maybe share the full script(s)

lime flower
#
   {
       PlayerData data = SaveSystem.LoadPlayer();
       score = FindObjectOfType<Score>();
       level = data.currentUpgrade;
       Debug.Log(min + max);
       Debug.Log("Level" + 1);
   }

   public void Update()
   {
       if (level == 0)
       {
           min = 1; max = 4;
       }

       if (level == 1)
       {
           min = 4; max = 8;
       }

       if (level == 2)
       {
           min = 8; max = 12;
       }

       if (level == 3)
       {
           min = 12; max = 16;
       }
   }

    public void ImmaculateIron()
    {
        importValue = Random.Range(min, max);

        Debug.Log("Immaculate Iron was chosen.");

        importText.text = "Immaculate Iron " + "- " + importValue;
    }
simple egret
#

Start runs before Update, so it's normal min and max do not have the correct values when you log them

#

Log them in void ImmaculateIron(), where you pick the random number

#

As well as in Update to ensure it's actually running

leaden ice
#

Nor what level is

simple egret
#

It's at 1, according to the log, so it passes in the right path in Update

#

Just, too late for you to see it, since you log earlier

lime flower
#

From ImmaculateIron()

#

Also update is being called

simple egret
#

Wait I misread lol Debug.Log("Level" + 1); - that doesn't tell us anything

#

Log the actual value of level

lime flower
#

Whoops I was testing that I'll fix that

leaden ice
#

I.e. probably you've referenced a prefab or something

simple egret
#

If you're not supposed to have more than 4 levels, consider adding

if (level > 3)
  Debug.LogError($"Invalid level value {level}", gameObject);

So you have a trace on what the value is, and which object emitted the log

leaden ice
#

also using else ifs would be more correct and more performant

lime flower
lime flower
#

and update is running

leaden ice
lime flower
#

Instead of blowing up the console with that message it just stops after two

leaden ice
#

or you have Collapse turned on in your console

lime flower
#

now its running per frame

#

but still no updating of min max

leaden ice
simple egret
#

If you get 2 logs while the messages are collapsed, they're probably from different instances

leaden ice
#

further evidence that it's two different instances

lime flower
#

when collapsed it's only one message

somber nacelle
#

Include the instance id in your log, GetInstanceID() will get it

lime flower
#

does the two messages tell me there's two instances?

#

the two messages only show with the id, only one shows without it

#

I've also managed to get min max to update

#

to 1 - 4

#

now import value doesn't update

leaden ice
# lime flower

yes those numbers are the different instance ids of the two instances

lime flower
leaden ice
#

no indication if they're on different GameObjects or not

#

they could be

#

further logging could tell you of course

#

Or you can just start looking around your scene to find them

raven orbit
#

I just made my first script by following a tutorial on how to make player movement (i understood everything in it) what do you guys suggest i make next

rigid island
#

make the same thing again but without using the tutorial

raven orbit
#

okay, thanks

leaden ice
#

Well this script wouldn't really be relevant

storm wolf
#

hey, what would be faster, using a dictionary with mapped functions, or using a switch statement and calling the functions for each case there? e.g.

using Dictionary<MyType, Func<T, R>>

or

using

switch(MyObj.MyType){//call functions for each type}

leaden ice
#

The script that actually spawns the text would be

leaden ice
storm wolf
#

lets say theres 20 items, will switch be slower? also does it evaluate every case each time

#

and in my case my type is just an enum

leaden ice
#

If there's enough options in the switch it will use a jump table

flint panther
#

I'm following this tutorial to try and instantiate a skinned mesh renderer on my character and I'm confused. It isn't quite working
https://www.youtube.com/watch?v=nSmEirb8JGM

public class EnemyBuilder : MonoBehaviour {
    [SerializeField] float gearLevel;
    [SerializeField] SkinnedMeshRenderer smr;
    [SerializeField] Transform[] bones;
    [SerializeField] Transform root;
    
    private void Awake() { Build(); }

    public void Build() {
        smr.bones = bones;
        smr.rootBone = root;
    }
}```
#

I know this is because the bones are not right. How can I do this though

#

This is for randomly generated outfits

swift falcon
#

Just wanna comment on how good that ragdoll is

flint panther
#

The colliders? Thanks

#

I look at Counter Strike 2 colliders

swift falcon
#

Games like Hitman 3 have perfect hitboxes, I feel like they arent even using physics, instead its some sort of Mesh/triangle detecting raycast. Wonder if thats possible

hidden elbow
#

hi there, im adding a acceleration system to my player and so to do that i use this code but the problem is when i press for example the left right arrow 1 is always going to be * by my acceleration and i was wondering if there was any way of getting rid of that 1 so that its just the acceleration that is being added to the player and not a constant 1 (or maybe im doing things wrong and if so then let me know)

also im using getaxisraw instead of getaxis (in update function) because its gives the exact same result (-1, 0 or 1) every time instead of fractions which makes it easier to control for me imo

    {
        // horizontal movement
        rb.velocity = new Vector2(horizontal * horizontalSpeed, rb.velocity.y);


        /// acceleration
        if (horizontal < 0)
        {
            horizontalSpeed += accelerationSpeed;

        }
        else if (horizontal > 0)
        {
            horizontalSpeed -= -accelerationSpeed;

            if (horizontalSpeed > normalAcceleration)
            {
                horizontalSpeed = normalAcceleration;
            }
        }
    }
hidden elbow
#

basically what im trying to do is when i press right for axample, a force gets applied to my player constantly so it feels like theres zero friction and then i add a line of code to fradually slow the player down

dense arch
#

i get this error (im trying to set an image to a certain sprite to make the dialogue person who's talking)

#

idk what to do

thin aurora
#

I don't remember the correct one though. There are two, you need the other one

#

Can you share your imported namespaces?

dense arch
#

wait whats a namespace

thin aurora
#

They import namespaces

dense arch
#

Monobehaviour?

thin aurora
#

Your code is also in a namespace, often manually specified

#

However, in Unity you mostly work in a default namespace and you don't specify it

thin aurora
thin aurora
#

Yes

#

namespaces organize code

dense arch
#

ok i cant show rn but ill see what i imported

#

iโ€™ll let you know

thin aurora
#

If that fixes it, then UnityEngine.UIElement is the namespace you should use instead for your image, and you are likely using UnityEngine.UI

#

So the latter should be removed and replaced with the former namespace

knotty sun
slate imp
#

Hi guys, I can't find a way to bake occlusion culling in a prefab....
I have a couple of big prefabs and would like to bake the occlusion culling to gain fps

thin aurora
slate imp
#

oh well sorry

thin aurora
dense arch
#

this works!

#

tysm

#

whats uielements for?

slate imp
#

Hi guys, I've got a strange issue with my code....
I'm using, i have the simple code here.

But whenever i build an addresssable asset (which should not be related to this code)
i have the following error

dense arch
#

u need to write using UnityEngine.SceneManagement;

slate imp
#

Already got it

dense arch
#

the problem seems to be line 13

#

idk

#

wait for someone else to answer

cosmic rain
lean sail
#

SceneAsset cannot be used in a build, it is under unity editor

slate imp
cosmic rain
#

That shouldn't be included in a build either

slate imp
#

ohhh okay

fresh notch
#

I been trying to get a collider to work with a line renderer, but for some reason the mesh is moved forward, it always happens and it multplies as farther aways as it gets from the first iteration, does anyone know how to solve this?

hexed pecan
leaden ice
fresh notch
#

i cant manage to get the code to show in c in discord

#

it's been along time since i tried to post some code

#
IEnumerator branchR(GameObject previousRoad){

        GameObject currentRoad =  new GameObject();
        currentRoad.transform.localScale = new Vector3( 1f, 1f, 0f);
        LineRenderer lineRenderer = currentRoad.AddComponent<LineRenderer>();
       

        lineRenderer.SetColors(Color.black,Color.black);
        lineRenderer.material = new Material(Shader.Find("Sprites/Default"));
        lineRenderer.widthMultiplier = 1f;
        lineRenderer.positionCount = 2;

        currentRoad.transform.rotation = previousRoad.transform.rotation * Quaternion.Euler( 0, 0, a + Random.Range(-1,1));

        currentRoad.transform.position = previousRoad.transform.position - previousRoad.transform.right * 4f + currentRoad.transform.right * 2.5f;
        
        lineRenderer.SetPosition( 0, currentRoad.transform.position);
        lineRenderer.SetPosition( 1, previousRoad.transform.position);

        MeshCollider collider = currentRoad.AddComponent<MeshCollider>();
        Mesh lineMesh = new Mesh();

        lineRenderer.BakeMesh(lineMesh, false);
        collider.sharedMesh = lineMesh;

        current.Add(currentRoad);
        roads.Add(previousRoad);

        current.Remove(previousRoad);

        yield return null;
    }
#

now

fresh notch
leaden ice
#

meshcollider positions need to be in local space for the MeshCollider
LineRenderer positions will depend on whether th LR is in world space or local space mode

fresh notch
#

you mean the camera one?

leaden ice
#

no the useTransform bool

fresh notch
#

i switched on and off multiple times

#

to what it looks to no effect

leaden ice
#

Well one problem is they're two different objects

#

Or... are they? maybe not

hexed pecan
#

Seems like the LineRenderer is added to currentRoad

leaden ice
#

The docs only mention rotation and scale for the useTransform param..maybe it doesn't consider position

fresh notch
hexed pecan
#

Are you only going to have one collider per one line segment (two points)?
Might as well use a boxcollider if that's the case

fresh notch
#

yes

hexed pecan
#

Anyways, is your LineRenderer using world space?

fresh notch
#

it's barely my first using c# and unity

#

so i have no idea

#

how i can check that

hexed pecan
#

It's a setting in the inspector

#

Not sure if it affects BakeMesh in any way

fresh notch
#

what i find strange its that as farther away it gets from the first interation of the system

#

the mesh appers farther away

hexed pecan
#

You have to offset the mesh vertices in some direction, but I'm having massive brain fog atm so I can't formalize it lol

#

Subtract the road's transform.position from each vertex?

fresh notch
#

but i am able to modify the verticies of the mesh?

hexed pecan
#

Try this cs var verts = lineMesh.vertices; for (int i = 0; i < verts.Length; i++) { verts[i] = verts[i] - currentRoad.transform.position; } lineMesh.SetVertices(verts);

hexed pecan
fresh notch
#

oh ok

#

yeah it looks like it may work

#

let me try it out

#

it's not working but i'll keep trying on other setting to see if theres any effect

fresh notch
#

it's seems like nothing has happened

hexed pecan
#

You added my code after BakeMesh, right?

fresh notch
#

yeah

hexed pecan
#

Because it should definitely do something

fresh notch
#

it dosent seem to have any effect

hexed pecan
#

Try with useTransform set to true in BakeMesh

fresh notch
#

I already did that

#

its having no effect

hexed pecan
#

Does it still have the issue where it is offseted further on more distant objects?

hexed pecan
fresh notch
#

already did that

#

but its seems like sometihng changed

#

it's having some effect

#

yeah

#

no offset as further away as you get from first iterations

hexed pecan
#

When subtracting currentRoad position or what?

#

Ah, I think you need to take rotation into account too

fresh notch
#

yeah subrstacting current

hexed pecan
#

But I thought that useTransform would do that

fresh notch
#

yeah i also need to do something rotation

#

as its offset by a few degrees

hexed pecan
#

You would either need to:
-Keep the rotation of the road object at zero and instead of using transform.right, calculate the currentRoad's offset in some other way
Or
-Counter-rotate the vertices by the inverse of the road's rotation

#

The issue is that your object is rotated and it the mesh vertices end up rotated too

fresh notch
#

ok i get it

hexed pecan
#

This should work for countering the rotation (in the for loop):cs var v = verts[i]; v -= currentRoad.transform.position; // Remove positional offset v = Quaternion.Inverse(currentRoad.transform.rotation) * v; // Remove rotational offset verts[i] = v;

fresh notch
#

i may try to calculate the offset in another way

#

as for what i understand i wouldnt have to worry about this

#

if i just offset them in another way

leaden ice
#

Couldn't an InverseTransformPoint just handle all this position and rotation stuff

hexed pecan
leaden ice
#

v = currentRoad.transform.InverseTransformPoint(v);

fresh notch
#

ok thanks

#

i'll try it out

#

but i think i will redesing the entire system

#

as i will allow me to skip this calculations

pastel imp
#

Hello everyone I'm new here!

hexed pecan
#

You could use multiple points in one linerenderer too. Unless you want these gaps in the corners

pastel imp
#

Can somebody help me with animating a simple camera?

fresh notch
#

but i am just testing out

hexed pecan
#

Also I'm pretty sure that a 3D MeshCollider with no depth won't really work for collisions here

pastel imp
#

I have camera and I want to make "cutscene" like for example you click an button and the camera will rotate 90 degrees in an animation how could I do that?

fresh notch
#

i'll just need to create a line renderer for each branch

fresh notch
#

it seems it would work

#

but i still havent enabled collisions

#

so i'll test it out

hexed pecan
#

Alright

fresh notch
leaden ice
pastel imp
#

Hello do you know why my vs code editor don't auto complete???

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

pastel imp
#

Ok thx

hexed pecan
#

Follow all of the steps

fresh notch
#

thanks for everything

#

but i think i will redesign everything

#

so it performs better

pastel imp
#

Thanks it works you're a lifesaver bc I had it broken for about 2 years

spare island
#

Is there a more efficient way to subscribe/unsubscribe to C# events for objects that are destroyed?

#

this can't be the best way

leaden ice
spare island
leaden ice
#

You are unsubscribing a completely different lambda instance

hard estuary
leaden ice
#

it will not unsubscribe the anonymous lambda you subscribed with

spare island
#

oh

#

ohhhhhhhhhh thats what i was doing wrong

leaden ice
#
UnityServiceManager.OnInitialized += OnServicesInitialized;

UnityServiceManager.OnInitialized -= OnServicesInitialized;```
For the parameterless one, this is what you would do
#

for the other one, I recommend making a function that takes the correct parameter

spare island
#

yeah i kinda just added the () from habit

leaden ice
#

and doing similar

leaden ice
spare island
#

nope v-v

leaden ice
#

it's creating a whole separate anonymous function

spare island
#

well great wonder how many times i accidentally made lambdas

#

looks like i dropped a cup of thumbtacks but the thumbtacks are a bunch of very tiny memory leaks

#

fun fun fun

gray mural
#

I have a player, whose torso consists of Tilemap's Tiles.
The tiles are added and removed perfectly, but when recording PlayerController, Torso Tilemap and Face Tilemap on length decrease, and undoing the action manually, some Tiles just disappear randomly.

torsoTilemap.RefreshAllTiles(); // test
faceTilemap.RefreshAllTiles(); // test

Object[] dirtyObjects = new Object[] { this, torsoTilemap, faceTilemap };

Undo.RecordObjects(dirtyObjects, "Change player's length");

// Here: 
// Add Tiles to Tilemap / remove Tiles from Tilemap
// Only testTile is drawn for test
// private void SetTorsoTile(Vector2Int position, TileBase tile) =>
//     torsoTilemap.SetTile(position, tile ? testTile : null);

torsoTilemap.RefreshAllTiles(); // test
faceTilemap.RefreshAllTiles(); // test

dirtyObjects.SetDirty();

The extension method SetDirty enumerates through every Object and calls EditorUtility.SetDirty on it.

#

To ensure, RefreshAllTiles is called in Update. The issue happens in both edit and play modes

gray mural
#

Tilemap's Tiles disappear randomly on Undo

mossy oyster
#

Why my procedural meshes won't receive shadows?

#

"Receive shadows" option is on

fleet gorge
#

bake the light again?

#

at runtime

mossy oyster
#

How do I do that?

fleet gorge
mossy oyster
#

Google tells me you can't do that during runtime

#

Ah I found why

#

Unlit texture

flint panther
#

How do I spawn a skinned mesh renderer on a character?

#

I need to make randomized outfits

tame summit
#

Hey, if anyone could help me out a bit Im trying to make a computer terminal in my game but Im attempting to have a UI element always be selected even after giving input

leaden ice
rigid island
tame summit
flint panther
#

But I am asking about how to make it work correctly. My character has a rig, and the skinned mesh renderer will not deform itself correctly until it has the right bones

#

But these bones are all very random, I don't want to do a loop searching for the same name of bone by string (yuck). What is an alternative?

rigid island
flint panther
#

Okay, sorry for that

#

I had asked several times before with no response and got tired of typing

rigid island
#

You know you can just copy and paste previous question too

flint panther
#

It sounds like the server would not like it

#

Its okay, we are here now

#

I follow this tutorial here where he just uses the already assigned bones on the prefab character to spawn and assign the new one. I do not know why he does this, it removes the point of instantiating a new one.
https://www.youtube.com/watch?v=nSmEirb8JGM

โœ… Modular Characters 50% OFF! https://cmonkey.co/synty_modularfantasy_charcustom
๐ŸŒ Get the GameDevTV Code Monkey Bundle! https://unitycodemonkey.com/courses.php
๐Ÿ‘ Learn Unity, Blender and Programming Patterns, from Beginner to Advanced!
๐Ÿ‘‡ Click on Show More
๐ŸŽฎ Get my Steam Games https://unitycodemonkey.com/gamebundle

๐Ÿ”ด RELATED VIDEOS ๐Ÿ”ด
How to SW...

โ–ถ Play video
#

(14:12)

leaden ice
#

or just disable anything related to selection for it

rigid island
flint panther
#

Thank you

#

I understand what is happening, just why is my question

#

The idea here is to spawn gear in runtime.. but you need reference to the right bones with the gear already on the object? Pointless

rigid island
#

yeah not sure because I havent dealt with bone based customizations yet :\

cerulean nova
#

How can I disable AssetPostProcessors for temporary?

jaunty sleet
#

!code

tawny elkBOT
jaunty sleet
#

Here is the result using a box collider

dawn nebula
#

If you're working in WebGL, can you not use async/await at all?

leaden ice
#

you can't use threads

dawn nebula
dawn nebula
# leaden ice you can use async await

Ah kk. In that case I'm using a library to make a call to Parse Server.
https://github.com/parse-community/Parse-SDK-dotNET
Is there anything to keep in mind when making a web request from within Unity? Should I wrap this in a Coroutine so it has a similar flow to the UnityWebRequest documentation?

GitHub

Parse SDK for .NET, Xamarin, Unity. Contribute to parse-community/Parse-SDK-dotNET development by creating an account on GitHub.

dawn nebula
# leaden ice you can use async await

I assume the logic here is that I want to keep code executing at specific points within Unity's execution cycle. If I just do raw async then who knows when the code completes? Wrapping it in a coroutine at least lets you resume at a controlled point?

rigid island
rigid island
#

async Task Something()
{
await Task.Delay(2000)
//done
}

#

similiar to how some coroutines operations can be stored in AsyncOperation you can store something in a Task for checking later

Task task = Something();
if (task.IsCompleted)
{
//done
}

dawn nebula
small schooner
#

Check Unitask it mix of async and Coroutines

rigid island
young tapir
#

Has anyone got an easy way to apply the rotation of arrow to the direction RootPhysicBody is forced? It's probably a pretty basic question but I just can't see how to do it

dawn nebula
leaden ice
young tapir
#

Ah what

#

Okay thank you, I feel silly now

rigid island
dawn nebula
rigid island
#

the ugs sdk from unity is all async and task anyway

#

but WebRequests i would use inside unity

#

also you can use the observer (events) pattern here to alert you when something completed

dawn nebula
rigid island
# dawn nebula Ok I'll wrap it in a coroutine then. I do want to ask for my own interest though...

there are a few caveats that need to be addressed thats why unity came up with the Awaitable class, this video explains better than I could
https://youtu.be/X9Dtb_4os1o

In this follow-up video, we explore the Awaitable class introduced in Unity 2023.1, which aims to improve asynchronous programming workflows.

See part 1: https://youtu.be/WY-mk-ZGAq8

Topics Covered:

  1. Learn about the new Awaitable.WaitForSecondsAsync, NextFrameAsync, EndOfFrameAsync & FixedUpdateAsync.
  2. Learn about cancellation tokens and s...
โ–ถ Play video
dawn nebula
#

Object was destroyed? Don't care.

#

Editor exited play mode? Don't care.

rigid island
#

yeah basically thats why it mostly works fine

small schooner
rigid island
#

now days, is it really worth the hassle of managing another library in your project

#

I think I only used Unitask once though so I cannot speak from xp ๐Ÿ˜›

small schooner
#

I used it in production project to fix bug that wasnโ€™t possible to fix it by C# tasks

rigid island
#

wasn't awaitable class basically made to merge this gap and pretty much make libraries like that kinda moot?

small schooner
#

Tasks is much clear in code than coroutines but coroutines can do much more because they are native to Unity 3d thatโ€™s why I use Unitask since that bug in my each new project

gusty aurora
#

Can someone confirm that setting a rigidbody to kinematic will also set its accumulated forces to a weird value ?

leaden ice
#

Easy to test.

gusty aurora
#

Wdym "easy to test"...? The entire point is to know if that weird behaviour happens on someone else's project

#

Of course I know they won't have any effect

leaden ice
#

see what happens

gusty aurora
#

I did, and it sets them to a weird value, as written in my first message.

#

I'm asking for help to see if the same behaviour happens on another computer

topaz whale
#

Hi guys,can u send ur favourite videos on how to make a game menu?I am making a 2d game for android if that specifies the type of menu

rigid island
lean sail
topaz whale
#

And it s kinda relevant to code as well ig

rigid island
topaz whale
#

Oh

#

Ok sorry

dark sparrow
#

Any idea if Muse Animate will be released for Unity 6 anytime soon?

wide terrace
digital girder
#

coding UI question: so I have an upgrade screen and I disable the upgrade button if the player uses it which works well enough, but then I can't really navigate past that button to other buttons because it's disabled. How do people normally handle something like this? Just don't disable buttons and I guess make sure my 'if statements' check for contingencies?

leaden ice
digital girder
#

I believe because it's disabled. Here's a picture of the upgrade screen in question. Mouse and keyboard work fine. It's more of a controller issue. The controller - through the event system can't really see the next button over from a disabled button, at least that's what I think is happening.

#

if shield 1 is selected, the controller won't go to dash 1 if sword 1 is disabled

leaden ice
#

also if the keyboard works the controller should work

#

they use the same system for navigation

digital girder
#

sorry, mouse works, not keyboard/controller

I'm setting interactable and enabled to false

leaden ice
#

not enabled = false

digital girder
#

ok, I'll try that. Thank you

young tapir
#

I'm back at it again with more questions ๐Ÿ˜…

I just set up a little script for referencing an array of skinned mesh renderers with the intent to change every renderers material emission as one, using a coroutine like so:

        public IEnumerator Emissive()
        {
            yield return new WaitForSeconds(0.1f);
            float tts = 1f;
            float timeElapsed = 0;
            Color toHitC = Color;
            Color CurrentC = CurrentColor;
            float tempR;
            float tempG;
            float tempB;
            float tempA;
            Color tempColor;

            while (timeElapsed <= tts)
            {
                tempR = Mathf.Lerp(CurrentC.r, toHitC.r, (timeElapsed / tts));
                tempG = Mathf.Lerp(CurrentC.g, toHitC.g, (timeElapsed / tts));
                tempB = Mathf.Lerp(CurrentC.b, toHitC.b, (timeElapsed / tts));
                tempA = Mathf.Lerp(CurrentC.a, toHitC.a, (timeElapsed / tts));
                tempColor = new Color(tempR, tempG, tempB, tempA);
                m.SetColor("_EmissionColor", tempColor);
                timeElapsed += Time.deltaTime;
                yield return null;
            }
            CurrentColor = Color;
            yield break;
        }```

is there a way I can group every material into one list and modify that? Currently m is just a single material which is no good.
leaden ice
#

loop over it

dusky lake
young tapir
leaden ice
#

Just iterate over that, no?

young tapir
leaden ice
#

tempColor = Color.Lerp(CurrentC, toHitC, (timeElapsed / tts)); < replaces all 5 lines

young tapir
leaden ice
young tapir
#

Nup

dusky lake
#

for/foreach?

leaden ice
#

just a for/foreach loop^

young tapir
#

I've used foreach loads, not all that familiar with it

dusky lake
#

foreach (var item in list) {...}

leaden ice
#

Kind of basic C#....

#

can't really use lists without knowing loops

dusky lake
#

yeah you should really look up the basic loops of C# ๐Ÿ˜„

young tapir
leaden ice
young tapir
young tapir
#

I was doing a stupid

#

Thank you eyes_hyper

lean sail
#

you should really go further into basics of c# then, loops are really like week one stuff.

young tapir
#

That'll hopefully be the last stupid question

leaden ice
#

each time it runs, it's the specific material for that specific renderer

#

If there are 5 renderers in the list, the code will run 5 times

#

and m will be each of the different materials, in turn

#

only one at a time

#

"for each", it's straight up english

young tapir
#

Is there a way to have all of the materials be one list that I can just modify with setColor?

leaden ice
#

i don't see how that would be any different than this

#

you would then just be writing a foreach loop over that list

#

and do the same thing you do here

dusky lake
leaden ice
#

You seem to have some idea that a list is "all the things at once", it's not. It's a collection of individual things

leaden ice
young tapir
#

After I change Material m to m, that is.

leaden ice
#

you're ignoring the variable

#

you would want to pass m into the coroutine as a parameter

#

really though, you should pass the whole list into the coroutine
and put the loop inside the coroutine to loop over them all each frame

dusky lake
young tapir
#

I will remove the wait, the full coroutine will be in a separate DLL

#

Thank you both!

leaden ice
#

If all the SkinnedMeshRenderers are using the same material, you don't even need to do this really

#

If you just get the material as sharedMaterial or reference it directly from the inspector, you could just modify the one material and they'll all be affected

young tapir
young tapir
dusky lake
#

Oh and a note from me too, if you want to use SetColor directly on the List you can utilize Extension methods:

using System.Collections.Generic;

public static class MaterialListExtension
{
    public static void SetColor(this List<SkinnedMeshRenderer> list, string name, Color color)
    {
        foreach (var skinnedMeshRenderer in list)
        {
            var m = skinnedMeshRenderer.material;
            m.SetColor(name, color);
        }
    }
}

this way you can call list.SetColor("_EmissionColor", color); directly

#

but yeah not going to get around using loops ๐Ÿ˜„

young tapir
young tapir
#

Looks like it'd only flip to the colour

dusky lake
#

yes you need to lerp the input color and call that function every time you make a new step on that lerp

raw token
#

Can somebody help me with water

#

The low gravity zone is very slim, only a slim zone on the surface of the water. How can I change that so that it is always under it?

vagrant blade
#

What does that even mean?

raw token
flint panther
#

need help for spawning the skinned mesh renderer on a player in runtime

placid star
#

@raw token hello

#

I have python programming background and im new to unity and C#. I am following youtube tutorials on making a 3D fps game. I am trying to figure out the falling/dying + respawning part right now
I tried some forums and it didnt work
This is the code for my trigger
player have rigidbody
trigger has rigidbody and box collider and I checked the box IsTrigger
im not sure what I did wrong, but from what I understand, player.transform.position is the variable that holds the player position, transform is the category and position is under the transform category. By setting it to equal the respawn point I can teleport to the respawn point. I also tried setting it to a vector3 and it also didnt work
The camera should follow the player right? would it be that im just setting the gameobject player to respawn but the camera falls through?

void basalt
# placid star

for future reference, you should paste the code instead of screenshots

rigid island
#

I can't even tell from this screenshot which one is the player

#

why does the respawn trigger have a rigidbody with gravity

spring creek
rigid island
#

ahh crosspost, very nice

#

only judging by colors rn does not look like it. at minimum classes should be green

mossy oyster
#

Hi, when I try open the editor, I get this message
The GUID inside 'Packages/com.unity.services.levelplay/Editor/Analytics.meta' cannot be extracted by the YAML Parser. Attempting to extract it via string matching instead. Please verify the file does not contain unexpected data. how can I fix this please?

ruby seal
#

I am working on procedural terrain generation in unity using the unity job system

I am able to get 200+ fps in 5000 sqr unity unit map which is divided in 1600 chunks and per chunk 75 subdivision which is total 54 million tris , in order to optimise the rendering I added culling which will render depending on the distance and view angle ...

Similar results are in larger maps too.

|| Is it something great? IDK what you guys think ||

I tried both classic perlin noise and simplex noise from the mathematics Library and was able to notice 2 to 10 fps difference.. (snoise is more performant)
Currently the world is generated using simplex noise

||System specific in case
i3 9100f - 4 cores 4 thread
16 GB 2400 mhz ddr4 ram
Amd rx560 4gb GPU
||

steady moat
ruby seal
ruby seal
steady moat
steady moat
ruby seal
#

I see

barren edge
#

hello, sorry, i'm french and my english is not very good, where can i find a help for a script in unity and, i don't understand "privileges" in a unity forum, thanks for your help and again sorry ๐Ÿฅด ๐Ÿ˜•

somber nacelle
#

you can ask for help here. just be sure to check #854851968446365696
the forums are currently readonly since they are being migrated to the discussions site in the next few days

barren edge
somber nacelle
barren edge
somber nacelle
#

what? i am referring to the unity forums site which is currently set to read only. you cannot post on the unity forums site because it is read only now. this is due to the migration to the discussions site which is taking place over the next several days

barren edge
#

you know help me for bug in video game 2D by chance ?

somber nacelle
barren edge
#

it's complicated, i'm new in the server, and my english is not perfect, so it's very not simple, i need to descripting my bug for you (it's i understand๐Ÿ˜• ) ???

somber nacelle
#

use a translator service if you do not understand.

barren edge
#

it's logic in fact...

somber nacelle
barren edge
#

ok, i take a screen-shot and descript my problem, but, i don't have error script, look, my screen shot and the description please (thanks for your patiently)

#

my problem is :

#

my player stay hang of my wall when i go against in my wall, you know why and how to repar that bug, i don't very know how explain that problem becaus i don't know where is the problem source๐Ÿ˜•

steady moat
# barren edge my player stay hang of my wall when i go against in my wall, you know why and ho...

Get rid of sticky walls in 2d platformers. Very easy and simple fix.

โœ… Get my courses with discount:
๐Ÿ‘‰ Unity 2D Master: https://www.udemy.com/course/unity2dmaster/?couponCode=SMOOTH-2D-MASTER
๐Ÿ‘‰ Unity Mobile Course: https://www.udemy.com/course/unitymobilecourse/?couponCode=SMOOTH-MOBILE
๐Ÿ‘‰ Unity Input System with Rebinding: https://www.udemy.co...

โ–ถ Play video
#

Trying to make a platformer in Unity3D? Rigidbodies keep sticking to walls? This could help! :)
Wishlist my new game, HexLands now! โžค https://store.steampowered.com/app/2244650/HexLands/?utm_source=yt&utm_content=rigidbody
Join our Discord community โžค https://discord.gg/6hKwSaCkwa

Some of you may also faced this problem when you were trying to ...

โ–ถ Play video
#

Do not know if they are talking about it in the video, but you can also RayCast/BoxCast before moving to prevent the player from moving if they would get in the wall.

barren edge
barren edge
steady moat
barren edge
knotty sun
barren edge
knotty sun
#

but your English is not good and it makes understanding you very difficult

barren edge
#

i know, i learn again ๐Ÿ˜…

#

and i very not first in my class room for that matter๐Ÿ˜‚ ๐Ÿ˜…

knotty sun
#

Ne pas

barren edge
knotty sun
barren edge
barren edge
knotty sun
heady prism
#

@everyone

I am getting pink screen in AR webgl project on running camera

barren edge
heady prism
#

I am getting pink screen in AR webgl project on running camera

Anyone please suggest to correct this

barren edge
knotty sun
heady prism
#

@barren edge I am building in urp and getting error

barren edge
heady prism
#

WebAR

barren edge
#

i don't know what is it, sorry, but, please, read #854851968446365696 for know the rules of the rooms ๐Ÿ˜•

barren edge
heady prism
knotty sun
heady prism
#

Kindly share correct channel

knotty sun
left anvil
#

Hey, does anyone know how I can reference a variable in a script that is in Assembly?

cold parrot
somber nacelle
#

they probably meant that the class that contains the variable is in a different assembly

left anvil
#

I wanted to refer to SaveContainer, it is a public static variable, the script is in the Assets/Scripts folder, I did not add any assembly there

#

The script from which I want to refer to it is in assembly

somber nacelle
left anvil
#

Ok thanks, I'll check this

vale bridge
#

How come I'm getting a nullreference exception at line 50 when I try to access the width and height of the texture2D? https://pastebin.com/fTgELayY

#

If I set the hotspot of the cursor as Vector2.zero the texture replaces the current cursor with no issue, though

#

Which means somehow accessing the texture itself is fine but not its width and height?

strange gust
somber nacelle
vale bridge
#

Thank you

somber nacelle
#

for future reference, check this out for how to solve a NullReferenceException: https://unity.huh.how/runtime-exceptions/nullreferenceexception
there was only one object on that line that could have been null, so it was simply a matter of seeing where that method was being called from since the null object was the parameter passed to it

vale bridge
#

Aye aye ๐Ÿซก

radiant marten
#
/* Component Classes */
public class B : A {
  public override void onFoo() {
    Debug.Log("Foo B");
  }
}

public class C : A {
  public override void onFoo() {
    Debug.Log("Foo C");
  }
}

/* Parent Class */
public class OpSys_Clickable : A {
  public virtual void onFoo() {}
}
/* Finder */
A findComponent;
foreach (RaycastResult i in results) {
  if (i.gameObject.TryGetComponent<A>(out findComponent)) {
    A.onFoo();
  }
}```
If I have a structure like this, where I have a GameObjects with B/C scripts added as a component, is there a way that I can easily find all items that inherit class A and trigger their overwritten methods instead of looking for each instance of a B/C/etc?
somber nacelle
#

that would be how

leaden ice
#

Assuming it can have multiple

somber nacelle
#

when you have a reference to an instance of type B stored in a variable of type A and call a method that has been overridden, it will run the override version fo that method

leaden ice
#

If each only has one then just a regular TryGetComponent works

somber nacelle
#

it's only when you hide a method, such as with the new operator that it wouldn't do that. so for this:

public class A { public void Foo(); public virtual void Bar(); }
public class B : A { public new void Foo(); public override void Bar(); }

A a = new B();
a.Foo(); //calls the Foo method defined in class A
(a as B).Foo(); //calls the Foo method defined in class B
a.Bar(); //call the Bar method overridden in class B
raw token
#

can somebody help me with cosmetics in a VR game

somber nacelle
#

this is a code channel

raw token
#

so wheres the help with VR cosmetics channel

somber nacelle
raw token
#

i cant even talk in there ๐Ÿ’€

somber nacelle
#

you're meant to read it

#

please put at least some thought into what you are doing

radiant marten
#

alright thanks everyone, it wasn't triggering so I suppose there's some other problem with my code I gotta figure out

raw token
#

i still dont see it

#

can u js tag the help with VR cosmetics channel

somber nacelle
somber nacelle
# raw token can u js tag the help with VR cosmetics channel

how about you put literally any amount of effort that isn't 0 into getting help for your issue instead of making everyone else do the thinking for you. finding the correct channel is literally brain dead simple if you just read the information provided to you

raw token
#

i did read it but I cant find a help with VR channel or cosmetics.

somber nacelle
#

then you didn't read it

raw token
#

is it this one?

somber nacelle
#

that depends, is your "VR cosmetics" question related to vr?

raw token
#

yeah

somber nacelle
#

then what do you think

raw token
somber nacelle
#

there are so many ways to handle dialogue there isn't really one "great" answer to this. I'd look into some of the popular dialogue system assets to see how they handle it.
though personally I would do something crazy like build a node based editor that allows me to create nice dialogue trees that i can then serialize to use in my code

somber nacelle
raw token
somber nacelle
#

that likely won't scale very well tbh, if you end up with complex dialogue trees, trying to find the correct scriptable objects in your assets folder might end up a nightmare

somber nacelle
knotty sun
raw token
somber nacelle
#

you can stop dragging this shit on and go ask your question in the correct channel now instead of continuing to be a complete nuisance

knotty sun
somber nacelle
#

congrats, your question had nothing at all to do with vr!

raw token
#

what?

#

yes it does

somber nacelle
#

your issue is not related to it being vr in any way. it is just a question about parenting and positioning objects.

raw token
#

yes but its in a VR game

vagrant blade
#

No need to keep this whole thing going.

#

Is gone because I've answered it.

raw token
vagrant blade
#

It's fine, you can leave it there. Move on, this conversation is beyond unecessary at this point.

vale bridge
#

Is it a better implementation if I have a manager script that gives my homing missiles targets or should I put the logic on the missiles themselves, practically does it make a difference?

vagrant blade
#

Practically it makes no difference. Organizationally, it's probably cleaner to provide the target to the missile from the thing actually tracking/doing the firing.

#

And then let the missile store the target and work the results on its own.

vale bridge
#

Gotcha

#

Thanks!

deft kindle
#

Where do i find the Client Secret (I have bought a Google Play Dev Account and made the app but i cant find the Client Secret)

deft kindle
rigid island
deft kindle
rigid island
#

iirc it gives you a json you were supposed to download with the sceret

#

havent touched google stuff in a while

#

when you created , pretty sure it gives you client secret too

deft kindle
rigid island
#

the guides i saw on the website say you do idk.
this is more of a google question than unity code question

deft kindle
deft kindle
#

Idk how to setup Google Play Games Login

rigid island
#

so read the manual

deft kindle
rigid island
#

google for ya

#

their unity sdks are hot garbage

cold parrot
#

Donโ€™t trust web devs to make game stuff

#

Imagine a world where you can just assume you have infinite resources. Imagine giving people in that world a tool that makes it easy to solve easy problems. Imagine what happens if they use that tool to solve difficult problems.

deft kindle
#

I found out that you needed to make a web OAuth client ID for getting the Client Secret and it should have been in the docs

rigid island
#

but yeah they dont specify anything about generated keys/secrets and you kinda have to already know how these things work

#

google really doesn't gaf about unity anyway

#

they make so much money with their own services this is chump change

vale bridge
#

Is it common for prefabs to have an inactive RigidBody which is then activated later instead of adding the rigidbody when something happens?

somber nacelle
#

Rigidbody does not inherit from Behaviour so it cannot be enabled/disabled. at best you could make it kinematic, but that isn't the same as disabled

gray mural
#

Note that Rigidbody is not running on a prefab if it's not spawned in the scene

vale bridge
vale bridge
#

And when it later detaches I add the rb component via script

#

Is this an acceptable way of doing things or nah

gray mural
#

You rarely add anything

vale bridge
#

hmm i see

gray mural
#

Although, cannot answer the question without more information provided

vale bridge
gray mural
#

Well, it rarely does

vale bridge
gray mural
# gray mural Well, it rarely does

The thing, which comes to my mind, is a moving arena with the player as its child. Both have Rigidbody. The player can move on its own, and also moves whenever its parent, arena, does

terse garnet
#

guys, i'm trying to implement unity IAP in my project, in the test unity it works very well with the products i've registered for testing, but when testing in a production environment, UnityPurchasing is not initialized, i'm running UnityPurchasing.Initialize(); but it doesn't give me feedback if it failed or if it initialized and i simply don't have information about the products.

knotty sun
terse garnet
knotty sun
#

you are a better man than I, you don't even say what build target you are using

deft kindle
#

My Authentication does not work

using System.Threading.Tasks;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using Unity.Services.Authentication;
using Unity.Services.Core;
using UnityEngine;

public class GoogleIntegration : MonoBehaviour
{
    [SerializeField] GameObject gameManager;
    [SerializeField] GameObject mainScreen;
    [SerializeField] GameObject loadScreen;

    public string GooglePlayToken;
    public string GooglePlayError;

    private async void Start()
    {
        await Authenticate();
    }

    public async Task Authenticate()
    {
        PlayGamesPlatform.Activate();
        await UnityServices.InitializeAsync();

        PlayGamesPlatform.Instance.Authenticate((success) =>
        {
            if (success == SignInStatus.Success)
            {
                Debug.Log("Login with Google was successful.");
                PlayGamesPlatform.Instance.RequestServerSideAccess(true, code =>
                {
                    Debug.Log($"Auth code is {code}");
                    GooglePlayToken = code;
                });

                gameManager.SetActive(true);
                mainScreen.SetActive(true);
                loadScreen.SetActive(false);
            }
            else
            {
                GooglePlayError = "Failed to retrieve GPG auth code";
                Debug.LogError("Login Unsuccessful");
            }
        });

        await AuthenticateWithUnity();
    }

    private async Task AuthenticateWithUnity()
    {
        try
        {
            await AuthenticationService.Instance.SignInWithGoogleAsync(GooglePlayToken);
            gameManager.SetActive(true);
            mainScreen.SetActive(true);
            loadScreen.SetActive(false);
        }
        catch (AuthenticationException ex)
        {
            Debug.LogException(ex);
            throw;
        }
        catch (RequestFailedException ex)
        {
            Debug.LogException(ex);
            throw;
        }
    }
}
deft kindle
tawny elkBOT
deft kindle
serene stag
knotty sun
deft kindle
graceful latch
#

im sure this is a stupid question but does anyone know why this is getting a null refference exception


//Check if object is interactable
if (hitInfo.collider.gameObject.TryGetComponent(out IInteractable InteractObj))
{
    // If Tooltip Is Text Get Tooltip And Assign it To The Tooltip's Text

    if (useTooltipHUD && InteractObj.Tooltip != null)
    {
        tooltipText.text = InteractObj.Tooltip; 
    }
    
    //Set The UI Elements As Active
    TooltipObject.SetActive(true);
    UpdateCrosshair(InteractObj.CrosshairIndex);

    //Check for input then interact
    if (inputDown)
    {
        InteractObj.Interact();
        Debug.Log("Player Interacted with: " + InteractObj.ToString());
        return;
    }
}```
graceful latch
#

sorry let me double check

graceful latch
somber nacelle
#

so what happens if nothing is hit by the raycast

knotty sun
#

then it is obvious the raycast hit nothing

graceful latch
#

can i make it so if it hits nothing its false?

#

its 5am ive been up all night

#

and my googling isnt helping

somber nacelle
#

what does Physics.Raycast return?

knotty sun
#

what do you think Physics.Raycast returns ?

graceful latch
#

that makes alot of sense im sorry like i said im tired i think ima just try and do stuff tomorrow when i have a functioning brain ๐Ÿคฃ

olive bobcat
#

public SceneAsset sceneName;
I get this error on VisualStudio but not on Unity: The type or namespace name 'SceneAsset' could not be found (are you missing a using directive or an assembly reference?)

#

This is ... irritating ๐Ÿ™„

somber nacelle
#

regenerate project files

olive bobcat
olive bobcat
somber nacelle
#

well no, the issue was likely just that your editor didn't actually create a csproj file for the UnityEditor assembly and regenerating project files forced it to do so

olive bobcat
#

So I will replace SceneAsset with public UnityEngine.Object sceneName; and I'll grab the name

somber nacelle
#

but if that code isn't for editor-only stuff then you'll need to change that because SceneAsset does not exist in a build

olive bobcat
#

Oh.. ok I get it, anyway the error pops out again after a few minutes.

somber nacelle
#

did you restart visual studio after clicking the regenerate project files button?

olive bobcat
#

Anyway I've fixed it by changing the type ๐Ÿ˜‰

plain moon
#

What's wrong with Application.targetFrameRate?
When I set 60 I've got 45 (in my 90HZ android)
When I set -1 I've got 30
When I set 90 I've got 70+ (good)

Optimized Frame Pacing is turned off

#

vsync is 0

gray mural
#

Hey, is it fine to wrap the method in the UNITY_EDITOR condition?

#if UNITY_EDITOR

private void MyMethod() { }

#endif
terse garnet
gray mural
#

When calling the wrapped method inside of the code, not wrapped in this conditon, is it just not called?

simple egret
waxen socket
slate blaze
#

Anybody know the syntax for referencing a sorting group component for 2d?

simple egret
slate blaze
tawny elkBOT
simple egret
#

Once done, errors will be underlined red, and you'll be able to invoke quick actions to fix this error for you

#

Do not skip this step, it is a huge help, and also required to get help here.

slate blaze
frosty token
#

i'm trying to update these Hosting fields through code, but if I iterate (both for or foreach loops) them and update the Hosting field to a new value, it does not seem to update at all. Is it needed to rewrite the array for updates? (During playtime, not in editor)

hard estuary
frosty token
#

yes, indeed, i was just thinking, i most likely have to write the entire struct again right?

hard estuary
frosty token
#

cool, yeah making them by ref would be ideal because rewriting these array items would be a pain

#

thanks, changing the struct to a class worked ๐Ÿ‘

fervent jacinth
#

Im trying to make a zero g player controller (like outer wilds) with fully axis independent movement. I need camera lerping for the smooth feel. Heres what I tried, but when the player goes upside down, the controls are inverted.

Quaternion yAxis = Quaternion.AngleAxis(pitch, Vector3.right);
Quaternion xAxis = Quaternion.AngleAxis(yaw, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, xAxis * yAxis, drag * Time.deltaTime);```
hard estuary
# frosty token yes, indeed, i was just thinking, i most likely have to write the entire struct ...

Here is a sample code as an example to what I've written earlier:

struct Test
{
  public int x;
}

Test[] tests = new Test[4];  

void Start()
{
  int count = tests.Length;
  for (int i = 0; i < count; i++)
    tests[i].x = i + 1; // It will update structs in array
  for (int i = 0; i < count; i++)
  {
    var test = tests[i]; // It will create a copy of structs from the array
    test.x = i + 2; // It will modify a copy of structs from the array, but won't modify original structs
  }
}
wide terrace
fervent jacinth
#

nope! its a camera issue

#

the camera controls get inverted

wide terrace
frosty token
frosty token
#

if anybody reads this later and wants to know how to do it, it like this for keeping the ref to the struct

for (int a = 0; a < AttachTo.Length; a++)
{
    for (int t = 0; t < AttachTo[a].type.Length; t++)
    {
        for (int h = 0; h < component.Host.Length; h++)
        {
            if (component.Host[h].attachmentPoint != other.transform)
            {
                continue;
            }
            for (int ht = 0; ht < component.Host[h].type.Length; ht++)
            {
                if (AttachTo[a].type[t] == component.Host[h].type[ht])
                {
                    Debug.Log($"Found compatible attachment {AttachTo[a].attachmentPoint.name} on {gameObject.name} to {other.transform.name}");
                    Attach(ref AttachTo[a], other.transform, ref component.Host[h]);
                    isAttached = true;
                    return;
                }
            }
        }
    }
}
wide terrace
fervent jacinth
#

pitch & yaw are the floats

#

mouse x and mouse y

wide terrace
#

ah right ๐Ÿ‘

wide terrace
# fervent jacinth mouse x and mouse y

I'm much rustier than I thought. But I'll play with it a bit. I think Steve was on the right track - it seems like the rotation needs to be made relative to the player's current orientation rather than working in world-space

fervent jacinth
#

thats what i thought too, with the Space.Self in the transform.rotate

#

i just cant find a way to do that with quaternion.angleaxis

wide terrace
#

I wonder if you could just like

transform.rotation = Quaternion.RotateTowards(
  transform.rotation,
  transform.rotation * Quaternion.Euler( pitch, yaw, 0f ),
  drag * Time.deltaTime
);
plain moon
#

What's wrong with Application.targetFrameRate?
When I set 60 I've got 45 (in my 90HZ android)
When I set -1 I've got 30
When I set 90 I've got 70+ (good)

Optimized Frame Pacing is turned off
vsync is 0

dusk apex
plain moon
#

I test in on my android device

#

I don't get reason of this issue. I used it all time before and have no problem, but now Optimized Frame Pacing was added and etc.?

dusk apex
deep oyster
#

Is there a good way to detect this sort of scenario? The character's circle collider on the corner of a square collider? I have some code to provide a little boost if moving to the right in this situation so you can climb onto the ledge instead of getting stuck on the corner, but right now I'm doing this with like, sending down a ray from each side of the character and testing distance and that's pretty gross and doesn't work in certain situations

#

I'm using the same raycasting technique to detect the slope of whatever ground I'm on and I assume there's gotta be a better way

woeful spire
nocturne dawn
#

I have a top down game and I made a object transparent but I only want the transparency to be for another specific gameobject is that possible to do easily? Like have it for example when a enemy goes through a powerup it will show the enemy through it but not the lines of my ground

sly ivy
#

Hi, so I'm completely stumped over an error Im getting exclusively in build. Im working on a sort of music playlist. It works completely fine within editor but when in build, it gives me index out of bounds in the array error

#

which makes no sense cus it works completely fine within editor

#

Console points me at this specific part of the code: ```
public void ChangeSong(int trackPicked)
{

    //Tracks the clips that have been played and plays in random order.
    if (!beenPlayed[trackPicked])
    {
        tracksPlayed++;
        beenPlayed[trackPicked] = true;

        playlist.clip = tracks[trackPicked];
        curIndex = trackPicked;
        playlist.Play();

        DisplayTrackName();

        //DEBUG SECTION
        Debug.Log("Changed track");
    }
    else
    {
        playlist.Stop();
    }
}
vivid halo
#

Set a breakpoint on the line that is giving the out of index error and observe the index (int trackPicked) and the list beenPlayed

sly ivy
#

Its saying that the line if (!beenPlayed[trackPicked]) is the cause

vivid halo
#

The list beenPlayed has less items than the value of trackPicked when you run the project

#

This can happen if beenPlayed is not properly initialized or is reset through another script

sly ivy
#

how is it that there's no error in editor then if this is a problem but only in build?

vivid halo
#

Set a breakpoint on the line that is giving the out of index error and observe the index (int trackPicked) and the list beenPlayed

#

There is likely a difference in how beenPlayed is initialized or set

#

Checking the debug information is the only way to tell for certain why the list access appears to be out of range

sly ivy
#

how would I be able to observe trackpicked since its not a public variable?

#

(sorry fairly new to coding)

vivid halo
#

By setting a breakpoint. Try this:

#

This pauses the execution of code at a particular line when that line is run

#

Then, you can observe the value of all variables while debugging

sly ivy
#

right but then unity freezes up for me so I cant really interact with unity in that state

vivid halo
#

That is the point

#

When it is frozen, that is when it is breaking.

#

You can also set a conditional breakpoint so it only stops when the integer trackPicked is greater than tracks.Count()

#

When unity freezes, you go into your code editor and observe the line of code that has frozen (as per the intention of your breakpoint) and then you can mouse over the variables to observe their values

sly ivy
#

ok

#

So it says trackPicked is 1

#

beenPlayed[3]

#

well

#

Bool[3]

#

is what its saying beenPlayed is

vivid halo
#

That should work.

#

Press continue and wait for it to loop around again.

#

It should do a loop and come back to beenPlayed when the trackPicked is a different number, and repeat this process until trackPicked is greater than or equal to 3, which should break the code by throwing an index out of range exception

sly ivy
#

trackPicked = 2

vivid halo
#

Continue once more, and note that 2 is the highest value that you can safely access the list beenPlayed

#

As soon as trackedPicked is 3, then the code should break.

sly ivy
#

nope

#

goes from 0 - 2

vivid halo
#

Ah, I see your error

#
tracksPlayed++;
beenPlayed[trackPicked] = true;
#

It's actually this line

#

2 is the maximum

#

But you increment 2 to 3

#

And then try to access beenPlayed[3] which does not exist

sly ivy
#

hmmm but that shouldnt be an issue either

vivid halo
#

That should be an issue

sly ivy
#

I have this running too at the same time to counter that

#
    {
        if (tracksPlayed == tracks.Length)
        {
            tracksPlayed = 0;
            for(int i = 0; i < tracks.Length; i++) 
            {
                if (i == tracks.Length)
                    break;
                else
                    beenPlayed[i] = false;
            }
        }
    }```
vivid halo
#

If beenPlayed has 3 items
Then:
beenPlayed[0] is valid
beenPlayed[1] is valid
beenPlayed[2] is valid
beenPlayed[3] is invalid

int trackPlayed = 2;
You enter the main loop checking if beenPlayed[trackPlayed] is valid
beenPlayed[2] is indeed valid
Then you increment trackPlayed by 1, so trackPlayed is 3
Then you set beenPlayed[3] to true, but you can't because beenPlayed[3] does not exist, and this throws an out of range exception.

#

In this block of code:

if (!beenPlayed[trackPicked])
        {
            tracksPlayed++;
            beenPlayed[trackPicked] = true;
            // Rest of code

What happens if trackPicked is equal to the very last item in the beenPlayed array, and the 'if' statement evaluates to edit: true, and you enter the block?

#

It necessarily throws an error.

sly ivy
#

Right, how would I be able to fix that then?

#

embed an if statement?

vivid halo
#

Basically. Check whether beenPlayed's length can support the index access attempt

#

If there are 3 items in beenPlayed, then the maximum index access value is 2, which is beenPlayed.Count() - 1

#
if (tracksPlayed <= beenPlayed.Count() -1)
{
  beenPlayed[tracksPlayed] = true;
}
// Rest of code. Do not attempt to access beenPlayed at an improper index further in this code, such as later when you access another index similarly via playlist.clip = tracks[trackPicked]
sly ivy
#

Nope, still same

#

I give up, thanks for the help though

#

appreciate it

gloomy helm
#

how could i rotate an object towards velocity only on the y axis without changing the other values

#

it makes both x and z values 0

leaden ice
#

Use that in Quaternion.LookRotation

silent tapir
#

why are the borders thicker in some spots? I am using a tiled imaged btw.

pastel patio
#

Hey guys, I just wanna confirm something- There's nothing bad about putting biome scripts as monobehaviours in the scene, right?

pastel patio
#

Originally I thought to use scriptable objects, but since I decided that it's better to hardcode each biome's generation code, it feels very wasteful to make a class for a scriptable object if I'd only make 1 instance of it

#

So the other way would be considering them as a singleton (monobehaviour)

#

Right, forgot, the reason why I need those scripts to be scriptable objects/monobehaviours is because I want to be able to customize it in the inspector.

young tapir
#

Is there a reason subscribing to events within coroutines doesn't work? I can subscribe just fine in the switch case but if I do it in a coroutine I just get a NRE for some reason. (I'm aware it says Event1, not Event. I'm only using that as an example)

#

It's not a problem, I'm just kind of curious

pastel patio
#

Basically the context is this:

  1. I've got a biome system
  2. All the biomes are different implementations of the same base class
  3. I want to be able to customize the biome settings in the inspector
  4. Each biome script only need 1 instance, or be a static class
  5. What should biome be? A singleton, scriptable object, something else?
pastel patio
lean sail
# pastel patio Basically the context is this: 1. I've got a biome system 2. All the biomes are ...

What do you mean each biome script only needs 1 instance, is this something only for 1 scene?
I'd probably go the scriptable object route, but really you're gonna be plugging these into a monobehaviour somewhere. The scriptable object part just makes it so when you edit values, you're editing the asset and not some random component in a scene. Makes it easier to see in git history for example

pastel patio
pastel patio
#

Making a button that only ever would be clicked once?

#

Cus I only need 1 instance of it, ever.

#

By button I mean something like: 'Create -> Biomes -> New Molten Lands'

lean sail
#

So? What resource is it wasting? The user will never see it. You'll never have to worry about it past doing it once

#

If you dont want the extra assets associated with creating a scriptable object script + instance for its data then simply dont use a SO. it's not some life changing decision here. You're basically choosing between having numbers on an asset, then taking the numbers from that asset, or just directly having them on the component to start with.

pastel patio
#

Fair enough...

#

Well, ig I'll go the scriptable object route

#

The git stuff is indeed a valid point to use Scriptable object... Considering that otherwise all modifications will be counted as scene modifications

#

The only other way, when using Monobehaviours is have it as a prefab, which would be very much comparable to SO, besides saving extra unnecessary data.

lean sail
# pastel patio The only other way, when using Monobehaviours is have it as a prefab, which woul...

The use case does seem small enough that you could also just put these all in the scene with no issue. If you dont have any specific state associated with each biome during its generation too then you could get away with having 1 monobehaviour and N scriptable objects. The use case does seem small enough that you could even put these directly as monobehaviour.
Though if you ever need to reference these monobehaviours from like a game manager, I find that something tedious to do because now you have to use the find functions or have the instances register themselves somewhere

hard estuary
# silent tapir why are the borders thicker in some spots? I am using a tiled imaged btw.

It happens when the area of an object doesn't allign with the area of pixels. Let's say that the border is 1,4 pixel wide. Since your screen can't split your pixels in half, it has to display it as 1 pixel wide or 2 pixels wide. Also each pixel displays whatever is in the center of the pixel. If some object happens to overlap with centers of 2 pixels, it's displayed as 2 pixels wide. If something misses the center of one pixel, then it's displayed as 1 pixel wide.

gloomy helm
lean sail
young tapir
#

Plus I was holding it in my hand while testing

silent tapir
#

any1 know how to make an icon out of this object but making it not appear like this:
it has the sky in the back even though I culled that out

hard estuary
# silent tapir any fix to it?

Make the game pixel-perfect by perfectly aligning the size and position of every object with pixels on the current screen resolution.

lean sail
young tapir
#

Wouldn't capture anything that isn't part of it

silent tapir
#

interesting you right i might

young tapir
#

I removed most of the code after I got it working in some capacity

lean sail
#

it really isnt weird, you just didnt debug enough of it at the time. if there was an NRE then it is null at the point of you trying to use it.

#

unless you had other errors in the console (deal with errors top to bottom), theres always gonna be a reason as to why this happened. If unity randomly had these errors, itd be a massive deal. It told you something was null, because it was

gloomy helm
#

how could i rotate an object towards velocity only on the y axis without changing the other values

pastel patio
#

You might need to add or subtract the rotation by PI/2.

#

Quaternion in a 2d game is really annoying

#

Eh, wait, it's 3d...

gloomy helm
#

yeah

#

ok wait let me try

lean sail
pastel patio
#

Eh, ig, it looks much easier

gloomy helm
#

and the x axis is zero it should be - 90

pastel patio
#

Even though it's converting from quaternion to euler then back xD

lean sail
# gloomy helm and the x axis is zero it should be - 90

you shouldnt rely on reading euler values in the inspector. First, its local rotation and 2nd its converting from the quaternion to show you euler.
Although in this case (-90,0,0) would be pretty different from 0,0,0 i think thats probably due to local rotation

gloomy helm
#

but the x axis has to be -90

pastel patio
#

Oh, right, reminds me, for my character I just normalize the vector to be flat in the y axis and use that instead

#

Maybe it gives an extra idea

lean sail
pastel patio
gloomy helm
gloomy helm
pastel patio
lean sail
#

well yea you copied a solution which sets X and Z to 0, while only using the x and y of the vector. Did you try what i wrote above?

gloomy helm
#

wait let me try

pastel patio
#

Ah also, you copied mine directly which used x and y haha

#

You needed to use x and z

gloomy helm
#

why x and z

#

not y

pastel patio
#

Because you cancelled y out yourself?

#

So essentially the result is that the formula is working with (x, 0)

#

Wait... No I'm confused fr

gloomy helm
#

oh wait now it works but it rotates the spline opposite of what i want it to be

#

i want is to be like this when walking forwad

pastel patio
#

How to turn it around you think? :)

gloomy helm
#

and this is what i am getting

#

(ignore the one laying on the ground)

pastel patio
#

Eh... Like, if you mean it's 180 deg off, add pi radians to it (Which is essentially 180 degrees)

#

If you mean it's turning towards the opposite direction, then you just have to add a negative sign to the rotation

gloomy helm
#

ok wait let ad pi radians (sorry for late respons my laptop ran out of battery and shut off i had to plug it in)

pastel patio
#

Honestly I'm really confused what your output was meant to be

#

But either way... It's just some basic tweaks left, normally