#archived-code-general

1 messages ยท Page 104 of 1

leaden ice
#

it's not something that happens on accident

urban marsh
#

OK, I think I'm just stupid at this point :
writing PhysicsScene2D.defaultPhysicsScene gives me an error : PhysicsScene2D does not containt a definition for defaultPhysicsScene.

simple egret
#

It's Physics2D.defaultPhysicsScene

leaden ice
urban marsh
#

yeah, I'm getting frustrated with these raycasts.. I need to take a break and breathe a little ๐Ÿ™‚

rough sorrel
#

Hi. One question, does anyone know if there's a way to like interact with something based on where the mouse is?

Like, I want to interact with a 3D button inside an aircraft cockpit. I was currently using a physics raycast, and that worked fine when the aircraft wasn't moving, but when it starts to move, the raycast just doesn't hit anymore, like as if it was lacking behind. Any idea how could I solve that please?๐Ÿ˜…

leaden ice
#

e.g. IPointerEnterHandler / IPointerClickHandler etc.

leaden ice
rough sorrel
#

Oh okay, I've never used that, I'll do some research about it thanks for saying that ๐Ÿ˜„

leaden ice
#

unless you use Physics.SyncTransforms before the raycast to force it to update

#

it can be behind

rough sorrel
leaden ice
#

It doesn't matter - if you've moved the objects in Update then the visual appearance of the object can be ahead of the collider

rough sorrel
#

well the object doesn't move other than being a child of the aircraft itself, but the same happens with the camera, so I thought they would be synced

leaden ice
rough sorrel
#

well it is using a rigidbody with interpolation

leaden ice
#

same issue

#

colliders do not move until the physics simulation step

#

period

#

unless you call Physics.SyncTransforms

rough sorrel
#

okay thank you so much ๐Ÿ˜„

swift falcon
#

@cobalt wave

Quaternion targetRotation = Quaternion.LookRotation (path.lookPoints [pathIndex] - transform.position);
                transform.rotation = Quaternion.Lerp (transform.rotation, targetRotation, Time.deltaTime * turnSpeed);
                transform.Translate (Vector3.forward * Time.deltaTime * speed * speedPercent, Space.Self);
cobalt wave
#

well

#

the only possible explanation I have is that the path is not on the ground

#

have you checked the path points individual position?

swift falcon
#

they're placed on this grid maybe lowering the grid?

cobalt wave
#

yea that should fix it as the grid appears the be obviously "floating"

#

and if the points are centered to the grid, they will be floating too

swift falcon
#

well sorta worked now hes half in the floor

#

ill try just moving it about

cobalt wave
#

why are the waypoints on a grid though?

swift falcon
#

A* Pathfinding

#

and yeah that did fix it thanks

cobalt wave
#

ohh

#

nice trying to implement your own

swift falcon
#

it works well mostly

#

like it does find the paths and avoids stuff

#

I am a good modeller I swear i just cant be bothered modelling anything "good" for this

cobalt wave
#

I'd suggest having some checks for the ground to avoid these sort of issues
instead of having the points be centered to the grid, raycast both up and down (to find the ground) and move them to the hit point

swift falcon
#

yeah that might be a smart idea

#

i've rushed it since its just a school project due in a few weeks lol

cobalt wave
#

oh, well then keep that in mind and if you have extra time, add it in :)
i'm sure it'll yield a few extra points

swift falcon
mental pumice
#
    [SerializeField] private GameObject enemyPrefab;
    [SerializeField] private float minSpawnInterval;
    [SerializeField] private float maxSpawnInterval;
    [SerializeField] private float startDelay = 2f;
    [SerializeField] private float minX = -10f; 
    [SerializeField] private float maxX = 10f; 
    [SerializeField] private float minY = -10f; 
    [SerializeField] private float maxY = 10f; 

    private Camera mainCamera;
    private float cameraWidth;
    private float cameraHeight;
    TimerManager Timer;


    void Start()
    {
        mainCamera = Camera.main;
        cameraHeight = 2f * mainCamera.orthographicSize;
        cameraWidth = cameraHeight * mainCamera.aspect;

        StartCoroutine(DelayedSpawnEnemy());
    }

    void Update(){
        
        if (Timer.currentTime < 10){
            minSpawnInterval = 0.5f;
            maxSpawnInterval = 0.5f;
        }
    }

    IEnumerator DelayedSpawnEnemy()
    {
        yield return new WaitForSeconds(startDelay);

        StartCoroutine(SpawnEnemy());
    }

    IEnumerator SpawnEnemy()
    {
        while (true)
        {
            Vector2 spawnPosition = new Vector2(
                Random.Range(minX, maxX),
                Random.Range(minY, maxY)
            );

            Instantiate(enemyPrefab, spawnPosition, Quaternion.identity);

            yield return new WaitForSeconds(Random.Range(minSpawnInterval, maxSpawnInterval));  

        }
    }
``` hello guys, i want to make in every 10 second decreasing the minSpawnInterval and maxSpawnInterval by 1 how to make it?
heady iris
#

another coroutine

mental pumice
#

:)

magic parrot
#

That's the exact error I'm dealing with

#

I think I found a solution tho

sharp oasis
#

Anyone knows the code that a 2D gameobject follows your MousePosition?

magic parrot
magic parrot
#

Look it up on google

sharp oasis
magic parrot
#

Dming you solution, one min

heady iris
#

i have an idea for a cool effect that I'm not sure where to start with.

i want enemies to "shatter" when destroyed -- actually turning into a 2D image that shatters into fragments

#

i feel like i need to do something like...

  • render just the enemy to a render texture
  • identify the opaque areas and create a mesh that covers it
  • cut that mesh up
#

the enemies are 3D objects

stuck glacier
#

i dont have much experience with character controllers but, i have to ask, why do people use it over a rigidbody? it handles physics for ya (still needs some tinkering) with some work, it can feel really smooth in any context
only benefits of a character controller ive seen is the slope and stair handling thing it has going on, and that it's easier to set up. but i would never use it on a game that has any form of gravity and light physics.

heady iris
#

i use character controllers in games with gravity all the time

#

the character controller isn't simulated by the physics system, so it behaves more predictably

stuck glacier
#

there's a lot of measures that can be taken to prevent rigidbody jankiness

heady iris
#

sure, but if the core problem is "I do not want this to be affected by physics", then the character controller does exactly what you want

high briar
#

quick question, if I convert a gameobject with a ghost authoring component to a entity, will all its children have their position/rotation networked, or just the parent?

tame iris
#

I am allowing users to pick audio file and play it, It is working perfectly fine but some audio is not playing. like audio with missing bitrate.

https://gdl.space/ijinipeqis.cs

How do I fix this?

winged mortar
#

!code

tawny elkBOT
#
Posting code

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

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

unborn fern
#

can anyone help with this? (available to ping)

potent sleet
#

ask photon server

tardy trail
#

kk thx

potent sleet
unborn fern
potent sleet
unborn fern
#

i have read all of this

potent sleet
#

?

#

also this is not a code question

unborn fern
#

i guess but where else would i ask for help

potent sleet
#

n follow what the log is saying

smoky pike
#

how do i convert a pixel value to the unity world space value? I currently have the height of my phone in pixels, but need to convert that to the unity coordinate value

smoky pike
lean sail
#

your screen coordinate is not a single value, and the z is just used for depth

#

the height of your phone is not 1 pixel either, u can imagine it as a row of pixels

hexed pecan
#

Or define a Z position if you need depth

hybrid relic
#

Why is my Unitys Math not mathing

#

im multiplying negative gravity by deltatime and im getting a positive value#

#

like what

heady iris
#

gravity is negative...

hybrid relic
#

playerVelocity.y += gravity * Time.deltaTime;

somber nacelle
#

is your gravity variable actually negative though

heady iris
#

at least, you tend to represent it as a negative number

#

you should inspect the actual values...

hybrid relic
#

it is

heady iris
#

check the inspector

somber nacelle
#

what is the value in the inspector

heady iris
#

that's just the default value

#

the value saved on that instance of the component may be different

#

e.g. if you originally wrote [SerializeField] float gravity = 9.8f

hybrid relic
#

bruh its 3.51 in the inspector, who did this, imma go ask my other teammembers

#

thanks i feel so stupid now cuz i overlooked such a simple thing

#

i was wondering why i was slowly going up instead of falling

lean sail
#

check your version control logs if u really need to see who did it

#

(pls dont say you dont use version control)

hybrid relic
#

nah its a small team, its all friends

#

idc prolly a mistake

lean sail
#

at least with git u can see a specific line and see the commit it was changed in

hybrid relic
lean sail
#

unlucky

hybrid relic
#

why plastic works fantastic

#

never had any issues

heady iris
#

i always had a 50-50 shot on being able to switch to a different changeset

#

"error: file is missing!!!"

#

yes, plastic, i just deleted it

#

that might be more of a problem with the integration with unity

lean sail
#

idk my entire opinion on plastic is based on the fact many people have had a version bug with it in unity lol

heady iris
#

i would also get random popups about the workspace being locked (or some words to that effect)

#

i just use git without any unity integration now

lean sail
#

i dont understand the need for unity integration anyways, github desktop is simple enough to not make major mistakes

hybrid relic
#

Im getting "spammed" with this, in my Debugger and i dont know why...

Cleanup Blit
UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset:OnDisable () (at Library/PackageCache/com.unity.render-pipelines.universal@12.1.11/Runtime/Data/UniversalRenderPipelineAsset.cs:509)

when removing this debug log from code its not saving it aswell cuz its in an dll file
Edit: could remove 2 from LootLocker Addon, but cant edit the file from urp

worn holly
#

So, for some reason my unity isn't detecting anything phone-related(Input.touch, IDragHandler), the correct android modules are instaled and the build settings have been switched to android, does anyone know what the problem could be? I wrote a simple touch detector to test and it didn't register.

vestal summit
placid ermine
#

Hi, I have a TMP_InputField and I am trying to listen to changes on it cs _searchBar.InputField.onValueChanged.AddListener(delegate { listener(); });
and it gets called whenever I type characters except when I delete the last one. Why wouldn't it be sending onValueChanged when it goes to blank? It does have a placeholder text.

cerulean oak
#

I am using the firebase realtimedatabase unity package.
when I call


var task = DatabaseReference.GetValueAsync();
task.Wait();

On a field that doesnt exist, instead of getting back a DataSnapshot, that has a null value and Exists to false, task.Wait() never finishes

#

anyone has any clue why?

simple egret
# vestal summit

The size you pass to new List<T> is the initial capacity. It'll grow as items get added up. If item count goes past the capacity, capacity is doubled.
If you want to shrink the capacity to the item size, use the TrimExcess() method. Note that this creates a new array internally to fit the new items in, creating some garbage to be collected.

#

Note that the capacity and item count are different

tulip fjord
#

hey, its quit a while. i have a problem with transformAccesArray. can i post my question here?

vestal summit
#

this is an inventory system. I made so that after adding another item that goes beyond the list size it won't add another number to the size

#

and I want to configure the inventory size aka the list size by a script

simple egret
#

If the slot count may not change after it's created, then use an array InventorySlot[] instead.

vestal summit
#

in a click of a button it should go down WITHOUT deleting the content in it

#

aka the items

#

and the slot count changes it's ok but the items aka content deletes inside it which I don't want

#

plus this is the way I tried to change the size of the list

#

it is wrong cause of the new

#

the new just gonna make a new list

#

is there any way to using something else?

#

you said arrays but I don't want to rewrite the whole system

hard estuary
vestal summit
simple egret
#

You usually don't change the size of a list. It's done as you add or remove items, it's not really a size

vestal summit
#

not increase the size

vestal summit
#

the inventory system needs a limit

#

so I made it have a limit

simple egret
#

Where? I don't see code that limits the size

hard estuary
scarlet talon
#

I think it's fine to make a new list, you just need to repopulate it, right?

vestal summit
vestal summit
tulip fjord
#

you can also copy a list to array, or to a new list.

scarlet talon
#

This is what I was trying to say but somehow omitted that

tulip fjord
#

or use removeAt, or insert

vestal summit
#

I never used arrays. Can you change the count in there somehow?

#

like the size or whatever

tulip fjord
vestal summit
#

the thing that I'm trying to achieve

tulip fjord
#

they have length

scarlet talon
#

No, you need to create anew array

simple egret
#

At this point it's just like having a fixed size, that can change once or twice over time. So an array, and to change its size there's Array.Resize()

vestal summit
#

resize? Explain a little further

hard estuary
# vestal summit so I made it have a limit

The size of the list increases every time someone tries to add a new item to it when it's full. It doubles it actually. E.g. if you have 4/4 items, then add another one, the capacity will increase to 8.

You can use .TrimExcess() to reduce its capacity.

vestal summit
#

I didn't use trimexcess. I just prevented the player from picking up the item when the list is full or the inventory is full

simple egret
# vestal summit resize? Explain a little further

Arrays have a fixed size. You cannot add or remove elements. You can only set an element at a specific position.
Arrays do not have Add or Remove methods like lists do. If you need to have more or less elements, you need to resize them using Array.Resize

vestal summit
#

yeah so I can't use arrays then

#

I'm stuck with lists

#

I thought changing the size is easy thought?

#

I just couldn't figure it out :P

simple egret
#

They. Have. No. Size

scarlet talon
#

Arrays are perfect for inventories

vestal summit
#

I call it size :P

dusk apex
#

You need to describe exactly what you're wanting.

simple egret
#

Having an inventory with a variable slot count isn't usual

#

Bear in mind, not the item count inside a particular slot

#

The slot count itself

vestal summit
#

ok I'll explain it a little further as much as I can

vestal summit
# vestal summit

you see those element thingys. Those are inventory slots. Right now what I'm trying to achieve is remove some of those elements or slots whatever you want to call them.

tulip fjord
# tulip fjord hey, its quit a while. i have a problem with transformAccesArray. can i post my...

this is the way im using the transform-job-thingy: ``` public TransformAccessArray transformArray;
void OnDestroy()
{
transformArray.Dispose();
}
IEnumerator Start()
{
transformArray = new TransformAccessArray(spawner.liste.activatedFriendly.Count);
}
void Update()
{
var job = new carJob
{
somevariables
}
JobHandle jobHandle = job.Schedule(transformArray);
jobHandle.Complete();
}````
this is suddenly causing memoryleaks since i was updating to 2022.2 . i read that this warning can be ignored, but its crashing unity if im using another script that is using overlapsspherecommand inside another job

