#archived-code-general

1 messages · Page 240 of 1

sharp bison
#

i drop the ornament in the trigger

#

both get destroyed and the object i assigned to activate in the placement trigger script activates

pure garden
#

I thought you wanted smth like theres a red blue and green ornament and you only want the red and green to be able to activate the trigger but the blue do nothing

sharp bison
#

ooh or maybe just to bypass all this trouble i can just activate the placement trigger with other funcionts in game such as i wake up and the object + the trigger gets activated

#

maybe i can provide footage to see what i mean lol

#

ah i'll just make the other functions activated the other placement triggers and the item

warm kraken
#

guys i have a script attached to an object. this object's child is a particle system. what the script itself does is to just copy the player's position. everything works as intended but the only issue is as i move player the particle system rotates. i tried both local and world space options on the particle system and it doesnt work. i cant figure out why its rotating it should be just copying the position.

sharp bison
boreal condor
#

Alright, hope recursion doesnt fuck my brain

latent latch
#

there's also the constraint class

terse turtle
#

How could I simply make scenes have a type? Something that would tell the Player that this scene is either Peaceful or Action.

latent latch
#

make an SO with the scene asset and any extra info relating to the scene

terse turtle
latent latch
#

you attach the scene to a script

terse turtle
open charm
#

Can navmesh work with tilemap colliders and regular colliders

#

Simultaneuously

latent latch
#

Actually, may need to use the GUID/Name

#

can't reference the scene by asset in build

gray mural
#

Hello.
I have a Canvas with Render Mode Screen Space - Camera.
I have a UI Image in this Canvas.
How do I make this Image's sizeDelta with the same as the current size of of 1x1 block?

#

The block's size changes according to the current camera size

hasty haven
#

Thoughts on how to approach checking specific conditions about the player for tutorial purposes?
I have a TutorialManager script that grabs a reference to the player controller script when they load in,
think I may start coroutines for each section that checks for conditions like basic movement, using their light, opening doors, etc

#

I already have simple zone triggers they can enter to trigger these tutorial messages

twilit radish
#

not sure if this is helpful

#

but a technique i used was a universal variable handler

#

and with variable like 'hasUsedFlashlight'

#

and the bool would be set to true

#

and you could check whether or not the bool was true

#

by accessing it from another script

hasty haven
#

Makes sense yeah, I intend to track some things that way

#

I can reference TutorialManager from anywhere with static methods like TutorialManager.ShowBasicMovementInstructions or something similar

#

within that coroutine it checks if player position has changed and then hides the message

#

From my notes:

1. "Use [WASD] to move"
 - Short delay after spawning
 - Persists until player moves

2.  "Hold [Shift] to run faster"
 - Persists until player runs or reaches next section

3. "Press [F] to use your light"
 - Door is blocked by particle field/wall
 - Persists until player turns on light
#

Thats just the very simple beginning stuff but yeah, making sure the tutorial isnt restrictive or overly rigid making you do every single action

#

I noticed a small amount of players never knew you could use a light and had a bad time with our demo as a result

#

At the time there was no official tutorial though, it was notes on the wall you could run by, and some people did. Most players seemed drawn to them though

brisk shore
lean sail
hasty haven
#

This seem like a good way to handle things?
This is a simple example that starts the scripted tutorial once the player spawns in, it waits for the local player to be defined.

The first conditional just waits for them to move and then hides the message.

private IEnumerator StartTutorialDelayed() {
      // Wait for player reference
      while(PlayerController.LocalPlayer == null) { yield return new WaitForSeconds(0.1f); }
      localPlayer = PlayerController.LocalPlayer;

      Debug.Log("Found local player: " + localPlayer.playerAttributes.displayName + 
                "\nStarting Tutorial");

      StartCoroutine(MovementTutorial(localPlayer));
  }

  private IEnumerator MovementTutorial(PlayerController p) {
      if(!p) yield break;

      Debug.Log("Tutorial Message:" + movementTutorialMessage);

      // Display hint text and record initial position
      PlayerHintText.ShowHint(movementTutorialMessage);
      Vector3 initialPos = p.transform.position;

      // Wait for position to change
      while(p && initialPos == p.transform.position) { yield return new WaitForSeconds(0.1f); }

      // Hide when player meets condition
      PlayerHintText.HideHint();
  }
brisk shore
lean sail
heady iris
brisk shore
heady iris
#

you explicitly indicate which objects you want to interact with

brisk shore
#

so like 20 lines of just that is fine?

heady iris
lean sail
#

Yea I drag in references in inspector for most things.

heady iris
#

note that you probably want more specific types

#

notice how, in my screenshot, none of these things are GameObject

#

they're very specific component types that are on those prefabs

#

I have a few public GameObject fields, but they're all in dead code I need to delete anyway

brisk shore
#

how bad is my layout then bc all this is just ui and menuscreens

heady iris
#

that's a separate matter entirely

#

Looks good to me.

heady iris
brisk shore
heady iris
#

If your code looks like this:

GameObject obj = Instantiate(prefab);
obj.GetComponent<Button>().DoSomething();

consider rewriting it to

Button button = Instantiate(prefab);
button.DoSomething():

by changing the field's type from GameObject to Button

#

If the prefab does many things, make a component!

#

I have a lot of components that are mostly just a way to glue other components together

#

i have a MenuButton component that references a text component and a button component

#

it does some work, like setting up a "click" sound when you click on it, too

brisk shore
#

anywhere where i can learn all those basics bc i tried doing the unity tutorials on the unity website but i think those are too basic

heady iris
#

I don't have a good source for this kind of thing. It's just something I figured out over time.

#

I didn't follow a lot of tutorials myself

#

mostly because I had a good programming background already

brisk shore
#

ight thanks for the help

heady iris
#