scarlet talon
#

You mean empty them?

vestal summit
#

I might have tried to explain this stuff way too quickly earlier. Sorry

vestal summit
tulip fjord
vestal summit
#

but there was a problem

#

the items in it got removed too

simple egret
#

Yeah that's normal. Changing the size in Unity re-creates a brand new list

vestal summit
#

the issue is obvious

tulip fjord
vestal summit
#

I'm creating a new list cause I don't know any other way to remove the elements

#

which is why I'm asking for help

hard estuary
#

@vestal summit
.Count - how many items are in List (includes nulls)
.Capacity - how many items should fit into the list before it has to automatically double it size
.TrimExcess () - cuts the Capacity to Count
.Remove (T) - removes T from the list
.RemoveRange (Int32 count, Int32 index); - removes count items from the list starting from the index index
list [i] = null; - changes the list slot at index i to null

simple egret
#

You can create your own Resize function that will execute inventorySlots.RemoveAt(n) where n is a specific index

#

That way you always use the same list

vestal summit
#

by the way why are arrays better than lists for inventory systems. You can't add a specific item from scriptable objects

tulip fjord
#

its another datatype

simple egret
#

Most inventories use arrays because the slot count never changes

vestal summit
simple egret
#

But for you it does, so arrays are out

vestal summit
#

the slots will change in my game

vestal summit
hard estuary
vestal summit
#

ok so I'm just trying to remove the items

simple egret
#

So re-create a custom Resize(int count) method on your InventorySystem, that calls Add() or RemoveAt() on your list, depending on whether the new count is greater or smaller than your current count

#

If the new count is smaller, then repeatedly remove the item at the end of the list until both counts are equal
If the new count is larger, repeatedly add a new slot at the end of the list until both counts are equal

vestal summit
#

yeah I understand

#

I'll try that

hybrid relic
#

What site to use if posting longer code ? i dont want to spam chat

#

and there is no site pinned

inner pine
#

could do a github jist or pastebin if you like

simple egret
#

"read me", the least read channel, shame

hybrid relic
#

!code

tawny elkBOT
#
Posting code

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

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

tulip fjord
hybrid relic
#

yeah works thanks @simple egret

tulip fjord
hybrid relic
#

So im having an issue, both my isCrouching and isSprinting get sucessfully changed by the button, but for isSprinting it doesnt apply the new tempspeed, it runs into the if case but doesnt like put sprintSpeed onto speed...
https://gdl.space/efepiqoqux.cs

#

it stays on 5f, but if Crouching is pressed it successfully removes 2.5f, idk what is happening

#

am i just very blind and missing something obvious ?

tulip fjord
#

if (isSprinting) { tempspeed = speed + sprintSpeed; }else { tempspeed = speed;}
Debug.Log(isSprinting);
if (isCrouching) { tempspeed = speed + crouchSpeed; }else { tempspeed = speed;}

simple egret
#

The else on line 34 is doing it

#

Resets the speed to default

tulip fjord
#

use a switch statement

simple egret
#

Or an else if

hybrid relic
#

yeah i might borked it with that unneeded else i just realised

#

while looking over it again, let me test

#

yeah

#

my brain was not braining

#

1am brain is real

#

thank you two

simple egret
#

Damn yeah it's actually 1am

#

Gotta go to bed

inner pine
#

the phenomenon of instantly figuring out what you did wrong as soon as you try to explain it is well known

hybrid relic
tulip fjord
#

where can i find related issues to my problem? i cant find anything on the net and i really dont know if its a bug and the method was introduced a month ago. -> 2022.2 is not lts, but its also not an experimental alpha (2023)

tulip fjord
# tulip fjord where can i find related issues to my problem? i cant find anything on the net a...

this is the crash report snippet ```0x00007ffbca67ecdc (mono-2.0-bdwgc) mono_runtime_invoke (at C:/build/output/Unity-Technologies/mono/mono/metadata/object.c:3113)
0x00007ff7605858d4 (Unity) scripting_method_invoke
0x00007ff760566344 (Unity) ScriptingInvocation::Invoke
0x00007ff76054dc84 (Unity) MonoBehaviour::CallMethodIfAvailable
0x00007ff76054ddaa (Unity) MonoBehaviour::CallUpdateMethod
0x00007ff75ffeae4b (Unity) BaseBehaviourManager::CommonUpdate<BehaviourManager>
0x00007ff75fff265a (Unity) BehaviourManager::Update
0x00007ff76021b82d (Unity) InitPlayerLoopCallbacks'::2'::UpdateScriptRunBehaviourUpdateRegistrator::Forward
0x00007ff760201e3a (Unity) ExecutePlayerLoop
0x00007ff760201fc6 (Unity) ExecutePlayerLoop
0x00007ff760208815 (Unity) PlayerLoop
0x00007ff7611b2ccf (Unity) PlayerLoopController::InternalUpdateScene
0x00007ff7611bfa1d (Unity) PlayerLoopController::UpdateSceneIfNeededFromMainLoop
0x00007ff7611bdd21 (Unity) Application::TickTimer
0x00007ff76164b02a (Unity) MainMessageLoop
0x00007ff76164fdd0 (Unity) WinMain
0x00007ff762a3395e (Unity) __scrt_common_main_seh
0x00007ffc58fa26ad (KERNEL32) BaseThreadInitThunk
0x00007ffc5a08a9f8 (ntdll) RtlUserThreadStart

#

maybe i shouldnt use transformaccsessarray while using spherecast

vestal summit
rocky shoal
#

In a Unity 2d project, I have 8 items in a grid layout group. Can an item besides the last one ever be the "top most" (closest to the camera) one? If so, how?

#

Basically I have a hand of cards that are curved and overlap, that scale up on hover and I want them to appear in front of the cards beside them.

somber nacelle
#

if they are UI objects then they are drawn in the order they appear in the hierarchy so lowest one in the hierarchy is drawn last or on top. also #๐Ÿ“ฒโ”ƒui-ux

uncut tundra
#

can anyone tell me why vscode is telling me that this class doesnt exist when it is in the project

somber nacelle
#

open the PlayerData file and make sure the class is actually called PlayerData

uncut tundra
#

it is

somber nacelle
#

is it in a namespace you have not imported in this other file?

uncut tundra
#

its not in a namespace

#

even unity doesnt give me errors

lean sail
#

whats the error you're seeing?

somber nacelle
#

have you actually saved for unity to attempt to compile to show errors?

uncut tundra
#

yes

#

i have

#

this is the error

somber nacelle
#

share both classes with a bin site

uncut tundra
#

k

somber nacelle
#

ugh of course it's pastebin with no syntax highlighting.

#

try regenerating project files

#

or restart vs code

#

or just use a better IDE that doesn't break for no reason

uncut tundra
#

ive restarted it already

#

how do i regenerate

somber nacelle
#

it's in the external tools settings

uncut tundra
#

it works now

#

thanks!

fickle lichen
#
IEquippable? equippableItem = other.gameObject.GetComponent<IEquippable>();

if (equippableItem is not null)
{
    PickUpItem(equippableItem);
}
else
    print("equippable item is null");
```Are nullable annotations being used in Unity? I saw scripts for null check but variable types are not null-capable (without question mark or not Nullable<T> class). Am I asking clearly? ![beluga](https://cdn.discordapp.com/emojis/1092430758720835615.webp?size=128 "beluga")
somber nacelle
#

no, you do not need to mark reference types with ? for them to be nullable in unity. however you should also not be using the is operator to check for null on UnityEngine.Object types (i know the interface doesn't derive from UnityEngine.Object but the component it is implemented on does)

fickle lichen
# somber nacelle no, you do not need to mark reference types with `?` for them to be nullable in ...

Yeah, I'm aware Unity is overloading == operator and null check is a bit different, but as you noticed it's an interface so I put is not null.
Earlier I was doing desktop applications with Windows Forms and putting ? was a daily routine, here in Unity I don't see it anywhere. You said I do not need to mark them as nullable, but why? Are all objects deriving from UnityEngine.Object nullable by default? (Also thanks for answering my question, after 3rd try only you bothered to answer Pepe_Pray)

somber nacelle
#

all reference types are nullable by default. that's how the language has worked since the beginning

quartz folio
#

The actual object is not an interface, it's a real thing that is a component

fickle lichen
#

aniblobsweat okay, I guess I'm slowly starting to understand

somber nacelle
#

it's only c# 10 that has nullable reference types enabled by default, and it wasn't even introduced until c# 8

fickle lichen
#

As I said I was doing Windows Forms earlier with .NET 7 so I guess it was either C# 10 or C# 11 beluga and as I said, I was using nullable annotations almost everywhere

#

Anyway, thank you both for answering my question!

quartz folio
#

To be clearer about nullable reference types, the question mark only actually makes something Nullable<T> when it's a value type. For reference types it just informs the compiler to give you static analysis, hints basically, and provides no actual nullability (as reference types can already be null), it only helps protect you against null reference exceptions if you've got the static analysis available and follow its instructions; which isn't aware of how Unity's working with it's fake null object

fickle lichen
somber nacelle
fickle lichen
#

Windows Forms seemed easy and I didn't need any compatibility for other operating systems

#

I know it's old and there are better options but as I said, I found it easy and it's not a big program anyway, a couple of forms, some scripts under the hood (about 1,000 - 3,000 lines of code) and that's it

#

Unity is stuck on C# 8 and partially supporting C# 9, right? aniblobsweat

somber nacelle
uncut tundra
fickle lichen
#

SerializationException: Attempting to deserialize an empty stream. PepeThink

lean sail
#

it tells u the error, the stream is empty

uncut tundra
somber nacelle
#

okay, and if your players decide they want to share save files (which is fairly common) then because you chose to use BinaryFormatter then they potentially open themselves up to malware

uncut tundra
#

ok

#

if i can figure out how to switch ill do it

uncut tundra
#

and idk how to fix this

#

nevermind, im gonna be encrypting it in json and give up on the binary system so

lone umbra
#

can I instantiate a mesh multiple times that I generated in runtime?

#

Generated mesh is fine, but when I instantiate it all their meshes seems to be empty, well not empty but it has no tris and faces

leaden ice
lone umbra
untold quail
#

Hey guys, I've been wracking my head over this for the past 4 hours and its going nowhere, i've built a generator that creates "province" gameobjects based on a colormask by doing Texture2D.GetPixel and then using it as an index, issue is i'm trying to get the provinces to actually highlight once clicked based on their shape in the colormask and i havent been able to find a good way to do that, does anyone have any ideas/advice?

leaden ice
#

Are you talking about mesh renderers?

#

Don't confuse meshes with MeshRenderers

lone umbra
#

Its was simplified writing

#

Code -

#

_fogOfWarTile is whats generated in code, and fow is the Instantiated one

leaden ice
lone umbra
leaden ice
#

You can't add components to a Mesh

#

And what exactly is the issue again?

lone umbra
#

I'm not adding components to a mesh, I make a mesh, make a new GameObject, add Mesh Filter and Meshrenderer to it, add the Mesh to the MeshFilter, add add other components i need for it on it, then I'm trying to Instantiate this new GameObject. Everything seems to be there all the componenets and the Mesh Filter and Renderer, it even has the Mesh name in MeshFilter that I generated, but the mesh in Instantiated GOs are empty (no tris, no faces etc). And the fixed that by doing the above code

solemn raven
#

hey,
is it possible to add items to a list of 10 items in reverse ?
like add item to the list at the 10th spot then 9th , .... 1st ?

lone umbra
leaden ice
leaden ice
tawny mountain
#

Hello all ,been a while since I've been on ... Can someone tell me why I'm getting this error?

leaden ice
#

But it just looks like you never declared that variable

tawny mountain
#

just says it doesn't exist in the current context

leaden ice
#

All of the declarations are inside preprocessor directives which are false

solemn raven
tawny mountain
#

Can I use those if statements at the top

solemn raven
leaden ice
#

So the variable has not been declared

tawny mountain
#

private readonly?

leaden ice
tawny mountain
# leaden ice You need an unconditional else preprocessor directive

Isn't that what I have in the image above?

#if DEVELOPMENT_BUILD && UNITY_ANDROID
        string adUnitId = "ca-app-pub-/";
#elif DEVELOPMENT_BUILD && UNITY_IPHONE
        string adUnitId = "ca-app-pub-/";
#elif UNITY_ANDROID
        string adUnitId = AdMobIDs.ANDROID_BANNER_ID;
#elif UNITY_IPHONE
        string adUnitId = AdMobIDs.IOS_BANNER_ID;
#endif
leaden ice
#

And none of the conditions are true

#

You need an #else

tawny mountain
leaden ice
#

Just looking at your IDE the target will be UNITY_EDITOR

lone umbra
visual fractal
#

Why does unity keep giving me the error "You are trying to save a Prefab that contains the script 'FirstPersonAudio', which does not derive from MonoBehaviour. This is not allowed.
Please change the script to derive from MonoBehaviour or remove it from the GameObject 'First Person Audio'"? The script does derive from MonoBehaviour. I am confused. Code is https://paste.ofcode.org/yvhX22jd68czWvnLXQDXkK

#

And while I'm asking for help, what does this error mean? 'StatsBar' does not contain a definition for 'bar' and no accessible extension method 'bar' accepting a first argument of type 'StatsBar' could be found (are you missing a using directive or an assembly reference?) Code is https://paste.ofcode.org/KwhfTGy4Qns53i4pRi7rPB

prime sinew
#

I'm assuming the error is from this line
HealthBar.bar.fillAmount = Health / 100;

Where HealthBar type is StatsBar, but StatsBar has no public variable called bar

visual fractal
visual fractal
prime sinew
#

You're using something that doesn't exist

#

How can you not be sure? You just blindly typed what the tutorial did?

#

It's just checking if StatsBar has a bar variable

#

Do you know what a variable is

visual fractal
prime sinew
#

I highly suggest you go through the unity beginner scripting course on Unity Learn first. You need to have a basic understanding of your code at least if you want to be able to act on the help people give

visual fractal
#

Ok...

prime sinew
lone umbra
visual fractal
lone umbra
#

Ok and StatsBar?

#

also if your Visual Studio is not linked with Unity, PLEASE do so

#

It will tell you what you doing wrong

visual fractal
lone umbra
visual fractal
lone umbra
#

Should be - HealthBar.Bar.fillAmount = Health / 100;

#

not - HealthBar.bar.fillAmount = Health / 100;

visual fractal
#

Ok. Thanks. I'm bad at capitalization.

tawny elkBOT
#
๐Ÿ’ก IDE Configuration

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

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

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

visual fractal
prime sinew
#

Try restarting your IDE too

lean sail
#

You also need to open files strictly through unity

rich harbor
#

Question, is it worth it to turn a little sequence like this into something that uses unity's timeline?

topaz gate
#

Hello I would like some help here is a small video of what it is i dont know how to explain it lol

#

The red text goes away after 3 or more characters ire in the join input field but not when in the create input field??

#

They use the same code

#

Just modifyed so it should work

#

Here it is

lone umbra
#

where are you calling ShowMessage1 and ShowMessage2?

topaz gate
#

In the Update

#

ShowMessage1 is for create and 2 is for join

lone umbra
#

well simple, you are calling both of them separately, it checks if Create has 3 letters (it doesnt ) so it sets it to true, then Join has three letters so it sets to false, and true and false, and true and false .........

Fix -

public void ShowMessage()
{
          if (Create.text.Length >= 3 || Join.text.Length >= 3)
        {
            Message.SetActive(false);
        }
        else
        {
            Message.SetActive(true);
        }
}
#

have just one function

#

and check both in one

chrome saffron
#

c# is such a trash language ngl

#

so static

topaz gate
chrome saffron
#

only learning this because of unity. dont they have an option for python or something?

lone umbra
topaz gate
lone umbra
#

well

#

you need to call the function too

topaz gate
#

Oh yeah my silly brain lol

#

Thank you friend! it worked

ashen yoke
#

youre only going to be paying about 100x performance cost for the same ops

#

probably more

lone umbra
#

and code that no one can read

daring cove
#

Hey,

Is it possible to make an editor script that listens for a specific script added to game objects?
Or how to get a list of all game objects in edit mode?

ashen yoke
#

SceneManager.GetActive().GetRoots()

#

you can register the script in an editor static

#
void OnEnable(){
#if UNITY_EDITOR
MyEditorScript.Register(this);
#endif
}
#
UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects();
#

for editor

daring cove
#

Thank you,

#

How can set values for scripts in editor mode?

ashen yoke
#

example?

#

you just get the component, set whatever values you need

#

then EditorUtility.SetDirty(component)

daring cove
#

This is what I have now.
But it doesn't increase the value in game objects with the script PersistantValue

    public class PersistantEditorValueGenerator : Editor
    {
        public int persistantValuePointer;

        private void OnSceneGUI()
        {
            GameObject[] gameObjects = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects();

            foreach (var lGameObject in gameObjects)
            {
                PersistantValue persistantValue = lGameObject.GetComponent<PersistantValue>();
                
                if(persistantValue.value == PersistantValueSettings.NO_VALUE) OnAddPersistantValue(persistantValue);
            }
        }

        private void OnAddPersistantValue(PersistantValue persistantValue)
        {
            EditorUtility.SetDirty(persistantValue);
            persistantValue.value = persistantValuePointer + 1;
        }
    }

PersistantValueSettings.NO_VALUE = -1

ashen yoke
#

first set value, then set dirty

#

also GetRootGameObjects() returns you roots

#

only root objects

#

you are also doing it every frame

#

what problem are you trying to solve this way?

knotty sun
daring cove
#

Debug.Log is not getting called so OnSceneGUI is not being called either.

[CustomEditor(typeof(PersistantEditorValueGenerator))]
    public class PersistantEditorValueGenerator : Editor
    {
        public int persistantValuePointer;

        private void OnSceneGUI()
        {
            GameObject[] gameObjects = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().GetRootGameObjects();
            Debug.Log($"[PersistantEditorValueGenerator.OnSceneGUI] gameObjects.Length = {gameObjects.Length}");

            foreach (var lGameObject in gameObjects)
            {
                PersistantValue[] persistantValues = lGameObject.GetComponentsInChildren<PersistantValue>();
                foreach (var persistantValue in persistantValues)
                {
                    if(persistantValue.value == PersistantValueSettings.NO_VALUE) OnAddPersistantValue(persistantValue);   
                }
            }
        }

        private void OnAddPersistantValue(PersistantValue persistantValue)
        {
            persistantValuePointer++;
            persistantValue.value = persistantValuePointer;
            EditorUtility.SetDirty(persistantValue);
        }
    }

I'm trying to automatically create persistant values for game objects that need them.

ashen yoke
#

what kind of persistent values

#

what are they for

daring cove
#

for gear placed in the world for example.

ashen yoke
#

runtime id?

daring cove
#

is it persistant so always the same?

ashen yoke
#

im asking about the concept you are trying to implement

#

what would you use the id for? save/load?

#

networking?

daring cove
#

Save and load

ashen yoke
#

editor wont work in build

#

and i assume you will create object at runtime

#

you are doing it backwards

daring cove
#

That shouldn't matter because I wan't the script to assign the values in the editor so that I don't have to constantly update it myself

#

I have #if UNITY_EDITOR for the whole file.

#

If you we're to add a gear item in runtime it would update the persistantValuePointer and it's stored in a game file

#

So what the problem is I wan't to keep track of how many PersistantValue scripts there are in all scenes only in editor mode.

ashen yoke
#

why are you doing it in editor?

#

ok let me explain

#

usually you dont need to keep any persistent runtime ids to anything until you actuall save the game

daring cove
#

Yes you do because there are different scenes.

ashen yoke
#

because when you are serializing you will be assigning ids to serialized values

#

at the moment of serialization

#

the scene index or any id can be part of the serialized id

daring cove
#

Is there an already available ID for each gameobject that is persistent across multiple scenes? Transform data can't be used.

ashen yoke
#

not built in

daring cove
#

That's why I'm making this, but please explain.

ashen yoke
#

so the task is only to track the count of them?

#

total amount? not to generate new ids?

daring cove
#

Yes

ashen yoke
#

i assumed that was the method you used to generate the ids

daring cove
#

I made the utility work in runtime but it has problem. The maximum amount gear is limited.

    public class PersistantValueGenerator : MonoBehaviour
    {
        public int persistantValuePointer;

        private void Awake()
        {
            UpdatePersistantValues();
        }

        private void UpdatePersistantValues()
        {
            GameObject[] gameObjects = SceneManager.GetActiveScene().GetRootGameObjects();
            Debug.Log($"[PersistantEditorValueGenerator.UpdatePersistantValues] gameObjects.Length = {gameObjects.Length}");

            foreach (var lGameObject in gameObjects)
            {
                PersistantValue[] persistantValues = lGameObject.GetComponentsInChildren<PersistantValue>();
                foreach (var persistantValue in persistantValues)
                {
                    if(persistantValue.value == PersistantValueSettings.NO_VALUE) OnAddPersistantValue(persistantValue);   
                }
            }
        }

        private void OnAddPersistantValue(PersistantValue persistantValue)
        {
            persistantValuePointer++;
            persistantValue.value = persistantValuePointer + (
                SceneManager.GetActiveScene().buildIndex * PersistantValueSettings.MAX_PERSISTENT_VALUES
            );
        }
    }

MAX_PERSISTENT_VALUES = 1024

ashen yoke
#

that wont work

#

as soon as you delete any object with persistent value you are creating a collision

#

if you generate a new value you will use the count, which will now be -1 which will override the last item id

daring cove
#
public class PersistantValueGenerator : MonoBehaviour
    {
        private void Awake()
        {
            UpdatePersistantValues();
        }

        private void UpdatePersistantValues()
        {
            GameObject[] gameObjects = SceneManager.GetActiveScene().GetRootGameObjects();
            Debug.Log($"[PersistantEditorValueGenerator.UpdatePersistantValues] gameObjects.Length = {gameObjects.Length}");

            int pointer = 0;
            foreach (var lGameObject in gameObjects)
            {
                PersistantValue[] persistantValues = lGameObject.GetComponentsInChildren<PersistantValue>();
                foreach (var persistantValue in persistantValues)
                {
                    pointer++;
                    if(persistantValue.value == PersistantValueSettings.NO_VALUE) OnAddPersistantValue(pointer, persistantValue);   
                }
            }
        }

        private void OnAddPersistantValue(int pointer, PersistantValue persistantValue)
        {
            persistantValue.value = pointer + (
                SceneManager.GetActiveScene().buildIndex * PersistantValueSettings.MAX_PERSISTENT_VALUES
            );
        }

I think you said make the pointer localized, because the pointer will be the same if you load a new scene?

#

Let me know if I didn't get it

ashen yoke
#

what happens when you delete an object

#

your algo gives it id 2

#

you delete it, add new object

#

that new object will get id 2

#

you have 5 ids, you delete object 3

#

now you have 4 ids

#

new new object will get id 5

#

but you already have object with id 5

daring cove
#

What do think the solution to this would be?

#

Maybe to keep a dictionary of pointers per scene and store it persistently?

{
  0: 9,
  1: 54,
  2: 4
}
#

key is the scene build index and the value is the pointer

daring cove
#

How to use GUID?

ashen yoke
#

Guid.NewGuid();

daring cove
#

How does it work?

ashen yoke
#

generates a unique id

daring cove
#

Limits?

ashen yoke
#

you mean cons? its not "human friendly"

daring cove
#

How many of them can you create?

ashen yoke
#

it is used globally

#

meaning same class generates an id that is guaranteed to be unique around the globe for the next thousand years

#

or something like that

daring cove
#

So it uses the system time?

ashen yoke
#

can you just google

daring cove
#

So this should work?

public class PersistantValue : MonoBehaviour
    {
        public string value;

        private void Awake()
        {
            value = Guid.NewGuid().ToString();
        }
    }
ashen yoke
#

yeah the more i think about it the more i realize there is no way to use counting as valid id

#

you will have issues with dangling references

#

meaning you delete something, and the id is still referenced, but since you are basing it on count

#

you will eventually create an object with that id, and the object can be anything else

#

its basically a minefield

#

to avoid that youd have to track each reference to that object and modify it

daring cove
#

To avoid you never decrease the pointer. Which is not ideal

ashen yoke
#

that would work

daring cove
#

Citing genesys.cloud
"
How unique is a GUID? 128-bits is big enough and the generation algorithm is unique enough that if 1,000,000,000 GUIDs per second were generated for 1 year the probability of a duplicate would be only 50%"

ashen yoke
#

yeah and probability of getting a dupe in a single game is pretty much 0

daring cove
#

It does seem to create the same id for each PersistentValue script added it's always something different.

ashen yoke
#

if youre gonna use it, serialize it with callbacks

daring cove
#

What do you mean exactly?

ashen yoke
#

implement ISerializationCallbackReceiver

#

on the mono

#

have Guid as Guid publically, internally store it as string, then convert to Guid on deserialization

#

its faster to compare Guids directly than do string comparison

daring cove
#

The problem is how can I tell which object needs a certain GUID?

ashen yoke
#

if string.NullOrEmpty()

daring cove
#

I mean all the objects are not going to have a GUID when the program is started up.

ashen yoke
#

or guid == Guid.Empty

#

why not?

#

serialize it

#

use [ExecuteAlways] attribute

#

check the guid in

#

OnValidate

#

Reset()

#

OnEnable()

#

this will ensure that its generated automagically at all points in editor

#

and at runtime

daring cove
#
public class PersistantValue : MonoBehaviour
    {
        public string value;

        [ExecuteAlways]
        private void OnValidate()
        {
            if(string.IsNullOrEmpty(value)) value = Guid.NewGuid().ToString();
        }
    }
ashen yoke
#

no

#

[ExecuteAlways] goes onto the class

#

it tells unity to run the mono methods in editor

lucid valley
#

you might need to set it dirty

daring cove
#
namespace ---
{
    [ExecuteAlways]
    public class PersistantValue : MonoBehaviour
    {
        public string value;

        private void OnValidate()
        {
            if(string.IsNullOrEmpty(value)) value = Guid.NewGuid().ToString();
        }
    }
}

How would this work for game objects added at runtime?

ashen yoke
#

actually this

#
public class PersistantValue : MonoBehaviour, ISerializationCallbackReceiver
{
    public Guid guid { get; private set; }

    [SerializeField] string _guidSerialized;

    public void OnAfterDeserialize()
    {
        if(string.IsNullOrEmpty(_guidSerialized))
        {
            guid = Guid.NewGuid();
            _guidSerialized = guid.ToString();
        }
        else
        {
            guid = Guid.Parse(_guidSerialized);
        }
    }

    public void OnBeforeSerialize()
    {
        if (guid == Guid.Empty)
            guid = Guid.NewGuid();

        _guidSerialized = guid.ToString();
    }
}

#

should be enough

ashen yoke
#

but that serialization hack should work also

#

probably

#

maybe with Awake() injection as well

sharp oasis
#

Hi, Anyone knows how to like animate camera if you enter a collider?
Thanks

sleek bough
#

@sharp oasis Don't cross-post

daring cove
#

Will PersistentValue.guid be different for all PersistentValue instances?

sharp oasis
ashen yoke
#

yes

sharp oasis
#

But can you help me fr

lucid valley
daring cove
#

It might be in the future

lucid valley
#

runtime GUID won't be deterministic, unless you sync it

daring cove
#

I can make the server decide

lucid valley
#

cool, that's fine

#

at that point though you might as well have used the inbuilt way the networking solution does it instead of making your own persistent values

daring cove
#

If I'm going to do multiplayer it's going to be Player hosted server

ashen yoke
#

problem with serialized guid is also that if you copy paste an object it wont have unique guid, youd have to handle it yourself

daring cove
ashen yoke
#

yeah then awake

ashen yoke
#

it will be different because its a new object you are creating

daring cove
#

I guess I can fetch them from the gamefile and create them that way

#

And set the guid in manually

ashen yoke
#

oh you mean the save

#

yes that part you have to do yourself

#

ISerializationCallbackReceiver is unity serializer

daring cove
#

Where does ISerializationCallbackReceiver save the data?

ashen yoke
#

.asset

#

or .prefab

#

on build its all converted into asset bundles

#

so that thing is only for objects created in editor

swift falcon
#

This is more of a theoretical question rather than a practical one, but what would be the best way to handle VR body force feedback? Its easy to just put force on the player's body instead of hands when he grabs a static object, but it becomes significantly trickier in the following two cases:
First, what if the grabbed object moves? its easy enough to detect if it's "static" by lack of a rigidbody, but there's no real way to know when to apply force and in what direction in such a case
Second, which is not as important, regarding non-static objects of significant weight, or perhaps when the player doesn't grab and just pushes using their fists. Using physics 24/7 is a bad idea because it will give the player motion sickness from getting their body moved around when swinging objects, especially in the air. First problem could probably be solved the same way this one is. This isn't as important (if it is at all), so I'm mainly focusing on the first issue

hollow stone
swift falcon
#

I am really not a fan of using unity's inbuilt physics components for VR, later down the line it will just become even more of a hassle to deal with if you're doing something more advanced than simple grabbing

#

I'll look into it tho

magic parrot
#

I mean it only happends when i build it, when its in unity it works

frosty pawn
#

Can I serialize SortingLayer and then get it's index like it happens in SpriteRenderer ?

swift falcon
#

In what language should i program in Unity? C# or C++

pearl radish
leaden ice
magic parrot
leaden ice
#

What steps did you take to check

magic parrot
#

I did nothing in the game related to script execution

leaden ice
#

That doesn't mean anything

magic parrot
#

Than what should i do?

leaden ice
#

Debug your program

#

Add log statements

#

To question your assumptions

magic parrot
#

Ok, ill try it, thank you

elfin tree
#

Hey, so in my code, I instantiate gameobjects inside a GridLayoutGroup at runtime. Only thing is they appear invisible at first, same thing in scene view inside and outside playmode. An easy work around is to go in the scene and enable, disable or change any one of the objects in the grid layout group and they all suddenly appear as if something was updated or refreshed. It doesn't work if I just SetActive to false then true in the code instead. Thoughts on how I could fix or hotfix this? Thanks!

SOLVED
LayoutRebuilder.ForceRebuildLayoutImmediate(grid.GetComponent<RectTransform>());

signal shoal
#

I'm pretty stumped on this one. Trying to use a dictionary of <string[], int>, but whenever I try to look up in the dictionary using a string[], I get the following error:

System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at <a40b0ad4a868437393ad434631fb6ff1>:0)```
It's as if what I'm looking up wasn't in the dictionary.
Here's my code:
```c#
Dictionary<string[], int> testDictionary = new Dictionary<string[], int>()
    {
        {new string[] {"A", "B"}, 123},
    };

void Awake()
    {
        Debug.Log(testDictionary[new string[] { "A", "B" }]);
        // Should debug 123, right?
    }

What am I doing wrong here?

simple egret
#

It's right, it's not in the dictionary because it's not checking for the values in the array

rain minnow
simple egret
#

It checks whether it points to the same location in memory, and since you're creating a new one, it's not

rain minnow
#

the reference is different . . .

signal shoal
#

Oooh, you're right, thanks for pointing that out! How would you recommend I go about implementing something like this then?

rain minnow
#

why are you doing it this way though?

signal shoal
#

Do I need a Linq expression or just loop through the whole thing?

#

This is all just test code, as part of a bigger script I'm trying to look up opcodes (ints) for a simulated computer using two strings that identify them.

simple egret
#

You can make a custom equality comparer that compares the elements of your array, and pass it to the dictionary when you new it

signal shoal
#

Sure, that seems like a good idea, thanks. Let me see how well that goes.

quartz folio
#

I would avoid that if you can. It might make more sense to just use concatenated strings

signal shoal
quartz folio
#

Potentially, it's impossible to say without understanding your use case. It just sounds like there should be better ways of doing this than arrays

#

If there's only pairs of two strings then you should just make a struct or use value tuples

signal shoal
#

Thanks, that's a good point, as all of this did seem to be veering into the not best practices zone. I already generated my original dictionary with a python script so I might just write another to make a list of concatenated strings

wide pecan
#

TextMeshPro somewhy changes the first letter of text. I have this script for floating text:

void FloatText()
    {
        string test = "";
        foreach(var p in FloatingCharacters){
            test += (p.character.ToString());
        }
        Debug.Log(test);

        var textInfo = MainText.textInfo;

        foreach (TMP_CharacterInfo character in FloatingCharacters)
        {
            var verts = textInfo.meshInfo[character.materialReferenceIndex].vertices;

            for (int j = 0; j < 4; ++j)
            {
                var orig = verts[character.vertexIndex + j];

                verts[character.vertexIndex + j] = orig + new Vector3(0f, Mathf.Sin(Time.time*2f + orig.x*0.01f) * FloatingHeight, 0f);
            }
        }

        for (int i = 0; i < textInfo.meshInfo.Length; i++)
        {
            var meshInfo = textInfo.meshInfo[i];
            meshInfo.mesh.vertices = meshInfo.vertices;
            MainText.UpdateGeometry(meshInfo.mesh, i);
        }
    }

The first letter is not in the list of FloatingCharacters and here's the result:

cunning pivot
#

Hello is there a way to stop a parented object from clipping through other colliders (i'm parenting a box to the player)

hexed pecan
cunning pivot
#

so maybe disable the character controller and activate the rigid body when the player is pushing the box ?

primal wind
#

Anyone extensively used async ? I tested it a bit a few months ago and i'm wondering if there are any limitations to it

#

I got to use Task.Delay() and it did work

hexed pecan
#

You can try swapping between them but its probably going to be janky

cunning pivot
twin hull
primal wind
#

Oh

hexed pecan
primal wind
#
async void Start()
{
    await Task.Delay(5000);
    Debug.Log("Done");
}
hexed pecan
#

Oh sorry I read "did not work"

primal wind
#

I'll try more stuff later

hexed pecan
#

I have been using basic delays like that and awaiting other async methods

primal wind
#

It could be extremely useful if it doesn't do weird stuff

hexed pecan
#

No major problems so far

primal wind
#

Oh nice

potent sleet
#

dont crosspost bruh

swift falcon
#

sorry

scarlet viper
#

nvm got it

fair mural
#

So I have a gun that shoots every .2sec. The animation is also .2 sec long. therefore, when firing the gun full auto, sometimes the shoot anim wont play because the fire rate and shoot anim are so close together that they conflict sometimes. How can I make it to where the shoot animation plays even if it is already in progress?

hasty wadi
#

I have a wave spawner script like this:
https://gdl.space/sawaqudave.cs
I used to tutorials to build it up but I couldn't find anything related to 3D infinite wave system. So I would like to have wave system, where waves are infinite and the amount of zombies are increasing every wave. Can anyone help me out a lil bit?

magic venture
#

How can I make a telescoping tower that opens each section once the last section reached it max position?

glad sierra
#

Hey, so I wanted to make a variable that only accepts scripts that inherit from a specific abstract parent class called TriggerScript so I can make sure all the scripts have one specific method I need to call. However

public TriggerScript script;

doesn't allow me to enter any script. Not a script that inherits from that nor the TriggerScript itself. Is it possible to make sure that the script I enter is inheriting from TriggerScript or has a method with a specific name?

glad sierra
#

like in those [SerializeField]s basically dropping them in there

crude mortar
#

What are you trying to drop in though.. ?

prime sinew
#

Look up how to expose abstract classes in unity

#

I know normally you can't. You need a workaround

crude mortar
#

But there isn't enough information to know if that's necessary. If TriggerScript is a MonoBehaviour (for example), it should work fine

glad sierra
crude mortar
#

That's not how it works though, you need a specific instance

#

You can't just choose a script to drag in

#

you need an Object that has that script on it

#

That way you create a reference to the specific Object by dragging the object itself (or the specific instance of that script) onto it

hexed pecan
#

Maybe he means a script component and not a script file

#

AFAIK you do need [SerializeReference] and some custom inspector logic to do this

prime sinew
crude mortar
glad sierra
#

this script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriggerTest : TriggerScript
{
    public override void trigger()
    {
        Debug.Log("Triggered!");
    }
}
crude mortar
#

You are trying to literally drag the C# file onto the slot?

#

Just want to make sure I understand

glad sierra
#

yep the parent class inherits from MonoBehavior so I should have all the functionality

crude mortar
#

So, again, that's just not how it works. You need a GameObject to exist that has the script on it

#

You could then drag that specific GameObject / Component into the slot

#

But this likely isn't what you want

#

So the short answer to your question is.. You can't do that, you would need to find another way. Perhaps ScriptableObjects?

#
public abstract class TriggerScript : Scriptablebject {
  public abstract void Trigger();
}

[CreateAssetMenu(fileName = "NewTriggerTest", menuName = "ScriptableObjects/TriggerTest")]
public sealed class TriggerTest : TriggerScript {
  public override void Trigger() {
    Debug.Log("Triggered!");
  }
}

You would then need to right click in your assets folder and create an instance of the ScriptableObject called TriggerTest. Then you could drag the ScriptableObject instance into the slot instead of the C# script.

glad sierra
#

Okay let me explain what I want to do with these scripts. maybe then it's better to understand.

I have the gameobject Trigger that I want to use for multiple trigger events. Like change music, play a sound effect, display text etc. And one trigger event should execute a script so a npc walks to a specific position, etc Does this work with ScriptableObjects? I am sorry. I never used them before. should have asked in #๐Ÿ’ปโ”ƒcode-beginner I guess sry

crude mortar
#

It could, but you would probably need to learn about many things, and how to structure your code in such a way that would make this possible. What you are trying to do is not necessarily easy. However, as a beginner, if you understand the concept of Singletons, you should be able to make it work with ScriptableObjects.

mental rover
#

is there a reason you're not just inheriting from MonoBehaviour and adding the different types of triggers as components directly?

crude mortar
#

That's probably a better idea haha

#

Just put your TriggerTest onto the GameObject that has the Trigger on it

#

Then drag in the TriggerTest (the component, not the script), into the slot

glad sierra
glad sierra
#

it works!

#

thank you ๐Ÿ˜˜

fair mural
#

So I have a gun that shoots every .2sec. The animation is also .2 sec long. therefore, when firing the gun full auto, sometimes the shoot anim wont play because the fire rate and shoot anim are so close together that they conflict sometimes. How can I make it to where the shoot animation plays even if it is already in progress?

heady iris
#

it needs to be able to interrupt itself

#

this is an animator problem

#

you'd want to add a transition from the state to itself

wintry grove
#

Hi guys I'm very confused, been trying to get this to work for a few hours yesterday and today in many different ways with the same results.

I'm clearly missing something.

I'm trying to store an array of game objects in an InstantiatedShip class and set them to inactive like this. This is done through a class with a singleton (which is the only thing I can think of being the problem)

        InstantiatedShip newShip = new InstantiatedShip(faction, selectableName, type, shipStats.baseHealth, shipStats.baseArmor, shipStats.baseHull, shipStats, isAI, shipReference, cargo);
        
        foreach (Transform g in shipReference.transform.GetChild(1).GetComponentInChildren<Transform>())
        {
            Debug.Log(g.gameObject);
            g.gameObject.SetActive(false);
            newShip.turretMounts.Add(g.gameObject);
        }

However in another class I am calling this

(something).currShip.turretMounts[0].SetActive(true);

The class is active since I can console.log it, it's pointing to the correct items, the correct game objects, the correct ship, etc. Everything is perfect from what I gather yet it does not actually enable the game objects.

However when the top code runs, then I comment it out, the objects stay inactive (which is probably the issue). Does anyone know why this might be? Maybe there's something about the engine I'm not sure of

heady iris
#

i don't understand what this means

#

However when the top code runs, then I comment it out, the objects stay inactive

#

do you mean that you comment out jus the foreach?

#

also, what is the singleton?

#

i don't see any singletons here

tacit lance
#

I want to have an area designated by 4 corners (I just need to randomly pick points inside that area latter). What's the best way to store this in code so that I can edit the area in the editor?

quaint crypt
#

I have a monobehavior that has OnValidate() { Debug.Log(GetComponent<Someother>().test) }, that test variable is set to 10, but this outputs 0. Why does this happen? Doesnt OnValidate run after all components have initialized?

heady iris
#

how are you setting this "test variable" to 10?

#

do you mean it has a default value?

#

e.g.

#
int test = 10;
wintry grove
heady iris
#

that won't affect the serialized value. the default value is only relevant when you add a new component or Reset a component

quaint crypt
wintry grove
#

anyway the solution was that the reference I was using was a prefab and not instantiated (though I thought it was instantiated) so i scoured the code and ensured I was doing it to the instantiated object and now it worked

quaint crypt
quaint crypt
# heady iris ```cs int test = 10; ```

so just to reitarate. I have a GO with scipts A and B. A has an OnValidate() with Debug.Log(GetComponent<B>().test), and on the GO in the inspector I've set test to 10

#

but it outputs 0 when the scene reloads because of a changed script for example

#

which apparently also calls OnValidate

#

on A

#

so my question is, why doesn't A have the proper B instance or whatever else is happening

#

if I change values in the inspector, it works fine

#

but whenever I change a script and unity reloads, it outputs 0

heady iris
#

i'm not sure if what you're doing is valid

#

Note: You should not use this callback to do other tasks such as create objects or call other non-thread-safe Unity API

quaint crypt
#

im not instantiating anything, just calling GetComponent

heady iris
#

That's not quite true. If you dissamble some UI components of Unity's, you'll see plenty of component fetches via .OnValidate().

#

so that does suggest it's valid

#

in some contexts, at least

#

I'm guessing you're spotting the component before it gets its serialized values written to it?

#

Definitely not very clear..

#

what happens if you set the default value for the field to something else?

#

like public int test = 3;

quaint crypt
#

on build. on actual inspector value changes, it works fine and outputs 10

west lotus
#

You mean when you start a build?

quaint crypt
#

yes, but not explicitly. by changing a script, and then going back to unity. that triggers a re-build, right? or am i mixing the terminology

west lotus
#

Thats a recompile

heady iris
#

i might casually call that a "build" in other contexts

#

but in unity you use that to refer to building the game into an executable

quaint crypt
#

oh, gothca

#

sorry for the confusion, was refering to a recompile

swift falcon
#

You have to put an f when when assigning a Float

Otherwise the compiler thinks youโ€™re trying to assign a Double

Right?

heady iris
#

not quite

#

you have to add an f to the end of a numeric literal to make it a float

#

a "literal" is something that's...literally the value

#

'a', "hello", 123, 4.0, true

#

4.0f is a float

#

4.0 is a double

swift falcon
#

Yeah, but like what helps the compiler understand what is a float and whatโ€™s a double, I assumed the F

heady iris
#

Right.

#

It tells it what you meant.

swift falcon
#

Oh alright thatโ€™s cool

#

Thanks

restive ice
#

if you want to be specific you can do 2d to indicate a double too

heady iris
#

which could be relevant!

swift falcon
#

Thanks for all the info

restive ice
swift falcon
#

Itโ€™s pretty useful

restive ice
#

nah it's just syntactic(?) sugar

heady iris
#

yeah, it's sugar

swift falcon
heady iris
#

dynamic is, indeed, a thing

#

I used it once for some code involving calling a generic function with an enum type determined at runtime

#

scary

swift falcon
restive ice
#

yeah don't overcomplicate stuff too much though youll barely use them

heady iris
#

in case you want to enjoy all of the keywords

#

i've never ever seen volatile in a C# script

#

scary

#

in C, at least, it tells the compiler to not try to be clever with the variable

#

no assuming it keeps its value until written to again, for example

restive ice
swift falcon
heady iris
#

i dunno

heady iris
#

hang on, how on earth is fixed less scary than yield or implicit

#

get outta here

restive ice
#

yield can definitely be scary

swift falcon
#

Thank god documentation exists for all those words

restive ice
#

anything coroutine related can be scary

heady iris
#

it's just a wafer-thin enumerator

#

๐Ÿ’ฅ

restive ice
#

multithreading yikes

heady iris
#

coroutines aren't parallel!

gray mural
#

When the audioClip ends - I should start the new one. The clip is changed a few times in Update's else block.

private void Update()
{
    // that's not full Update code
    
    if (audioSource.isPlaying)
    {
        if (!changingTime) timeSlider.rawValue = (int)audioSource.time;

        ChangeTimeInputText();
    }
    else
    {
        print($"started: {audioSource.isPlaying}; \nclip: {audioSource.clip.name}; \ntime: {audioSource.time}");

        PlayBackgroundMusic();
        ChangeTimeSlider();

        Debug.LogWarning($"CHANGED: {audioSource.isPlaying}");
    }
}
private void ChangeTimeSlider()
{
    timeSlider.minValue = 0f;
    timeSlider.maxValue = (int)audioSource.clip.length;

    musicParsedLength = ParseMusicTime(audioSource.clip.length);

    ChangeTimeInputText();
}

private void ChangeRawValue(float rawValue)
{
    if (!Mathf.Approximately(timeSlider.rawValue, timeSlider.maxValue) && !(rawValue < 0 && timeSlider.rawValue <= timeSliderStart))
    {
        timeSlider.rawValue = rawValue;
        audioSource.time = timeSlider.value;
    }
}
gray mural
potent sleet
gray mural
heady iris
#

we were looking at this a day or two ago

gray mural
heady iris
#

it seems like isPlaying is snapping back and forth for some reason

gray mural
potent sleet
#

sucks audiosource doesnt have event

heady iris
#

it becomes true immediately after playing

#

but then appears to go back to false

#

which is very odd.

potent sleet
#

is this like a music player or something

gray mural
potent sleet
gray mural
gray mural
# potent sleet also where is this code from
private void PlayBackgroundMusic()
{
    audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
    audioSource.time = 0f;

    audioSource.Play();
    print($"PLAYED: {audioSource.isPlaying}; clip: {audioSource.clip.name}; time: {audioSource.time}");
}

private void ChangeTimeSlider()
{
    timeSlider.minValue = 0f;
    timeSlider.maxValue = (int)audioSource.clip.length;

    musicParsedLength = ParseMusicTime(audioSource.clip.length);

    ChangeTimeInputText();
}
gray mural
#

also there are logs after placing few prints

heady iris
#

so it's not multiple copies of the same component

#

these are happening at different times

#

that's a very interesting time, though...

potent sleet
#

yeah starting from 0 and then ends at 165

gray mural
potent sleet
#

gets the length after playing

heady iris
#

hmmm

gray mural
#

!code

tawny elkBOT
#
Posting code

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

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

heady iris
#

i wonder if your time slider is interfering here

#

somehow

gray mural
#

sorry?

potent sleet
gray mural
potent sleet
#

idk using Update is weird to me
I would just use a coroutine and while loop

#

maybe use isPlaying only as extra measure

gray mural
#

no succeeded as you can see

potent sleet
#

do you want an example

#

you can adapt the rest yourself

gray mural
potent sleet
#
 [SerializeField] private AudioSource audioSource;
    [SerializeField] private List<AudioClip> clips;

    [ContextMenu("Play")]
    public void Play()
    {
        StartCoroutine(PlayMusic());
    }
    
    IEnumerator PlayMusic()
    {
        audioSource.clip = clips[Random.Range(0, clips.Count)];
        Debug.Log(audioSource.clip.length);
        audioSource.Play();
        while (audioSource.time < audioSource.clip.length)
        {
            Debug.Log("Playing" + audioSource.time);
            yield return null;
        }
        Debug.Log("Done");
        yield return PlayMusic();
    }```

Just tested this and works
#

wait i think it needs tuning ,

gray mural
potent sleet
gray mural
potent sleet
gray mural
#

@potent sleet you can also do this way I guess

[ContextMenu("Play")]
public void Play()
{
    StartCoroutine(PlayMusic());

    IEnumerator PlayMusic()
    {
        audioSource.clip = clips[UnityEngine.Random.Range(0, clips.Count)];

        Debug.Log(audioSource.clip.length);

        audioSource.Play();

        while (audioSource.time < audioSource.clip.length)
        {
            Debug.Log("Playing" + audioSource.time);
            yield return null;
        }

        Debug.Log("Done");
        yield return PlayMusic();
    }
}
potent sleet
#

you could but now you have no way to stop it

gray mural
potent sleet
#

normally you'd make a
Coroutine playingMusicRoutine = StartCoroutine(PlayMusic());

potent sleet
gray mural
#

I should work I guess ??

potent sleet
#

it should still work

flint needle
#

hey, any way i can animate a mesh vertices in a performant way?
SetVertices per update sounds terrible

primal wind
#

Manually change the vertices? tho i don't know much about this

#

So it could actually be the same thing

flint needle
#

what do you mean?

#

im trying to use a DoTween.To that calls SetVertices in its tween OnUpdate callback

#

but performance is terrible

maiden fractal
gray mural
# potent sleet ```cs [SerializeField] private AudioSource audioSource; [SerializeField] pr...

I still have the same issue

private void Update()
{
    if (audioSource.isPlaying)
    {
        if (!changingTime) timeSlider.rawValue = (int)audioSource.time;

        ChangeTimeInputText();
    }
    else
    {
        print($"started: {audioSource.isPlaying}; clip: {audioSource.clip.name}; time: {audioSource.time}");

        ChangeBackgroundMusic();

        Debug.LogWarning($"CHANGED: {audioSource.isPlaying}; clip: {audioSource.clip.name}; time: {audioSource.time}");
    }
}
[ContextMenu("Play")]
public void ChangeBackgroundMusic()
{
    StartCoroutine(ChangeBackgroundMusicHelper());

    IEnumerator ChangeBackgroundMusicHelper()
    {
        audioSource.clip = backgroundMusic[UnityEngine.Random.Range(0, backgroundMusic.Length)];
        audioSource.time = 0f;

        Debug.Log(audioSource.clip.length);

        audioSource.Play();

        ChangeTimeSlider();

        while (audioSource.time < audioSource.clip.length)
        {
            yield return null;
        }

        Debug.Log("Done");
        yield return ChangeBackgroundMusicHelper();
    }
}
flint needle
flint needle
#

i -could- do it on shader but in the end im modifying the vertices so idk

gray mural
potent sleet
#

@gray mural I g2g bbl

just don't put anything it update. call it once. that's it

maiden fractal
flint needle
#

is it that bad?

#

i mean it seems like lol. but they aint that many

maiden fractal
flint needle
#

maybe iยดll just drop the idea, just wanted it good looking but not worth the hussle

maiden fractal
#

How many vertices are there in the mesh?

flint needle
#

250x250 plane

maiden fractal
#

Thats something but not a lot

flint needle
#

yeah

gray mural
maiden fractal
flint needle
#

Gon remove it and see if it speeds up the process

#

i wanted to treat it as matrix but i could just have used column / row index

hexed pecan
#

You can just have a 1D array and a getter method that takes X and Y

maiden fractal
#

Im afraid that you are doing something crazy every iteration of vertex array so id like to see the implementation

flint needle
#

yeah it was silly to do it that way, im going to refactor

#

if i remove the setVertices form OnUpdate and call it just once at the end its alright, so it may be the ConvertArray conversion

maiden fractal
flint needle
#

im not sure how to scheadule it to animate with the DoTween

#

before using DoTween i would only call it once when i clicked

hexed pecan
#

So youre trying to actually animate it so the terrain changes gradually?

flint needle
#

just the couple vertices i modify, (5-10 usually)

maiden fractal
#

But as Osmal said, ConvertArray seems unnesessary anyway, sounds like tons of garbage

flint needle
#

but its honestly more worth it to throw in a VFX and just directly modify it

hexed pecan
#

I'm doing something like this but with compute shaders

#

Worth looking into

potent sleet
flint needle
#

if i put terraforming in game maybe iยดll dedicate more to it

#

Thank yall by the way, iยดll start by cleaning up extra code ๐Ÿ‘๐Ÿป

golden vessel
#

Hey, I have chaining coroutines for a turn based game, how do I go about stopping the game (when the player gives up) without it breaking the game ? Do I check every frame of every coroutine if the player has given up?

heady iris
#

Chaining coroutines?

dusk apex
#

Show us your implementation

#

Also define "stopping the game"

golden vessel
#
    {
        yield return StartCoroutine(PlayStartTurnText());
        yield return StartCoroutine(currentlyPlaying.PlayStatus());
        if (gameAlreadyOver)
        {
            yield break;
        }

        yield return StartCoroutine(currentlyPlaying.PlayTurn(true));
        if (gameAlreadyOver)
        {
            yield break;
        }

        currentlyPlaying = GetNextCharacter(currentlyPlaying);

        StartCoroutine(PlayTurn());
    }```
#

I have this main coroutine that play a coroutine on another script that's on the character

dusk apex
#

If you just need to terminate all coroutines, you could use the stop all coroutine function

golden vessel
#

I don't know if there's other things that could interfere

#

Guess I'll experiment with it for now

rough fjord
#

Can I recalculate static mesh colliders at runtime? I have a procedurally built area and the colliders don't work on convex, but they aren't "static" because I place them at runtime.

clear tiger
#

One message removed from a suspended account.

somber nacelle
#

do you have a physics raycaster on the camera?

clear tiger
#

One message removed from a suspended account.

somber nacelle
#

that's why

rough fjord
steady moat
heady iris
#

adding a mesh collider to an object with a mesh on it should already Just Work(tm)

steady moat
#

I mean not sure why you want things to be static.

rough fjord
#

I had some modular blocks to build a world with procedurally but the convex colliders weren't any good.

I have decided to use a different method, so it doesn't matter now.

steady moat
rough fjord
#

Physics

#

I'm just using terrain now.

steady moat
#

Then, you do not need to do anything. If I remember correctly, everything that does not have a rigidbody is consider static.

rough fjord
#

Oh.

steady moat
#

There is no mention of physic

cobalt gyro
#

`using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemPickup : MonoBehaviour{
public Item item;
public Transform itemSlotContainer;

GameObject trueItemSlotContainer;

Transform slot;
Transform imageContainer;
ItemDisplay itemDisplay;

public GameObject itemImage;

bool slotAvaliable;
void Start(){
    trueItemSlotContainer = GameObject.Find("InventoryGrid");
    itemSlotContainer = trueItemSlotContainer.GetComponent<Transform>();
}`
#

for some reason itemSlotContainer isn't being declared on start. does anyone know what im missing

heady iris
#

isn't being initialized, you mean?

#

for transforms, you can just do .transform

#

but that ~should~ work

#

perhaps you're getting an error from that line? itemSlotContainer = trueItemSlotContainer.GetComponent<Transform>();

#

that would happen if trueItemSlotContainer was null

cobalt gyro
#

thanks

woeful narwhal
#

with the new input system, is there a way to check when a key is released?

woeful narwhal
#

oh mb

blissful frost
#

hello i have a question with unity's trigger system

#

may anyone help

#

i am trying to check for collision beetween a car and a check point but i want that to be on the movement script so not on the actual trigger. i dont know how to set that up at all been at this for a while

#

please ping me if you can help

leaden ice
blissful frost
#

ok may you show me how?

leaden ice
blissful frost
#

this is on the car script ```void OnTriggerEnter(Collider other)
{

        // Check if the collision involves the desired trigger
        if (other.CompareTag("aiCar"))
        {
            points += 10;
            print("sup");
        }
    }```
leaden ice
#

to make sure the code is running at all

blissful frost
#

it defintatly is

leaden ice
#

and if it's not, follow the link above to find out why

leaden ice
blissful frost
#

thats in the update function and everything else is running in there

#

it all works

vagrant blade
#

Your OnTriggerEnter cannot be inside of an update function.

leaden ice
#

that's definitely wrong then

blissful frost
#

oh

#

wait

vagrant blade
blissful frost
#

fuck

leaden ice
#

don't put functions inside other functions. That's an advanced/intermediate feature.

#

Don't do it as a beginner.

#

It will only confuse you

blissful frost
blissful frost
#

alr swag it works now

lean sail
#

Ive run into a really strange issue. after the entire day I narrowed it down to a few lines of code thats causing my bug, but this was through brute force of commenting out code. Im wondering if anyone can help explain this.
The video shows the 2 active ragdolls on the left jittering, they are placed from prefabs. This jittering causes them to move faster than the character on the right (who is moving as i want). The weird part is the character on the right is just a copy of the first prefab, it only got moved to the right. This character has no issues at all. It moves smoothly. This issue started in a different scene, so I made it into a prefab and brought it into this new scene which still has the same issue.
code: https://paste.ofcode.org/38rfU5z4aYGcvw74QKi9nPq
If lines 35 to 41 are commented out, my bug is "fixed" because none of them jitter anymore. But i need the code, it just moves the character in the forward direction of the camera.

Now im wondering why this only happens when I place the character down from the prefab file, and why the copied character has no issues at all. To clarify as well, the copied character is able to move in the direction of the camera easily

cobalt gyro
#

`void OnTriggerEnter2D(Collider2D coll){
int i = 0;
if (coll.gameObject.tag == "Player"){
foreach(Transform child in itemSlotContainer){
slotAvaliable = true;//Slot is innocent until proven guilty
slot = itemSlotContainer.GetChild(i);//Cycles through all 15 slots in the grid
imageContainer = null;//Resets called non-cycling variables
itemDisplay = null;

            try{
                imageContainer = slot.GetChild(0);//Atempts to get child image of item slot frame
            }
            catch(System.Exception){
                slotAvaliable = false;
            }

            if(slotAvaliable == false){
                Instantiate(itemImage,new Vector3(0,0,0),new Quaternion(0,0,0,1), slot);//Instantiates item into inventory
                imageContainer = slot.GetChild(0);
                itemDisplay = imageContainer.GetComponent<ItemDisplay>();
                itemDisplay.item = item;
                Destroy(gameObject);
                break;
            }
            else{
                i++;
            }
        }
    }
}`
dusk apex
rain minnow
cobalt gyro
lean sail
#

i debugged this before i added force
Debug.Log(transform.parent.name + direction.normalized + speed);
and all 3 objects were printing the same direction and speed.
Ill check the rotation i guess

dusk apex
#

If my assumptions are correct, placement would matter.

cobalt gyro
dusk apex
#

Where it may be placed in a certain orientation that allows it's return value of Euler angle to be correct.

lean sail
#

they all do have difference rotations being given back from Quaternion.Euler(0f, movementAngle, 0f) so i guess that makes sense. The only thing I dont get though is why it works when i copy the character then move it. Maybe some weird stuff with the configurable joint

rain minnow
# cobalt gyro whats a backtick

the key used to format code. it's the same as the tilde key (on an american keyboard). the same one you already used to format your previous code snippet. just use 3 of them instead of 1 . . .

dusk apex
#

Smooth damp would iterate towards the specified angle but the possibility that angles return could be 180+ or the opposite would have the target wiggling if attempting to traverse the the opposite direction - a common issue with quaternion to Euler and shortest path.

dusk apex
#

The usual solution is to not read Euler data from Quaternion and simply have local fields representing angular orientation (in Euler) of the objects.

#

That would be my only assumption as there isn't much happening with the few lines you've posted - that could go wrong.

cobalt gyro
lean sail
#

I understand how that can be related, but i just dont know why this only fixes for the character that is copied. I think theres just some configurable joint value that probably starts rotated weirdly

#

also the hip isnt connected to anything, maybe this has some effect

dusk apex
#

Place the copy where the defects are and with the same settings as the defects. See if it's reproducible.

#

But definitely reading from Transform.eulerAngles or Quaternion.eulerAngles would throw red flags in my mind.

lean sail
#

in that video the very left one, and the one the camera is focused on are the defects. All the copies move fine

#

the characters u see behind them as well as just for animations, u can ignore those. Theres no script on it, its just a bunch of transforms currently

dusk apex
lean sail
#

Yea if i move them, they still always jitter

#

i move them all by dragging the CharacterWrapper as well which u can see in the vid

dusk apex
#

Either way, it's related to those few lines.

lean sail
#

I can try just rotating it a different way, maybe the prefab ones have a bugged limit of rotation on some joint

dusk apex
#

Log direction before normalizing and adding force.

#

Include the object names (you only need the three) and the direction.

lean sail
#

They're all the same, regardless of it they're jittering or not

#

its printing object name, direction, speed

#

so it has to be rotation i guess

dusk apex
#

Log their hip euler angles as well

#

Wouldn't be surprised if you got some bizarre numbers

lean sail
#

im looking through a lot of debug logs and so far they all seem relatively similar. The expanded log at the bottom shows all the details and they never differ by more than like 0.02

#

the copied character and prefab 2 also are very similar, its only prefab 1 that has the 0.02 difference because its in the middle currently while prefab2 is on the left and copied character is on the right

dusk apex
#

You've printed the quaternion which would not change

lean sail
#

at the bottom u can see the expanded view, i printed 3 things on 1 line. the target angle, euler angles, and quaternion

dusk apex
#

When the quaternion converts to Euler, you'll not be guaranteed that it's the value you gave it. Example, 270 degrees might not be what it is after writing to and reading back from the quaternion.

lean sail
#

ah

dusk apex
#

So if I were damping towards 270 one frame then -90 the next, I'd get weird wobbling.

#

Which might affect the speed.

#

How it's computed, we don't know. But maybe it's got something to do with how near it is to the camera or it's position/orientation relative to the camera etc

lean sail
#

yea ill probably just rotate it differently then. I tried putting one prefab far away and it is considerably slower nvm its still doing the same

lean sail
#

i just find it really odd that its specifically bugged when placing a prefab, but fixed when copying it

dusk apex
#

That's my assumption what the issue is.

lean sail
#

thanks tho ill try to do it without euler angles

dusk apex
#

Just cache the initial Euler angles and use the cache when needing to read Euler values.

#

When modifying rotation, you'd just modify those values as well.

#

Basically your own local Euler angles - not interpreted Quaternion Euler values returned by the euler angles property.

lean sail
#

I dont know if I can actually do that for this, because my active ragdoll can fly in any direction when hit

dusk apex
#

If the rigid body can compute the new direction/angle, so can you - maybe.

Practically though, you'd just avoid ever reading from the eulerAngles property and you'd be all set UnityChanWIP

lean sail
#

i suck at physics so i probably couldnt compute it. plus the hips can be pushed from other limbs moving and it stands up using joint drives. id rather just learn quaternions

dusk apex
#

I think it's simply that the quaternion does not retain the angular values and are instead converted to some numerics that can recreate the angles or variants of particular angles. For example -270 may just be referred to as 90 or one of the other periods (360).

lean sail
#

even though i shouldnt use euler angles, i still feel like this is a bug with configurable joints specifically. i dont know if i mentioned this before but that code actually worked perfectly fine before today

#

i just wish i knew what i changed overnight, my pc shut down so something didnt save