(if someone else has suggestions, that'd be very helpful!)

somber nacelle
#

vertx's site has a bunch of useful little tips like that
https://unity.huh.how
you kind of have to know what to search for in some cases though

heady iris
#

I've considered writing my own hot takes, but I'm not sure it'd be a net positive given how many places you can already get hot takes from

somber nacelle
#

do it anyway even if it's only for yourself. more backups of this kind of knowledge/useful info is never really a bad thing

lean sail
heady iris
#

those make me suffer

#

you won't believe number 12

#

(number 12 is switching to local mode from global mode)

#

"THINGS I WISH I KNEW"

somber nacelle
#

i saw one of those top 5 unity tips videos recently where one of the tips was just to use print instead of Debug.Log for some reason and at least one of the others was just bad practice

heady iris
#

lol

#

top 0 tips for using Unity

#

video ends

hexed pecan
#

Tbh I cant even think of text-based unity resources other than unity docs, unity.huh.how and catlike coding

heady iris
#

catlike coding is good

hexed pecan
#

And some random blogs

heady iris
#

i vastly prefer well-organized written documentation to basically anything else

#

hey guys today we're going to make an epic first person shooter in just 3 minutes

heady iris
#

somehow

random pelican
#

what is this error?

somber nacelle
#

editor error due to a window you have open that uses the graph editor like shader graph or animator. you can ignore it

random pelican
#

ok

random pelican
# somber nacelle editor error due to a window you have open that uses the graph editor like shade...

my health bar isnt working?

using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class PlayerHealth : MonoBehaviour
{
    public Slider slider;
    public PlayerEnemyCollisionManager collisionManager;
    public TextMeshProUGUI healthText;
    private String currentHealthText;
    private String maxHealthText;

    private void Update() 
    {
        slider.maxValue = collisionManager.maxPlayerHealth;
        UpdateHealthBar();
    }

    private void UpdateHealthBar()
    {
        float healthPercentage = (float)collisionManager.currentHealth / collisionManager.maxPlayerHealth;
        slider.value = healthPercentage;

        maxHealthText = collisionManager.maxPlayerHealth.ToString();
        currentHealthText = collisionManager.currentHealth.ToString();
        healthText.text = currentHealthText + "/" + maxHealthText;
    }
}   
somber nacelle
#

well it's not related to that error you posted

random pelican
#

heres the other script too

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

public class PlayerEnemyCollisionManager : MonoBehaviour
{
    public AttackingEnemies enemyStats;
    public int currentHealth;
    public int maxPlayerHealth;

    private void Start() 
    {
        currentHealth = maxPlayerHealth;
    }

    private void OnCollisionEnter2D(Collision2D other) 
    {
        if(other.gameObject.CompareTag("Enemy"))
        {
            currentHealth -= enemyStats.enemyDamage;
            if(currentHealth <= 0)
            {
                Destroy(gameObject);
            }
        }
    }
}
random pelican
somber nacelle
#

any errors? and be more specific than "not working" what isn't working

random pelican
#

the health bar doesnt even start full and doesnt update and neither does the text

somber nacelle
#

well for starters, is this component actually attached to anything in the scene?
also you should ideally use a filled image rather than a slider, it will look better

random pelican
somber nacelle
#

have you used breakpoints or logs to determine if your code is actually running?

random pelican
#

for some reason currentHealth = 0

#

wait

random pelican
somber nacelle
#

that doesn't answer the question i asked

random pelican
somber nacelle
#

are you referencing the correct object

random pelican
#

maxPlayerHealth = 12

somber nacelle
#

for example, if the PlayerHealth component is referencing the player prefab instead of the instance of the player that would certainly be wrong

toxic lodge
quartz folio
#

The docs have { 0, 3, 1, 2, 3, 0 } listed, but you'll need to do some debugging to show what corners the vertices are at for anyone to helpfully correct the indices

#

By logging their positions, or displaying labels at their positions

#

Can you view that from the back? Ie. is it renderered double-sided?

#

that's the only way I can understand your vertices

#

I would use 0, 1, 2, 0, 3, 1 if I'm correct in understanding their layout

#

can you not look at the other side in the scene view?

#

Well, we don't really allow modding discussion here, partially because it's difficult to communicate solutions when so little of the editor is available to you.
Surely the indices are changing something? Regardless, you need to understand how meshes are constructed. I have a page on triangle winding order that also describes how triangle indices works that might help

nimble cairn
#

Hey guys, just a bit confused on when (or why) I should reference a component through the inspector rather than GetComponent<ComponentType>()

#

Are there instances where I should use one over the other?

#

What are the downfalls to both methods?

latent latch
#

convenience

nimble cairn
#

Are there any performance downside to assigning components through script rather than the inspector?

latent latch
#

downfall to linking it via editor is if you edit variables / serialized values and don't handle it correctly it will unbind from the editor, while doing it via component is more explicit to the location to where this reference may be.

#

performance-wise, you do know the direct reference to the component if linked via editor, but if you handle getcomponent correctly such that it doesn't need to linear search through hundreds of components/gameobjects then it should be minimal

nimble cairn
#

@latent latch Thanks! +rep

#

Just wanted to double check 👍

quartz folio
#

Personally I don't use GetComponent outside of setting up serialized references in Reset and dynamic use-cases.
Setup costs have always come back to haunt me, and so has placing extra requirements on the way components are set up

latent latch
#

I getcomponent usually if it's to that specific gameobject

#

feels strange to link it to itself otherwise

quartz folio
#

I don't, because I rarely create components where that's a requirement. I just set those references up in Reset for convenience, but they're still serialized

latent latch
#

If you were say working on some UI gameobject that had a Image component / Button and you had a script that interacts with it, I'd feel like that's a case where you'd just use getcomponent

#

unless you mean like you mostly keep a lot of that logic off those gameobjects and centralize it elsewhere

indigo cobalt
#

the interpolation value in lerp will automatically use 1 if given a value greater than 1 right?

quartz folio
#

Just like the button having a serialized reference to the image despite them being on the same object, I do the same

quartz folio
#

Whether or not it's clamped is up to the implementation

indigo cobalt
#

what's the unclamped one?

quartz folio
indigo cobalt
#

oh okay thanks

shrewd roost
#

this might be a thing with VS Code that is not applicable to Unity but has anyone had these popups in VS Code? it happens every time I save a script and seems to be 'Restoring' the same few scripts from my project constantly. it appears in the bottom right and doesn't really get in the way, but it's just annoying and idk why it's appearing

rigid island
#

VSCode being its typical charming self xD

#

are you using the Unity extension for VS ?

deft spear
#

How can I reset values in a component in editor when I stop play? OnApplicationQuit doesn't seem to work

cosmic rain
deft spear
#

@cosmic raincinemachineVirtualCamera.GetCinemachineComponent<CinemachineTransposer>().m_FollowOffset.y doesn't seem to

cosmic rain
#

Cinemachine? I think it had a setting somewhere to keep changes during play mode.🤔

deft spear
#

Oh yeah that checkbox was checked, maybe that is why

cosmic rain
#

Yep. That's why. It is so that you can get the settings you like in action and not lose them.

terse turtle
#

Is there a way to mark a scene? I am trying to mark scenes either Combat or Peaceful. How can this be done?

shrewd roost
void basalt
#

if it tries to load a scene and can't find the script, throw an exception

rigid island
#

!vscode

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

terse turtle
shrewd roost
sullen fern
#

I'm using mouse delta in order to move my camera, but when starting the game in the editor it always moves a large amount at start sometimes bugging my script

leaden ice
sullen fern
#

i havent done that sort of code before

#

how would you skip the first frame?

leaden ice
#

Could be as simple as:

#if UNITY_EDITOR
  if (Time.frameCount <= 0) {
    return;
  }
#endif``` in Update
#

you can change the number to something higher if you need to skip multiple frames

sullen fern
#

I'll try that out

#

thank you

#

uh do i put this into like my update function?

leaden ice
#

I did say "in Update" didn't I?

sullen fern
#

youre right

#

im blind

#

took 4 extra frames but it seems like that has fixed it

#

thanks!

terse turtle
#

Why is Player Duplicating? c# private void Awake() { if (instance == null) { DontDestroyOnLoad(gameObject); instance = this; } else if (instance != this) { Destroy(gameObject); } }
I have the same code on the GameManager, but that object doesn't duplicate?

leaden ice
leaden ice
#

Where did you put logs? What printed?

terse turtle
#

Its printing at the instance !- this*

#

the null part is printed at the start of the game though

leaden ice
#

Then it's being destroyed

terse turtle
leaden ice
#

So it's working

terse turtle
leaden ice
#

And what are those objects? What components are on them?

terse turtle
terse turtle
cosmic rain
#

Is instance static?

terse turtle
cosmic rain
#

Then it would be null of course

leaden ice
terse turtle
#

Thanks for the help. 😄 I need to be more attentive to my code.

fervent coyote
#

Hello, I am getting a weird error when making projectiles:
This is the code that runs Instantiating projectiles:
GameObject _spawnedProjectile = GameObject.Instantiate(_Combat._Projectile, origin.transform.position + new Vector3(0, 0.6f * (_charcontroller.height / 2), 0) + pos + (origin.transform.right * 0.2f), Quaternion.Euler(dir));
And this is what dir is
MainCamera.transform.forward
Using debug, it turns out dir is approx: (-0.00872, 0.00034, -0.00017, 0.99996)
However, using dir is also used for raycasts, and raycasting (And debugging raycasting while I'm at it) works fine! How can I convert so the projectiles will work correctly? Thanks

#

Okay, so I know what I'm doing wrong...

Unity is weird with rotations. So I guess my question is, how do I convert transform.forward directions to eulerAngle directions. I really prefer to use just one dir in my code as it is used by both the player and NPCs to shoot

fervent coyote
#

Thank you so much

mellow sigil
#

you can just use MainCamera.transform.rotation though

fervent coyote
#

Oh, I know

So, basically, dir is used for raycasts (hitscan). And also, it is using both the player AND the NPC view. For the player, it is as described above, for NPCs:

(target.transform.position + (Vector3.down * 0.5f)) - transform.position

#

Essentially, i guess this is setup for Raycasts

#

Before, I just did use what you recommended me for both the player and NPCs... However, I wanted to combine both into one script since they work basically the same. So, when I did, this issue came up

#

Thank you for your help, works flawlessly!

lofty crest
#

I am trying to make a dialogue system i have a dialogue trigger on my npc.

#

On my dialogue box i have a dialogue manager

#

but it just wont trigger,

knotty sun
#

so how are your colliders and rigidbodies set up?

lofty crest
lofty crest
#

this is on my npc

knotty sun
#

So you need to add some Debugs to your Trigger script to see what is/not happening

lofty crest
#

ok wait where do i put the debug triggers?

cosmic rain
#

In code

knotty sun
#

do you not know what Debug.Log is?

lofty crest
#

can it just be put anywhere?

knotty sun
#

what code do you expect to run when a Trigger happens?

lofty crest
#

i am trying to follow along this video and understand it, and i just dont know what is wrong

knotty sun
#

answer my question

lofty crest
# knotty sun answer my question

well if i understand correctly, in unity i can create elements which have the dialogue lines or icons etc, and then sends it to the dialogue manager when the player collides with the npc

knotty sun
#

that is not what I asked.
Specifically which method in your code should run when a trigger happens?

lofty crest
#

is it not public void TriggerDialogue ()

knotty sun
#

no it is not

lofty crest
#

then im missing something

knotty sun
#

where does TriggerDialogue get called from

lofty crest
#

is it private void OnTriggerEnter2D (Collider2D collision)
{
if (collision.tag == "Player")
{
TriggerDialogue();
}
}

#

sorry im a begginer

knotty sun
#

yes, so that is where you need to add Debug statements

#

but this shows you have made all of this code and not understood a single thing about it. Programming is not just about writing code you must also understand every word that you write

lofty crest
#

wait what is wrong here on line 39

knotty sun
#

That is not how you write Debug.Log statements.
If you dont know something go and look it up in the documentation

#

that is also not where you want the statements, it would be pointless

lofty crest
#

@knotty sun based on the Debug.Log it is triggering

knotty sun
#

show code and console

lofty crest
knotty sun
#

ok, so now we need to know what is triggering this if it is not the player. So add the collision tag to your debug.log

lofty crest
#

the player is triggering it

knotty sun
#

no, it gets triggered when anything enters the trigger

#

how do you know it is the player if you do not show that in the debug.log?

lofty crest
knotty sun
#

but it says player because you have hardcoded "Player" not because it is the player

dusk apex
#
Debug.Log($"{collision.name} triggered {name}", collision);```
fervent furnace
#

it can be maincamera if you tag it to be main camera

knotty sun
#

we need the tag in the debug

native fable
#

Hello

When I recompile scripts, subscriptions to buttons in the editor window fall off, well, in general, everything is reset, the objects are null

Is it possible to fix this somehow? Should I re-init?

cosmic rain
lofty crest
dusk apex
dusk apex
lofty crest
dusk apex
#

Make sure to click the message and see which object becomes highlighted yellow

lofty crest
dusk apex
#

Is it the expected object?

lofty crest
#

yes the player is the object that triggers the shroudling

fervent furnace
#

use .comparetag to see if there is player tag first
then check the tag of the object that "looks like player"

dusk apex
#

Is the object tagged correctly in the inspector?

knotty sun
#

show the inspector of the Player object

lofty crest
dusk apex
#

We need to see the tags above

#

Note that Player object needs to be tagged "Player"

lofty crest
#

ah

#

im so stupid

dusk apex
native fable
lofty crest
#

ok it is working

cosmic rain
lofty crest
cosmic rain
native fable
#

I found such events, but then it’s not very clear how to correctly unsubscribe from them

cosmic rain
#

Doesn't sound like a great way. Assembly reload is not just compilation. You might be executing code when the objects are not even initialized yet.@native fable

knotty sun
#
        protected void OnFocus()
        {
            if (error == null)
            {
                Init();
            }
        }

        internal void Init()
        {
            error = new ErrorLine(this);
            Initialize();
            this.Show();
        }
native fable
cosmic rain
#

InitializeOnLoad/InitializeOnLoadMethod attributes docs literally say that they are for keeping your editor scripts initialized on domain reloads.

knotty sun
#

unsubsribe in OnDestroy

native fable
knotty sun
#

but the domain reload does

quaint crypt
#

hello, I am developing a multiplayer game, with NGO (I dont want to use steamworks p2p or anything low level like that), but also want some steam integration such as: being able to join steam friend lobbies via right click -> join, or being able to find friend servers via the server browser. what addons / packages do you recommend for me to use to speed things up?

native fable
knotty sun
#

It's being called for me

cosmic rain
native fable
native fable
#

Editor tool

knotty sun
#

Then IMGUI. Take a look at AssemblyReloadEvents

#

btw I build all of my new Editor tooling using UIToolkit it is so much better than IMGUI

native fable
#

somehow this is correct?

native fable
# knotty sun Then IMGUI. Take a look at AssemblyReloadEvents

like this?

    public class SdkManager : OdinMenuEditorWindow
    {
        [SerializeField]
        private SwitchSdkView switchSdkView = new SwitchSdkView();
        private SwitchSdkProcessor _switchSdkProcessor;

        [MenuItem("Sdk/SDKSwitcher/Window")]
        private static void OpenWindow()
        {
            var window = GetWindow<SdkManager>();
            Debug.Log("ShowWindow");
            window.Show();
        }
        protected override void OnEnable()
        {
            base.OnEnable();
            AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
            AssemblyReloadEvents.afterAssemblyReload += OnAfterAssemblyReload;
        }
        
        protected override void OnDisable()
        {
            base.OnDisable();
            AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;
            AssemblyReloadEvents.afterAssemblyReload -= OnAfterAssemblyReload;
        }

        private void OnAfterAssemblyReload() => Init();
        private void OnBeforeAssemblyReload() => Dispose();
        
        protected override void OnDestroy()
        {
            base.OnDestroy();
            Dispose();
        }

        private void Init()
        {
            _switchSdkProcessor = new SwitchSdkProcessor();
            _switchSdkProcessor.Init(switchSdkView);
        }

        private void Dispose() => _switchSdkProcessor.Dispose();

        protected override OdinMenuTree BuildMenuTree()
        {
            OdinMenuTree tree = new OdinMenuTree(supportsMultiSelect: true)
            {
                { "Switch", switchSdkView, SdfIconType.ToggleOn }
            };
            
            return tree;
        }
    }
distant ice
#

Is this a place I could ask about Vivox?
I'm struggling really hard to be able to start the vivox client muted x.x

thin aurora
#

Asking questions about specific libraries usually do not fit here unless they ar every commonly used. I never heard of Vivox, and I don't think you really can get an answer here

#

You're better off asking in their server if they have one

vapid condor
heady iris
#

Is there a decent way to get a REPL (i.e. an interactive C# interpreter) in Unity?

#

it'd just be more convenient than repeatedly editing and recompiling the test code

late lion
heady iris
#

oh, neat

late lion
# heady iris oh, neat

Rider also has an immediate scripting window when you're paused on a breakpoint, but then you have to have somewhere to pause.

heady iris
#

oh right, I think you can do that in VSCode as well

late lion
heady iris
brazen pebble
#

ok - my google skills are failing me. I'm trying to create a global list (probably a scriptable object) that contains a list of ItemOptions class. Then in my Item class I want to have a list of ItemOptions but only pick specific ones from the global list - preferably in the inspector. Is that possible? I'm failing to come up with ideas...

storm bough
#

Hey, guys, not sure where to post this? I was only hoping for some advice. I was asked if it was possible to make a desktop application in Unity, the purpose of which would be to have a button that you press to select files (in Windows explorer), and then build an asset bundle from these selected files via another button. I tried googling around but there is a big issue number one - you cant use Unity Editor commands in a build, and I'm not sure I can build asset bundles without using Unity Editor?
Any advice on if such app is even possible to make?
Edit: I do know how to normally make asset bundles in Unity. They were hoping to make an app that can do this automatically without running Unity engine for it.

storm bough
round violet
#

hello,
im trying to get the source collider of a OnCollisionExit, since its a child i am using .GetContact(0).thisCollider
but when doing this i get an error (there are 0 contact)

i dont understand why this doesnt work, because it does with OnCollisionEnter

hexed pecan
#

I suppose that there just are no contacts since the collision ended

round violet
round violet
hexed pecan
#

Seems like checking the last contacts from OnCollisionStay could work.
I'm not sure though - it seems really hacky

round violet
#

yeah

#

ty for trying to help

polar marten
tired pecan
#

can somebody pls help me im trying since an hour or so to code a basic jump n run controller with the new input system but whenever i change a random thing i the code unity says nullreferenceexcaption what does this even mean

round violet
#

i forgot to edit my message, i updated my code
i have each of my child using OnCollision and calling a parentOnCollisionExit with the Collision and self

round violet
#

this way i got the child who got entered and exited

#

the issue is i have to use more rigidbodies

polar marten
# round violet this way i got the child who got entered and exited

with unirx, you can do

this.OnCollisionEnterAsObservable()
 .SelectMany(entered => this.OnCollisionExitAsObservable()
                            .Where(exited => exited .collider == entered.collider)
                            .Select(_ => entered))
 .Take(1)
 .RepeatUntilDestroy(this)
 .Subscribe(thisArgumentIsTheColliderWeEnteredWith_CalledAtTheTimeItExits => { ... });
round violet
#

ima be honest this code is to complex for me

polar marten
tired pecan
polar marten
#

you can create a bunch of variables and fields to do the same thing, it will be more code, more buggy and more complex

tired pecan
round violet
rigid island
tired pecan
rigid island
#

this isn't helpful. get the stack trace and we can start with something otherwise this is wasting time lol

tired pecan
#

sry

polar marten
tired pecan
#

i restarted visual studio and now everything works wtf. don´t even try explaining me this i won´t understand

swift falcon
idle oxide
#

So I've been just simply trying to get some sort of detection that would allow enemies to see the player to work. I'm just trying to shoot a ray to the player position from the enemy and if it hits the player it will do something but I'm encountering a problem which I can't figure out why it's happening (tbh it's probably something stupid and I'm just too blind to see it). I would really appreciate any help!
Code: https://gdl.space/qusutafimu.cpp

random relic
#

i want to make planets on wich you can walk i got that but i dont know how to rotate the camera when walking around the planet

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

public class GravityControll : MonoBehaviour
{


    public GravityOrbit gravity;
    private Rigidbody rb;
    public float RotationSpeed;


    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {


        if (gravity)
        {
            Vector3 gravityUp = Vector3.zero;
            gravityUp = (transform.position - gravity.transform.position).normalized;


            Vector3 localUp = transform.up;
            Quaternion targetRotation = Quaternion.FromToRotation(localUp, gravityUp) * transform.rotation;

            transform.up = Vector3.Lerp(transform.up, gravityUp, RotationSpeed * Time.deltaTime);

            rb.AddForce(-gravityUp * gravity.Gravity);
        }

    }
}

this is the code for the gravity

swift falcon
#

Hello! I am trying to update a variable named questionItem in questionManager and when im trying to see it in the inspector, it doesnt update properly, it remains the value before

somber nacelle
#

!code

tawny elkBOT
swift falcon
somber nacelle
#

now instead of making everyone dig through your code, why don't you tell us where you are trying to do this

swift falcon
somber nacelle
#

well for starters, that questionItem variable in Answer is unrelated to the one in questionManager. now explain what you mean when you say "it doesn't update properly"

somber nacelle
#

in what way

#

keep in mind that i am neither a mind reader, nor can i see your screen

swift falcon
#

im trying to update questionitem to the first item in OnPrev() in questionManager

#

and the second in OnNext()

#

i meant the children objects in questionManager

somber nacelle
#

well again, i don't know what you mean by that. and also none of the code in the Answer class does anything to any child objects

#

nor does it do anything at all to questionManager

swift falcon
#

as you can see in the right, the elements update in the second question even though i have selected the first one. the update code uses questionItem

somber nacelle
#

you need to show your Question class since that is where anything is happening. your Answer class does not touch questionManager at all
this also appears to be a mess of singletons that are going to be a bitch to untangle and debug

swift falcon
somber nacelle
#

and yet you said your issue is within the methods inside of Answer, which do nothing at all to anything inside of questionManager

swift falcon
#

question script

somber nacelle
#

jesus this really is a gigantic mess of GameObject.Find calls, singletons, and relying on gameobject names. you're going to need to use the debugger to figure this out yourself

swift falcon
#

imma use it then

keen smelt
#

Hello friends. I just figured out how to actually use singletons properly. God I'm such an idiot. Life is good. I just needed to share. That is all, thank you all!

hexed pecan
#

Change targetPos to "targetDir". You can calculate a direction from vector A to vector B with B - A

idle oxide
hexed pecan
#

B - A, not A - B

#

So target.transform.position - pos

idle oxide
#

Okay thank you I will try that out!

swift falcon
#

I can still play my game and it works fine can I just live with my life and move on?

oak siren
#

Looking for some advice on how to structure code in C# and unity.
I'm working on a game which I want to contain a large number of items, skills & enemies, somewhere in the 100s total.
Each of the 3 categories follows the same principle design of having 1 abstract class, and then everything inheriting from those.
The problem arising from this is how to cleanly define these items/skills/enemies, as it feels like a lot of classes which may not be necessary.
The way I would approach this problem naively would just be by creating 100s of classes with constructors defining the different fields (say damage for item), and some of those having a special behavior when attacking, for which I would have a method to be executed on an attack.

Performance isn't a huge priority for me, as this would mostly be a turn based game during the times when this would matter, but I'd still be very interested in better performing solutions that offer the same features and logical encapsulation.

I'm looking for alternative approaches to this problem, whether that is defining some stuff in XML (like the basic fields they inherit), and then reading that into a Dictionary which I would use in my constructors, or something else that c# or unity allows me to do (maybe these should all be prefabs? I'm worried about the moddability of that).

What I do like about the current approach is that I would definitely be able to keep all the data & logic of any item/skill/entity in one file, which is quite nice.

Here is an example:
I have an item class
I have a weapon class which inherits from that item class, this weapon class has some custom functions.
I have a sword class which inherits from that weapon class and changes a lot of fundamental field values
I have 5 generic swords which might make slight changes to fields
I have a special sword which wants to override a base function defined in weapon to add some functionality.

Any advice would be much appreciated and sorry for the long post

latent latch
oak siren
#

Alright, ty @somber tapir @latent latch, I'll look into those for a bit and see if they're a good fit. At first glance they do seem to be more 'unity' than pure classes (especially since they'd allow non-programmers to more easily modify certain fields) but I don't immediately see any fundamental differences in the way I'd use them vs what I was thinking before

oak siren
rigid island
#

the major benefit is making many different as assets

oak siren
#

But yeah ok

rigid island
#

they're quite powerful

#

Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. In this talk, Schell Games shares specific examples of how they have used the Scriptable Object for everything from a hierarchical state machine...

▶ Play video
latent latch
oak siren
oak siren
latent latch
#

edge cases are more of a programmer error. If there's bad combinations then just dont craft them ;)

#

but hey, maybe you do eventually want a bow that shoots out sword beams

oak siren
#

like an IGolden wouldn't rly work

#

Or well it would

latent latch
#

Well, you'd have a sword an bow class derived

#

that's fine for polymorphism

oak siren
#

but it'd be annoying to have to copy paste the exact same code every time

somber tapir
#

if you have to copy paste the same code than you are doing something wrong.

oak siren
#

exactly

latent latch
#

I just wouldn't make two sword classes where one shoots beams of light, and the other that does a whirlwind attack, but later on want a sword that shoots beams of light and does a whirlwind attack

oak siren
#

That's fair

latent latch
#

But if it's just a handful of classes then it's probably fine. I'm just speaking for expandability

#

Not everyone is making a looter shooter

oak siren
#

Hey I mean it's still worth thinking about I think

#

But tbf I don't think it would really change my architecture fundamentally

#

I could add a separate skill effect or something later

#

So that's not a super big concern rn

#

I think

polar marten
# oak siren Looking for some advice on how to structure code in C# and unity. I'm working on...
// attached to base prefab
abstract class Weapon : MonoBehaviour {
 abstract async Task<...> Attack(Context context);
} 

// attached to prefab variant
class ScimitarOfGonads : Weapon {
 public float range, damage, duration;
 async Task<...> Attack(Context context) {
  await Attacks.Whirlwind(context, range, damage, duration);
  await context.Delay(0.3f /*seconds*/);
  await Attacks.Beam(context, range, damage, duration);
 }
}

@oak siren

#

however if you are making this kind of game for PC, use Unreal, and use its Gameplay Attribute System

latent latch
polar marten
#

use a prefab, it's better

#

i wouldn't ever program inside a scriptable object

#

lists of actions and delegates to invoke => a method

#

just write a method

oak siren
polar marten
#

i wouldn't invent a programming language inside XML

latent latch
#

It doesn't need to be on the SO, but on the class itself. You can simply map keys to the method which you'd populate the container with.

polar marten
#

mapping keys to methods, populates, containers... just write the method and call it

oak siren
polar marten
#

i really wouldn't overthink it

oak siren
polar marten
oak siren
#

lol

latent latch
#

You still need to make a bunch of different classes, and prefabs where you can just have a general Weapon prefab to build upon.

polar marten
#

yeah it's im possible to not write code

#

you will be writing code somewhere

oak siren
#

But so fundamentally you'd more or less suggest I go with my original approach

polar marten
#

it's upt o you: do you want the code to be written in C#, or do you want it written in XML

#

yes, but i am trying to illuminate that an effect is "just" a static method somewhere

oak siren
#

fair

amber sinew
#

@oak siren Like other people said, scriptable objets using custom editors might save you a lot of trouble. If any weapon can be summed as a collection of values and pre-defined behaviors/objects that can themselves be stored as assets, then you don't need to write them manually through a constructor.

polar marten
#

if you want to make a method reusable, i guess, you know, make it a method and call it in mulitple places

#

don't do any scriptable objects or editors or whatever

#

all of that stuff is a colossal waste of time

#

trust me

#

it takes 5s to write a constructor and it will tell you if you've made a mistake.

latent latch
#

scriptable objects for data is fine for reusability

#

there's a reason we use it over plain text or json everywhere (otherwise enjoy explicitly typing out asset paths)

#

but again, I speak for making more than 5+ weapons

amber sinew
#

Also, you can define "default" behaviors for any field that is left unfilled. For example, if you have an "axe" scriptable object, it can be assumed that the very vast majority will share similar base traits, maybe the same attack speed, base damage, attack animation,... in which case you will only need to fill these values if you want to override the default behavior

oak siren
amber sinew
#

It's mostly about reusability, and ease of use. There are multiple ways of achieving that result, but using scriptable objects makes editing stats, models, animations much simpler than going through constructors

rocky jackal
#

can i somehow turn all these variables into the default variables from my script ?

polar marten
#

you can also right click on any value

rocky jackal
#

oh no, i meant the other way arround so the default variables become the shown variables

polar marten
#

and i think it has reset as an option

polar marten
#

not in one command. you can certainly just copy and paste the values in

#

into the .cs file

#

or create a preset

#

that's the button that looks like two bars with knobs in them

#

to the left of the triple dots

civic folio
#

How would you go about detecting mouse click at a point somewhere along a dynamic 2d path?

polar marten
civic folio
#

I could use a line renderer

#

so yes

hexed pecan
#

@civic folio Search the web for a function that gives you a distance from a point to a line segment

#

Just make sure to have all the coordinates in the same Space (world or screen space)

leaden ice
#

Most spline frameworks give some kind of "GetNearestPointOnSpline" function

civic folio
#

I thought splines are always curves

leaden ice
#

they can be curvy or jagged

#

generally curves yes

#

"dynamic 2d path" was quite vague

civic folio
#

wasn't sure how to call it

#

I was thinking of Sebastian Lague's logic simulator and how you can click at any point to split the wires

#

and how the corner rounding works, a fixed distance bezier curve?

#

I tried reading the source code of that once but I think it was a little beyond my knowledge

rigid island
leaden ice
civic folio
#

what's the difference between a spline and an array of points

#

I always thought about splines like of bezier curves

hexed pecan
#

GetNearestPoint would convert the spline into an array of points anyway, AFAIK

#

Splines allow for infinite curvature, an array of points doesn't

leaden ice
sharp lotus
#

hey gang, im having an issue where when in the editor i run my menu scene, with a canvas button for "play", it all works and executes without error. but when i build it it sorta locks up on clicking the play button. the button does even change color upon clicking, but then just stays like that

#

i can provide more info if needed, or even the build. im just unsure what i can share that may help

somber nacelle
#

start by checking the player !logs to see if there are any errors happening when you click the play button

tawny elkBOT
#
📝 Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

sharp lotus
somber nacelle
#

the build since that is where your issue is happening. you don't need to manually look at the player log when using the editor since exceptions and logs are printed to the console

dim umbra
#

What's a good way to have an enemy damage you, but be killed by getting jumped on? I've tried a few different methods but they all seem to have flaws, mostly due to how fast the player could be moving when they're falling on an enemy

hexed oak
#

Is there a way to prioritize something to run before unity encounters the "enter safe mode" screen? I'd like to make a junction to another folder before it opens

rigid island
dim umbra
# rigid island what problem are you having, you can do it different ways including just math or...

The way I'm doing it now is that I check if the player is touching the enemy, has downward velocity, and is more than a certain height above the enemy. This doesn't work because with how fast the player is traveling, it occasionally goes below that height threshold and thus doesn't kill the enemy. If I make the threshold any lower, you'll be able to kill the enemy just by running into the side of it with a downward velocity

#

Basically it's not touching the enemy one frame, and by the next frame it's already below the threshold

rigid island
#

Another way i would try it is using Dot product or something like that on the head

#

and only make it count as kill if the hit/collision point is within that dot product

dim umbra
#

I'll try it

vagrant agate
#

Show a picture of what you mean by stretching

pulsar holly
#

Whenever I try to rotate an object, it doesn't go down when the angle changes, it moves depending on the angle.

#

I'll show the code ASAP

#

!code

tawny elkBOT
pulsar holly
viral prairie
#

Hello i am currently trying my luck with multiplayer and i have come across the problem that i am trying to fill the network prefab lists of the network manager but the list just "wants" so called "Network Prefab List" as a object,
i have no clue to what this could be or why it doesnt want objects.
does anybody now something more?

viral prairie
#

ok thanks i didnt knew that channel existed

rigid island
#

were you just guessing your way though ?

pulsar holly
#

Whenever I try to rotate an object, it doesn't go down when the angle changes, it moves depending on the angle.

somber nacelle
pulsar holly
vagrant agate
pulsar holly
#

The object is moving in the direction of the z rotation axis.

#

It's not going down despite the direction.

vagrant agate
#

Yea im going to be honest, your code has a multitude of design problems ,if you continue coding your movement like this, you will continue to have unexpected behavior.

I would advise you learn some better movement methods, we would have to rewrite your whole movement logic, unless someone else wants to step up to this one lol.

rigid island
#

why

cosmic rain
#

Yandere dev apprentice

somber nacelle
#

every time they've posted code they've been asked to format it correctly. they still refuse to. and they keep using these sites that don't even offer syntax highlighting so reading it is an absolute pain

vagrant agate
rigid island
#

yea formatting does huge difference, even still this code is scary looking lol

cosmic rain
rigid island
#

dude hates brackets fr

cosmic rain
rigid island
#

the only one that might have a chance is rotation.x == 0

#

even still float point approx is needed prob (but yeah rotation is prob not what you think it is)

pulsar holly
#

Where should I put the brackets?

vagrant agate
pulsar holly
#

Why is the position changing based of the rotation?

#

If the rotation is 180, the game object doesn't go down.

rigid island
#

because you're using Quaternions

#

they never reach above 1

pulsar holly
#

How do I fix it?

rigid island
#

use euler angles

pulsar holly
#

How do I do that?

rigid island
#

have you tried googling it

pulsar holly
#

I just did

rigid island
#

and?

#

should be first result

cosmic rain
cosmic rain
vagrant agate
#

i sure hope that isnt a tutorial on the internet

rigid island
#

at this point nothing surpise me if it were xD

pulsar holly
#

I'm using tutorials, I think.

vagrant blade
vagrant agate
#

Anthony kind of reminds me of hitting regenerate response on chat gpt question

swift falcon
#
#if UNITY_EDITOR

using UnityEditor;
using UnityEngine;
using UnityEngine.Tilemaps;

[CustomEditor( typeof( Tilemap ) )]
public class SceneMouse : Editor
{
    public Vector3 MousePos;

    void OnSceneGUI(SceneView sceneView)
    {  
        // Vector3 mousePosition = Event.current.mousePosition;
        // MousePos.y = sceneView.camera.pixelHeight - mousePosition.y;
        // MousePos = sceneView.camera.ScreenToWorldPoint(mousePosition);
        // MousePos.y = -mousePosition.y;

        // Debug.Log("OnSceneGUI");
    }
}
#endif```What are these?
#

am i using OnSceneGUI wrong?

somber nacelle
swift falcon
#

oh

#

copied it from a forum,

#

right, this

dim umbra
#

I have a rotating circle collider, how can I make an object copy its position exactly without rotating? I tried using a script to do this, but the object always trailed one frame behind the position of the circle collider, which messes up my collision detection

#

to be clear, the script set the objects position to the circle's position every fixed update

somber nacelle
#

is the circle's position also changing in FixedUpdate? if not, then the issue is because you are changing the position on a different time step

dim umbra
#

It's just a physics object, so I assume yes

#

Is there something like "LateFixedUpdate"?

somber nacelle
#

no, you could try LateUpdate though. or even Update. or a coroutine with yield return new WaitForFixedUpdate. physics updates after FixedUpdate but before WaitForFixedUpdate and Update

dim umbra
#

Doesn't seem to fix the problem

tall lagoon
#

hey guys im doing a science fair project and i need help with collsions so i have this cube that learns how to navigate the course by collidng with these walls and in order to learn i run this code when it collides the ones that are facing straight at the bottom of the picture at set at 0 and the one snext to rotated one is 90 and these perfecly fine but when the cube hits the 45 degree angle on it dosent even collide with it when i debug.log i can conform without the 45 degree angle check it collides but when i add it to the if stement it dosent detect collison anymore.is it bc its a child?

#

or what could be wrong?

#

its 45 in code and inspector

somber nacelle
#

don't base your logic on the eulerAngles like that. they are interpreted from the quaternion at the time you access them and may not be what you are expecting them to be because multiple sets of angles can be the same rotation

tall lagoon
dim umbra
# dim umbra Doesn't seem to fix the problem

I guess what I would need is for it to be at the exact same position as the circle, after the circle's position updates but before it checks collision. Is that even possible to do?

tall lagoon
#

should i do this insted?

somber nacelle
#

no because that's basically the same thing

tall lagoon
somber nacelle
#

no because that is still basically the same thing

tall lagoon
#

so what should i use insted if quaternions are not angles?

somber nacelle
#

accessing differently named properties that all do the same thing (interpret eulerAngles from a quaternion) is all going to lead to the same issue where the returned angle may not be what you expect. not only that but floating point imprecision is going to cause issues with equality

somber nacelle
somber nacelle
#

okay well that's not even the important part since you weren't reading the individual components of a quaternion

tall lagoon
#

its says i hsould familerize myself with.dot prduct

lean sail
tall lagoon
#

checkpoint postion

#

its really imporatnt

#

but it depends on the rot

#

and its weird

#

but its the way the ai learns

somber nacelle
#

this feels like you're trying to recreate ML agents without actually using ML

tall lagoon
#

thats what im using for this project

tall lagoon
#

i prmoise

#

i just need this quicly bc i need have something to show in1 hour

lean sail
somber nacelle
tall lagoon
#

so for the 45

#

i need to check the x pos

#

and if the x pos is less than

#

the chkecpoint pos

#

bc for the ones with 0 rot we check if the cube is above it

#

and when its 45 we need to go to the x pos

#

or check x pos i mean

tall lagoon
#

or something im doing wotng?

#

plz

dim umbra
potent saffron
#

Hello! My name is Ricky, and me and a friend are making a simple horror game, in a forrest within a maze. We have been using Unity Terrain - HDRP Demo Scene (and ofcourse HDRP) and started to aid foilage like grass and bushes to our floor. They are just spread around and dont look like much but are bursting with verticies causing this monstrosty of a stats window.

I have no clue what to do and how to get this to run proparly. Can anyone point out any suggestions?

  • Ricky
#

Occlusion culling does'nt do anything for the performance.

lean sail
# tall lagoon or something im doing wotng?

what you're describing is basically to gibberish to others. The rotation of an object has nothing to do with where a cube is, so it doesnt really make sense. Still got no clue what you're trying to ask tbh

lean sail
dim umbra
#

The box collider should stay in the same relative position the whole time but doesn't

rigid island
dim umbra
#

no parenting involved

#

it rotates

#

I can't parent

rigid island
#

wdym

#

ur talking about JumpHitBox?

dim umbra
#

the circle collider is rotating

#

if I made the box a child it would also rotate

#

so I have to use a script to set the position

rigid island
#

u put it inside update ?

dim umbra
#

It's in fixed update

rigid island
#

put it in update

dim umbra
#

I think that fixes it visually but I don't think it fixes the physics of it

rigid island
#

if you want something more accurate ditch the script and the separate object comepletly

#

use physics queries inside update

#

BoxCast, OverlapBox or even CheckBox

dim umbra
#

I'll look into those

swift falcon
#

https://gdl.space/iqebofoyup.cs does unity have other callback that happens literally everytime? (without needing to have a TileMap selected, cause this one does need)

rigid island
swift falcon
#

actually, yea

#

but imma just keep it here for now, not too crucial fn anyways

heady iris
#

Unity is calling a constructor in a POCO class when I recompile. I don't believe is serialized anywhere, but removing [System.Serializable] makes the issue stop.

I'm loading something from Resources in the constructor, which is causing an error.

I'll get around this by just moving this logic to an "init" method I explicitly call, but...this is very weird!

The stack trace isn't very enlightening here.

#

It looks like Unity always winds up constructing an instance of a field type if the type is serializable, even if it's not serialized

#

(i originally thought inheritance was involved, hence "Child")

#

the more you know, I guess 🌠

#

it should trigger an error on recompile if Child is attached to an object in the scene

swift falcon
#

yea unity objects always create a poco class they own when it is serializable, you cant even null it

#

doesnt even care as well for modifiers

#

you can make the field [NonSerialized] though

#

(ʀᴇᴀʟɪᴢᴇᴅ ɪ ᴊᴜsᴛ ʀᴇᴘʜʀᴀsᴇᴅ 80% ᴏғ ᴡʜᴀᴛ ʏᴏᴜ'ᴠᴇ ᴊᴜsᴛ sᴀɪᴅ)

heady iris
#

I doing think NonSerialized helped

potent saffron
#

And yes, its a different project

normal mica
#

i just found out about StateMachineBehaviours and they seem like a really interesting way to manage behaviors that apply to specific states - now i'm thinking about trying to use them for everything (e.g. the docs use them for Grounded checks) and i'm wondering if anyone has insight on whether this is a good idea or will cause me trouble down the line?

rigid island
#

Animator just makes all the boiler plate code for you mostly

heady iris
#

I use state machines all the time, but not using the Animator Controller

normal mica
#

yeah state machines seem like a clear must, but why not just use the animator controller to have a graphical representation of the state transitions then?

#

seems like the alternative is having two different state machines that are hopefully kept in sync

rigid island
#

not easy to search through states

#

idk sometimes gui gets in the way but if thats your speed go for it

normal mica
#

well i feel that actually, big reason why i get tired of unreal blueprints and shader graphs and wish i could just do it all by hand lol

rigid island
#

if you work with anyone else like designers i try to make some gui tools when possible otherwise animator is a perfectly capable fsm

#

and you still need to write scripts , they just go inside the animator

normal mica
#

sounds like there's no obvious pitfalls anyway and this is a prototype so i'll just give it a go

#

thanks for the input!

swift falcon
rigid island
#

prob best have that instead

#

this should be inside ifeditor anyway

quartz folio
#

.... but ExecuteInEditMode is just ExecuteAlways but you're too lazy to check if it works in Prefab Mode

swift falcon
#

ExecuteAlways is new ig (me is dont have it)

quartz folio
#

Things aren't "new" when you don't have them, you're just in ancient history

swift falcon
#

new is relative blushie

drifting crest
#

Hey guys I am trying to produce a steering wheel behaviour to control a ship but i don't know why the steering isn't giving well response is it because of transform.translate? that the ship isn't rotating

rigid island
#

its probably not what you expect them to be

drifting crest
rigid island
hexed pecan
#

Reading from world euler Y of the wheel seems a bit sketchy, I would use localEulerAngles at least

drifting crest
drifting crest
hexed pecan
#

Dont need the rotation in the middle

drifting crest
#

I want the ship to rotate smoothly according to the steering wheel's rotation

hexed pecan
#

Is the wheel's Y axis pointing forward?

drifting crest
#

and I have made wheel a child of an empty gameobject

hexed pecan
#

Also yeah log all of the floats involved in this and see if they are what they're supposed to be

hexed pecan
#

And check that rotationSpeed has the correct value in the inspector

#

Not just the default value kn code

drifting crest
#

also the wheel is rotating in 360 when it is supposed to be rotate in one axis as I have locked it's constraints in rigidbody

long scarab
#

how can I visualize a raycast for debugging? I tried using Debug.DrawLine() but its not showing in game

hexed pecan
long scarab
hexed pecan
#

Maybe your positions are wrong then. Show code?

#

DrawLine does work for that

long scarab
#

full script or just raycast function?

hexed pecan
#

Raycast, for starters

long scarab
#
private void checkInteractable()
    {
        Ray interactRay = new Ray(Hand.transform.position, Hand.transform.forward);
        Debug.DrawLine(Hand.transform.position, Hand.transform.position + Hand.transform.forward);
        if(Physics.Raycast(interactRay, out RaycastHit hitInfo, InteractRange))
        {
            if(hitInfo.collider.gameObject.TryGetComponent(out Interactable interactableObject))
            {
                Debug.Log("Interact ray fired and hit interactable");
                InteractionTarget = interactableObject;
                InteractionTarget.ShowInteractButton();
                Debug.Log("Interaction available");
            }
        }
    }```
hexed pecan
#

Is this called every frame?

long scarab
#

yes

hexed pecan
#

Looks good to me then, you sure its running?

long scarab
#

yup

#

it was working when i raycasted off my playercam

#

but its positioned at an offset, so it was detecting and printing debugs when it shouldnt have

hexed pecan
#

Maybe Hand is not where you think it is?

long scarab
#

i added a hand object and tried to raycast from it and now its liek a 10% chance it hits

long scarab
rigid island
#

try giving it long duration time

long scarab
#

i just grab a gameobject reference via inspector

long scarab
hexed pecan
rigid island
hexed pecan
long scarab
#

now its showing but its not registering the hit

drifting crest
#

their InteractionBehaviour Component requires rigidbody

rigid island
#

Debug lines don't collide

long scarab
#

i'm seeing the drawline hit the target, but the ray itself isnt

drifting crest
hexed pecan
long scarab
#

ah ty

long scarab
#

and i can't tell why

green creek
#

I need to execute a thread to do some calculations asynchronously on a lot of data in my project once, so obviously I will use the Unity Job system. I also don't know from the beginning how much data I will need to store in the end result. I'm new with jobs and I'm wondering, is it a bad idea to use linked lists to store my data and save on memory? Is a linked list of native arrays containing the data a better idea instead?

hexed pecan
#

@long scarab

long scarab
hexed pecan
#

Do the other objects have colliders?

rigid island
#

which one is the colliders

long scarab
#

yup

hexed pecan
#

And the colliders are not triggers?

long scarab
long scarab
rigid island
long scarab
long scarab
hexed pecan
rigid island
#

I think they do

#

depends what they have on QueryTriggerInteraction settings

hexed pecan
#

See querytriggerinteraction parameter in the raycast

#

Or the global Physics.queriesHitTriggers bool

hexed pecan
long scarab
hexed pecan
#

Not there at least

rigid island
hexed pecan
#

Ok but why are you showing me the docs

rigid island
#

my bad replied wrong person

hexed pecan
#

Ah ok

rigid island
long scarab
# rigid island also where did you put Debug.Log collider
private void checkInteractable()
    {
        Ray interactRay = new Ray(Hand.transform.position, Hand.transform.forward);
        Debug.DrawLine(Hand.transform.position, Hand.transform.position + Hand.transform.forward * InteractRange, Color.red, 2f);
        if(Physics.Raycast(interactRay, out RaycastHit hitInfo, InteractRange))
        {
            if(hitInfo.collider.gameObject.TryGetComponent(out Interactable interactableObject))
            {
                Debug.Log(hitInfo.collider.name);
                InteractionTarget = interactableObject;
                InteractionTarget.ShowInteractButton();
                Debug.Log("Interaction available");
            }
        }
    }```
hexed pecan
#

Been ages since I started a fresh project

rigid island
#

should've been before If statement

#

if(Physics.Raycast(interactRay, out RaycastHit hitInfo, InteractRange))
{
Debug.Log(hitInfo.collider.name);

long scarab
#

ahh to see if it hits anything at all

rigid island
#

bingo

#

it might be hitting itself or something else entirely

elder zenith
#

Hi, is there any way to change the cursor to some default OS value?

I want to have buttons and input fields that change the cursor to the operating system's default "pointed finger" and "i-beam" respectively

From what I can see you can change the cursor through Cursor.SetCursor() but is there any way to use system default specifically?

hexed pecan
#

Or its hitting a child collider

long scarab
#

omfg

long scarab
#

it was hitting the player weapon

rigid island
#

ah ye Osmal got it

hexed pecan
#

No u

long scarab
#

so then does a raycast stop immediately once it hits anything?

#

or can a single ray detect multiple objects

rigid island
rigid island
long scarab
rigid island
#

ie anything player layer

long scarab
#

just curious

rigid island
elder zenith
#

Changing cursor from OS default selection

long scarab
#

which is odd since it did when i cast the ray from a different object

rigid island
long scarab
#

that stem is the collider its hitting now

rigid island
#

is the arm ever going to tilt up ?

#

otherwise you might need to make that the hitzone no? not sure how your thing works

long scarab
#

atm it doesn't

#

the group i have working on it wants gravity similar to super mario galaxy, so the player kinda normalizes their position based on the surface under them

#

probably will add aiming up/down in the future

rigid island
#

yea or you can do some type of autoaim for ray for now

long scarab
rigid island
long scarab
rigid island
long scarab
#

the script sits on the parent gameobject

#

do children carry references?

long scarab
rigid island
long scarab
#

i see

#

i might try that if i can't get this way to work neatly

long scarab
rigid island
long scarab
#

ah perfect

#

@hexed pecan @rigid island tysm, finally got it working

#

time to just make it look pretty

stoic ledge
#

How can one exclude libraries from build in a safe way? (To avoid "The type or namespace name X could not be found")
I excluded certain server-only things from client, but an android build crashes with "The type or namespace name X could not be found" exception (I don't use the components, that use the excluded libraries on the client).

In editor, everything runs just fine.

lusty dune
#

using UnityEngine;

public class SimpleFloating : MonoBehaviour
{
    public static bool movePos = true;
    public Vector3 posAmplitude = Vector3.one;
    public Vector3 posSpeed = Vector3.one;

    private Vector3 origPos;

    private float startMoveOffset;

    void Awake()
    {
        origPos = transform.position;

        startMoveOffset = Random.Range(0f, 540f);
    }

    void Update()
    {
        if (movePos)
        {
            transform.position = origPos;

            Vector3 pos;
            pos.x = origPos.x + posAmplitude.x * Mathf.Sin(posSpeed.x * Time.time + startMoveOffset);
            pos.y = origPos.y + posAmplitude.y * Mathf.Sin(posSpeed.y * Time.time + startMoveOffset);
            pos.z = origPos.z + posAmplitude.z * Mathf.Sin(posSpeed.z * Time.time + startMoveOffset);
            transform.position = pos;
        }

        if (!movePos)
        {
            origPos = transform.position;
        }
    }
}

So, I have this code.. i reference this script in another script and whenever i want to pause game, i put animPos = false (because i dont want to pause some animations)... But whenever i resume game by making animPos = true the gameObject position is reset... How do i stop the resetting ?

drifting crest
hexed pecan
#

You didnt show anything related to that

lusty dune
#

what is the best way to pause a math function?

drifting crest
hexed pecan
#

If it is a VR specific thing the I have no clue

hexed pecan
#

Not sure what you mean tbh

drifting crest
lusty dune
drifting crest
hexed pecan
#

I saw you ask earlier but I couldnt figure out what it all means

latent latch
#

that's the only thing I can think of unless you're changing values elsewhere

deft timber
#

there is also Time.realtimeSinceStartup which isn't, it's real time in seconds

hexed pecan
#

Thats for editor, but there is Time.unscaledTime

craggy veldt
#

it's runtime api

#

the editor one is this one EditorApplication.timeSinceStartup

latent latch
#

well, if Time.time is affected, then I guess the sin func should just continue on from where it left off so that was my guess

craggy veldt
#

their question has nothing to do with timescale I think

thick iron
#

hello, i have a button in a scroll rect and when i try to press it the onClick event is not firing. what can i do? i tried to change drag threshold of event system but it doesnt work

latent latch
#

make sure it's a raycast target, and if you're using canvas groups that 'blocks raycast' is selected

thick iron
#

btw when i remove scroll rect the button works

latent latch
#

could be blocked by another UI component and stuff like that. Alpha values will even block raycasts if there exists a UI element

thick iron
#

yeah.. i think that it's blocked by the scroll event of the scroll rect.. idk

#

but when i disable scroll rect component

#

it works

#

(my button is in the 'content' parent from the viewport of scroll view)

hexed pecan
latent latch
#

not too sure of the hierarchy but try setting the button* to the lowest of the UI elements

#

below the scroll rect, or even a child of it

thick iron
#

crafting slot is the button

#

yeah, the thing is that i want to be in this location because if i will have more buttons i want to scroll between them..

#

i can't move it from 'content'

tender haven
#

i made this simple sensitivity thing and it works but when i exit the game it doesnt save it how do i make it save?

latent latch
# thick iron

Looks fine to me, as far as the hierarchy is set up. So, I could only think that something's not configured correctly.

delicate olive
tender haven
#

ok

delicate olive
# tender haven ok

If you want to use playerprefs, a high level overview of what you should do is

  1. when you want to change the sensitivity, save it to the playerprefs by using "PlayerPrefs.SetFloat("sensitivity", sens)"
  2. after the player loads into the game, to get the sensitivity from the saved setting, you use "PlayerPrefs.GetFloat("sensitivity")" and set the return value of it to the "Sensitivity" variable/property you already have
#

You can imagine the playerprefs as like a storage where you can store and retrieve data (in this case the value of the sensitivity)

lean sail
# tender haven ok

You should just save to file (json or whatever format you want). Once you start needing to save other things, playerprefs wont suffice and will be a pain to work with.
There are many tutorials for json save systems online

delicate olive
#

So it depends on the scope of the game

#

And whether or not they're willing to learn more complex stuff

lean sail
#

Json is not complex by any means

#

It can be as simple as like 5 lines of code

dusk apex
#

I agree with bawsi. Player pref is sort of interesting in how easy it is but because it can annoyingly fill your registry up on Windows with garbage, it's limited types and whatnot, you're better off trying to get a simple generic json or file-read/write setup. I'd give playerpref more attention if storage location was optional.. Other than that, the name implies it's for configuration - which is valid in this case (it just unfortunately floods the Windows register while at it notlikethis )

delicate olive
#

If they anticipate a scalable system with many more settings to come, then JSON is by all means the right path to take

delicate olive
deft timber
#

you perhaps mistaken it with EditorApplication.timeSinceStartup

dusk apex
lean sail
dusk apex
#

They really ought to just let devs choose/edit the file location for Player Pref

thick iron
delicate olive
tender haven
#

should i make my player a singleton

delicate olive
#

I would make it a singleton but some people don't like the pattern so

tender haven
#

ill try making it and see if its ok

delicate olive
#

I think it'll be fine as long as it's not overused everywhere

delicate olive
#

Like when you have 20+ singletons then it's a problem in the architecture of your game

thick iron
#

if i remove mask component from scroll view the button works...

delicate olive
# thick iron no

That means that either another UI element is blocking the button, or the button isn't raycastable somehow

delicate olive
thick iron
#

yeah

#

the buttons only works when i remove the scroll rect component from scrollview or when i remove the mask component

#

but i want to keep them

#

xd

#

i tried to change drag threshold of the event system

#

still not works

delicate olive
#

That's weird, when I use scrollrects they always work just fine with all kinds of raycastable stuff

delicate olive
thick iron
#

probably

#

but i tried

delicate olive
#

Have you tried creating another scroll rect and see if it works there? then if it does you just see the diff between the two and that could help troubleshoot the problem

thick iron
#

no

#

let me try

#

thanks

delicate olive
#

okay it's a good idea

thick iron
#

yeah.. it works if i make an empty scroll rect with button

#

thanks for the idea

#

i will try to find the differences

#

and solve

delicate olive
#

But great if you got it working

thick iron
#

yeah

tame spruce
#

Hello all. I'm building a .unitypackage and it comes with a few scenes. I want to have a "Scene Switcher" where I list all my scenes and switch to them upon clicking a button. But in order to use SceneManager.LoadScene(sceneNameToLoad) the scenes should be in the Build Settings

Now, I can write an editor script to add my scenes to the build settings of whoever downloads my package but that's intrusive and I don't want to do that. Is there not another way?

I also am aware that I can use string scenePath = AssetDatabase.GetAssetPath(sceneAsset) but that only works in the editor...

delicate olive
tame spruce
delicate olive
#

Without the complexity of assigning them to the build options

tame spruce
#

Ah, so your suggestion is to ditch the "menu" scene entirely?

delicate olive
delicate olive
tame spruce
# delicate olive So it's like a root scene that contains buttons to other scenes?

Correct. Here's what I prepared (yet to test) - not sure how valid this is:

    public class SceneSwitcher : MonoBehaviour
    {
        [SerializeField] private Object sceneAsset;
        [SerializeField] private string sceneNameInBuild;

        public void ChangeScene()
        {
#if UNITY_EDITOR
            if (sceneAsset == null)
            {
                return;
            }

            var scenePath = AssetDatabase.GetAssetPath(sceneAsset);
            sceneNameInBuild = System.IO.Path.GetFileNameWithoutExtension(scenePath);

            // Check if the scene is in the build settings
            var scenes = EditorBuildSettings.scenes;
            if (scenes.Any(s => s.path == scenePath))
            {
                SceneManager.LoadScene(sceneNameInBuild);
            }
            else
            {
                Debug.LogError("The scene " + sceneNameInBuild + " is not in the build settings.");
            }
#else
        if (!string.IsNullOrEmpty(sceneNameInBuild))
        {
            if (SceneManager.GetSceneByName(sceneNameInBuild).IsValid())
            {
                SceneManager.LoadScene(sceneNameInBuild);
            }
            else
            {
                Debug.LogError("The scene " + sceneNameInBuild + " cannot be found. Make sure it is added to the build settings.");
            }
        }
        else
        {
            Debug.LogError("No scene name specified for the runtime build.");
        }
#endif
        }
    }

#

I'll be filling in these references before releasing

delicate olive
#

But you could also try the intrusive approach, so add the scenes to the list and somehow delete them after they are done using them..?

tame spruce
# delicate olive But you could also try the intrusive approach, so add the scenes to the list and...

Yeah, and I guess that would look something like this:

        // Fetch current list of scenes in the Build Settings
        var originalScenes = EditorBuildSettings.scenes;
        var newScenesList = new System.Collections.Generic.List<EditorBuildSettingsScene>(originalScenes);

        // Add new scenes to the Build Settings
        foreach (var scenePath in scenePathsToAdd)
        {
            if (!newScenesList.Exists(scene => scene.path == scenePath))
            {
                newScenesList.Add(new EditorBuildSettingsScene(scenePath, true));
            }
        }

        // Apply the changes back to the Build Settings
        EditorBuildSettings.scenes = newScenesList.ToArray();

I really don't like this though!

delicate olive
#

But maybe you don't even need to add the scenes to the build options

#

I just looked at the documentation for SceneManager.LoadScene and it seems like you can use the path directly for changing scenes

#

And the way you could get the paths at runtime is have a config scriptableobject, and have a main handler or something for the scenes. Then when the main handler asset is loaded, you get the full paths of the sample scenes, cache them to the SO and then access the SO at runtime

tame spruce
#

Hmm, yes I see

delicate olive
#

But idk I may just be overthinking here

tame spruce
#

I think so hahah. Just didn't expect this to be an issue until I prepared the UI for the main menu scene 😆

tame spruce
#

I guess I'll simply use SceneManager.LoadScene(sceneNameToLoad); and let people manually add scenes. Thankfully there aren't that many.

#

Thanks for your input 👍

delicate olive
delicate olive
drifting crest
#

hey I am rotating a steer gameobject when I interact with it but when I leave the interaction I want the steering to stop rotating so I am trying to set back to intial rotation but it isn't stop rotating

delicate olive
delicate olive
# drifting crest yes

In that case, before you set the rotation to the initial rotation, you should reset the rb's rotation velocity

deft timber
#

this is a code related channel

drifting crest
delicate olive
drifting crest
# delicate olive Show the code

public void StopSteer() {

wheelRigidbody.velocity = intialwheelVelocity;
steeringWheel.localEulerAngles = intialWheelrotation;
// RotateShip(0);
Debug.Log("Stop Steered");

}

drifting crest
# delicate olive Show the code

private void Start()
{
intialwheelVelocity = wheelRigidbody.velocity;
intialWheelrotation = steeringWheel.localEulerAngles;
}

This is the code in start

deft timber
#

!code

tawny elkBOT
delicate olive
knotty sun
delicate olive
#

Sorry for the bad formatting lol

delicate olive
knotty sun
#

who is talking about velocity?. He is using transform rotation when he should be using rigidbody rotation

delicate olive
knotty sun
#

intialWheelrotation = steeringWheel.localEulerAngles; ????????????

#

steeringWheel.localEulerAngles = intialWheelrotation;

delicate olive
deft timber
#

why is he using localEularAngles at all

#

when he is using Rigidbody component

#

it's like you'd modify transform.position when you have Rigidbody

#

non sense

delicate olive
knotty sun
#

no

delicate olive
#

Modifying the transform pos with rb

deft timber
#

sure you can but why add rb then?

#

if you won't use it properly?

#

it's like having a car

#

but not driving it

#

instead you push it with your arms all the way

#

will that work? yes

#

is that correct? no

delicate olive
#

Well, one scenario I can think of is when you need a kinematic rb (a damageable for example) in order to register bullets which don't have rb

#

But then again bullets should be the ones with rb so idk

drifting crest
knotty sun
#

basically you should never mix transform manipulation and rigidbody manipulation, use one or the other

deft timber
delicate olive
deft timber
#

you just reset the localEulerAngles

#

the velocity is not resetted

drifting crest
#

I wanted to rotate the ship as well according to the steering and that's why used eulerangles ig coz i thought that's how it's done

deft timber
#

just do Vector3.zero

#

if you want to zero it

drifting crest
#

okay lemme try

deft timber
#

then make sure you are not overriding it anywhere else

#

because that is probably the case

#

you set it to zero, then you set it to some value somewhere else

trim schooner
#

Can a cursor sprite colour be changed via code? Or do you have to swap out different sprites?

deft timber