#archived-code-general

1 messages · Page 370 of 1

spare dome
#

please add 3 more ` at the end of your sentence

#
//code
warm badger
spare dome
#

dont be

#

you're fine

ocean hollow
#

so whats stopping you with this?

warm badger
spare dome
#

well just making it a corountine doesnt automatically make it wait for a set amount of seconds

warm badger
soft shard
#

Currently, your logic is going to start a new coroutine for every frame that dist <= distance, which will most likely be far more than just once, this could also be throwing off your testing

warm badger
spare dome
mossy snow
soft shard
#

Yup, using a timer could be a good option, or a bool that the coroutine controls could be another option as well

spare dome
#

toggling a boolean could work

#

as well

normal ingot
#

What usually causes stack overflow in unity and how can i fix it?

Edit: I restarted the editor and my problem is gone : )

vital hamlet
#

how are MLAgenets so fast

#

what model do they use

cosmic rain
vital hamlet
#

sorry i mean the training is really fast. When i try to make something like it (not for unity) its not even close to updating once per frame

#

im using keras

cosmic rain
ember stag
#

Hi everybody. Not sure if this is the correct channel for this, but I’m having an issue with switching quality level that causes Unity to crash. I have two scenes: a 3D scene and a 2D scene. The 3D scene is the main one. It seems if the game switches from the 3D scene to the 2D scene and I exit play mode, Unity crashes.

I attached screenshots of the errors.

I’ve got a ‘3D’ quality level and a ‘2D’ one.
Code:

    private IEnumerator TransitionToCardScene()
    {
        SaveGameState();

        QualitySettings.SetQualityLevel(cardSceneQualityIndex, false);
        SceneManager.LoadScene("CardScene", LoadSceneMode.Single);
        yield return null;
    }
        QualitySettings.SetQualityLevel(boardSceneQualityIndex, false);
        SceneManager.LoadScene("BoardScene", LoadSceneMode.Single);
        yield return null;
    private void ReturnToBoardScene(bool answeredCorrectly)
    {
        StartCoroutine(ReturnToBoardSceneCoroutine(answeredCorrectly));
    }

Any help would be much appreciated!

#

I’m using URP. Unity v2022.3

cosmic rain
ember stag
#

Yes, I couldn’t find any answers, though. I couldn’t find anything related to changing the quality level

#

I’ll keep trying to troubleshoot it, but if anyone has any idea on how to fix this, I’d really appreciate it

cosmic rain
cosmic rain
ember stag
#

I created my project with the Universal 2D v2.1.2 preset. The default URP asset file is used for the 2D quality. For the 3D quality I use URP_DungeonsLite.asset supplied with the asset pack for the 3D scene I’m using: https://assetstore.unity.com/packages/3d/environments/dungeons/low-poly-dungeons-lite-177937 It uses the supplied URP_DungeonsLite_Renderer.asset.

I’m guessing maybe Unity isn’t handling switching between these two very well. However, it only happens if I switch from the 3D scene to the 2D scene and exist play mode. If I exit play mode in the 3D scene, it doesn’t cause the crash or errors.

I’m not sure how to copy the stacktrace because whenever this happens, Unity crashes, and I have to force-quit.

#

In Quality settings, ‘2D’ uses the default URP file, and ‘3D’ uses the Low Poly Dungeons Lite URP file.

cosmic rain
#

I’m not sure how to copy the stacktrace because whenever this happens, Unity crashes, and I have to force-quit.
Then how were you able to take a screenshot?
Regardless, you can get the stacktrace in the !logs

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

fair moss
ember stag
cosmic rain
ember stag
#

Thanks for the help, and I hope I’ll be able to fix this. It’s likely just an editor issue, but IDK. I’ll try posting it on the Unity forums perhaps

#

It’s some issue with changing the quality level.

#

At least I believe so

cosmic rain
ember stag
#

Okay, I’ll give that a try. Thank you!

wary veldt
#

Is there a way to specify fields required to be set in the inspector? To make unity warn or even prevent starting the game until you set the value

soft shard
muted schooner
#

Hi folk! I'm working on a project that is a kind of Vampire Survivors. I'm trying to optimize it to work with as much entities as possible - though I saw a strange performance leech in the profiler in Deep Profile mode.

public bool TargetInRange(out Vector2 direction, out float distance) {
        direction = YKUtility.GetDirection(ownedObject.transform.position, objectToFollow.transform.position);
        distance = Vector2.Distance(ownedObject.transform.position, objectToFollow.transform.position);
        return distance < reachDistance;
    }
#

have you got any idea about why this function is heavy? (400x entities, 22.7% total )

#

I think Unity is not caching transforms at all, and every time I call .transform it spends a lot of effort on it

#

should I just put the transform into a variable and let it consume RAM instead?

#

any information is appreciated and going to be helpful, thanks

mossy snow
#

you waste a lot of time fetching transform and position repeatedly. You waste more time on getting world position twice for each object, which is more expensive the deeper the transform hierarchy is. You waste a little time using distance instead of squared distance. You waste a bit of time casting Vector3 to Vector2 twice. This could be a good candidate to jobify btw, look at TransformAccessArray

muted schooner
#

that was useful, thanks! I'll give a look at c# jobs, looks like a good idea

muted schooner
cosmic rain
muted schooner
#

I'll give it a shot, though it turns out the main problem was that my RareTick was getting triggered EACH tick..

#

I was wondering why the AI movement was so smooth.. lol

maiden fractal
#

The final performance on build might also be much better on build compared to editor especially if IL2CPP is used

muted schooner
#

yeah definitely.. also deep profiling approximately halves the performance

gray mural
#

Having an array, what is the best way to initialize it without an error thrown?

[SerializeField, HideInInspector] private Object[] _undoObjects;

// Awake
_undoObjects = new Object[]
{
    gameObject,
    numberText.gameObject,
    difficultyText.gameObject
};
cosmic rain
gray mural
cosmic rain
gray mural
jolly pelican
#

hey, could anyone help with accessing the new input system within a state machine? i want to assign a different function to an input action based on the player state and i'm not sure how to go about it

vagrant agate
woven dome
#

hi there
does anybody know why animator.SetFloat("Speed", value); wouldn't work (resulting in animator.GetFloat("Speed") = 0) even though "Speed" is guaranteed to be in the animator?

cosmic rain
cosmic rain
#

Assuming you're actually using the correct signature. Otherwise there would be a compile error.

rigid island
#

how did you verify what value is ?

woven dome
#

logging, just before

rigid island
#

could be something setting it right after

#

we would prob need to see full script

woven dome
#
animator.SetFloat ( AnimatorParams.Speed, _rigidbody.velocity.magnitude );
Debug.Log ($"velocity: {_rigidbody.velocity}, magnitude: {_rigidbody.velocity.magnitude}, prop: {animator.GetFloat ( AnimatorParams.Speed )}" );

this shows prop: 0

pearl burrow
#

Hi. If i have OnApplicationPause() on many script, is the execution order dictated by the settings i've set in the engine?

#

i cant seems to find an answer anywhere on the docs or over the web

cosmic rain
cosmic rain
rigid island
#

oh didnt see it myb

woven dome
#

there is only one, and I do in the sample above

woven dome
cosmic rain
pearl burrow
#

ill give a try

cosmic rain
#

Test it and see for yourself

pearl burrow
#

ok i tried with OnApplicationQuit() and it didnt work

hexed sorrel
#

I'm trying to make something where light from an event travels outwards in a sphere and can be detected by various detectors; my idea is to give the light from the event a trigger sphere collider with an expanding radius, and then when it touches the detector's collider the detector does something. But I'm wondering if there's a better way to do it - there may be lots of detectors and I don't want them checking collisions with one another or similar

cosmic rain
cosmic rain
elfin tree
#

How can I make a vertical layout group put the elements above (bottom to top) instead of the usual top to bottom?

cosmic rain
#

Don't crosspost.

elfin tree
# elfin tree How can I make a vertical layout group put the elements above (bottom to top) in...
paper tree
#

Is there in unity / C# any common patter of storing safe/encrypted data localy?

cosmic rain
paper tree
#

Sure, i just try to rewrite my storing data for game from XML to somehow secured like encryption JSON

The main goal is to prevent easy editing like text files or coppy from 1 device to another and run app with copied/ stealed data (they are not sensitive datas like Rodo or passwords etc... just some game saves)

opaque vortex
#

I am writing the code for my game, and I am working with protobuf to transfer data. Should I keep trying to learn protobuf despite my issues with it, or go for easier JSON for now?

#

I will end up needing to use protobuf in the finished project, the amount of byte data and other user related information will give me no choice in my finished project.

carmine osprey
#

Does anyone know how to fix my pitch? when it gets too high it sounds wrong. I have a audio clip for each note in the 4th octive. It could also just be my audioclips that sound wierd

    public void PlayNoteClip(int octave, int note, int velocity)
    {
        if (note < 0 || note >= keys.Length)
        {
            Debug.LogWarning("Invalid note index: " + note);
            return;
        }
        var obj = GameObject.Instantiate(keys[note].gameObject);
        obj.transform.position = new Vector3(0, 0, 0);
        var audio = obj.GetComponent<AudioSource>();
        audio.volume = velocity / 127f;
        audio.pitch = Mathf.Pow(2, (octave - 4));
        audio.Play();
        if (!obj.activeSelf) { return; }
        GameObject.Destroy(obj, audio.clip.length);
    }
oblique spoke
paper tree
#

but isn't in reverse it unsafe to read binary code as it may be attacked from 3'rd party programs

oblique spoke
#

I believe it comes more down to deserializer design (and how you use it) than the format.

paper tree
#

Yeah i readed that decoding binary data can be executed as well so its not good idea at all to use it from local files

simple egret
#

The vulnerability comes with BinaryFormatter, if you are not using that, you should be safe

#

There are other binary serializers, and if you want to roll your own file format, there's BinaryReader and BinaryWriter

winged sphinx
#

Is there any way to open a second window in an application?

swift falcon
#

I am trying to have the camera drag using the right mouse button, but it just refuses to budge when I DO click the right mouse button

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

public class Sims3Camera : MonoBehaviour
{
    public TMP_Text data;
    public TMP_Text data2;
    private Vector3 point;
    private bool pandrag;
    // Start is called before the first frame update
    void Awake()
    {
        point = gameObject.transform.position;
    }
    // Update is called once per frame
    void Update()
    {
        

        float xPos = Input.GetAxis("Mouse X");
        float yPos = Input.GetAxis("Mouse Y");

        //data.text = xPos.ToString() + yPos.ToString();

        pandrag = Input.GetMouseButton(1);
        if (pandrag)
        {
            point = new Vector3(point.x + xPos * Time.deltaTime, point.y, point.z + yPos * Time.deltaTime);
            data.text = point.x.ToString();
            data2.text = point.z.ToString();
        }
        else
        {
            //data.text = pandrag.ToString();
        }
    }
}
mellow sigil
#

There's nothing there that would move anything

outer plinth
#

Hey, i am struggling with this particular Orientation problem, I want the character's Up and Forward axis to return to normal but also apply the additional rotation, this code seems to do this but the additionalRotation is applied in the wrong direction

https://cdn.discordapp.com/attachments/763495187787677697/1284137133531070515/2024-09-13_14-02-03.mov?ex=66e82c66&is=66e6dae6&hm=e5d816e3c9871f7fac348a4c13cec7ecea5dc4d18f95628d572e14af50d6bb9e&

(https://pastebin.com/Nkj3GX4x)

#

Is there a better way to combine those two FromToRotations and another quaternion?

#

And/or is there a standard practice for combining more than 2 Quaternions that I am missing?

swift falcon
mellow sigil
#

I haven't done anything like that with Cinemachine. You might want to ask in #🎥┃cinemachine about it

winged sphinx
oblique spoke
knotty sun
oblique spoke
woven dome
# cosmic rain Take a screenshot of the parameter in the animator
animator.SetFloat ( AnimatorParams.Speed, _rigidbody.velocity.magnitude );
Debug.Log (
    $"velocity: {_rigidbody.velocity}, " +
    $"magnitude: {_rigidbody.velocity.magnitude}, " +
    $"prop: {animator.GetFloat ( AnimatorParams.Speed )}"
);
private static class AnimatorParams {
   public static readonly int Speed = Animator.StringToHash ( "Speed" );
}
#

additionally

elfin tree
#

How come this code directly modifies the prefab, even if it seems properly instantiated?

 [SerializeField] private DirectoryData rootDirectory;
        [SerializeField] private GameObject buildMenuElementAsset;

        private BuildMenuFolderController _rootElement;
        
        public void Start() {
            var folderGo = Instantiate(buildMenuElementAsset);
            _rootElement = folderGo.GetComponent<BuildMenuFolderController>();
            _rootElement.transform.SetParent(transform);
            _rootElement.InitializeRootFolder();
            
            BuildFolders();
            //PopulateFolders();
        }

(...)

        public void InitializeRootFolder() {
            Debug.Log("[Build Menu] Initializing Root Folder...");
            _isAlwaysExpanded = true;
            _expandDirection = ExpandDirection.RIGHT;
           
            InitializeExpansion();
            
            gameObject.name = "Directory - Root (Folder)";
            _layoutGroup.transform.localPosition = Vector3.zero;
            _layoutGroup.gameObject.name = "Directory - Root (Content)";
            _layoutGroup.gameObject.SetActive(true);
        }

inner shuttle
#

instead of using a new Vector3 is there a more efficient way of altering one axis like this?

playerCam.transform.localPosition = new Vector3(0, 0.1f, 0);

worn crystal
inner shuttle
#

oh yeah i suppose

simple egret
#

(this does not alter one axis btw, it reassigns a whole new vector)

inner shuttle
#

localPosition.y?

#

to alter 1

simple egret
#

Altering one axis would be:

Vector3 v = playerCam.transform.localPosition;
v.y = 0.1f;
playerCam.transform.localPosition = v;
inner shuttle
#

alright cheers 👍

west lotus
#

But to answer your question, no there is not a more efficient way since vector is a value type

#

But it’s pretty efficient to allocate new ones

gray mural
#

And since it's a property

rigid island
inner shuttle
#

oh lol okay thanks

elfin tree
#

yeah, it was that

#

what a weird behavior

deep stirrup
#

Is it possible to detect when Character Controller uses step offset to climb the surface?

rigid island
#

not likely as that happens C++ side

deep stirrup
#

😦

rigid island
deep stirrup
#

🙁

elfin tree
#

What's the best way to extend the "hitbox" of a ui element?

rigid island
elfin tree
#

negative means outwards for some reason

rigid island
#

oh for square ig is easier?

#

I was wondering if the image component at 0 opacity would still work with alphaHitTestMinimumThreshold
since it states it grabs it from the actual sprite texture and not the renderer
(I guess ill just testit)

elfin tree
rigid island
#

yeah I was thinking of a different shape than square 👍

#

good enuf 😅

elfin tree
#

ohh, yeah if you have a more complex shape

#

and 0 opacity idk, i think i needed to use 1 opacity once

#

but i'm not sure if iirc

#

but yeah you can probably use alphahittest to fix that

#

lmk if u end up testing it

rigid island
#

will do!

rigid island
#

so you can technically have invisible images any shape you want above it as hitbox to trigger whatever you want

swift falcon
#
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class BulletController : MonoBehaviour
{
    [SerializeField] private float flyTime = 5f;
    [SerializeField] private float flySpeed = 10f;

    

    void Start()
    {
        var rb = GetComponent<Rigidbody>();
        rb.velocity = transform.forward * flySpeed;
        Destroy(gameObject, flyTime);
    }
}

Error:Skipped updating the transform of this Rigidbody because its components are infinite. Could you have applied infinite forces, acceleration or set huge velocity?

void ShootPlayer()
    {
        Instantiate(bulletPrefab);
    }

Getting this error when bullet gets instantiated onto the scene

rigid island
#

its telling you exactly whats wrong

#

Could you have applied infinite forces, acceleration or set huge velocity?

#

also check colliders when spwaned, make sure its not stuck somewhere or huge

swift falcon
#

Forgot to say that I'm not applying an infinite force, acceleration or huge velocity. I'm only doing this rb.velocity = transform.forward * flySpeed;

rigid island
#

I see that

#

the computer says otherwise though, I tend to trust the results of the computer

#

have you tried debugging the values before passing to it ?

swift falcon
#

I'll try to. When it's an error like this I tend not to trust unity at all

rigid island
#

var myVel = transform.forward * flySpeed;
rb.velocity = myVel
Debug.Log($"{this} myVel is {myVel} and current rb.vel is {rb.velocity} ")

rigid island
#

when things dont work as expected is *usually * the users fault somewhere, not the computer

lean sail
swift falcon
#

no that's not the case there are no large values assigned on my end

rigid island
#

what you see here is not whats happening in the game so 🤷‍♂️

#

also where is the collider

swift falcon
#

it's a sphere collider

rigid island
#

lol where not what

swift falcon
#

idk what you mean by where but it's on the bullet

Edit: I was being stupid I forgot to destroy the game object after it collided

rigid island
swift falcon
#

ik i didn't show the full game object

rigid island
#

anyway I would suggest debug the runtime values

#

see whats actually happening in playmode

inner shuttle
#

learning wise, whats the best way of actually getting something out of tutorial code? i thought of commenting it for what i knew but i dont know if thatll make anything stick

storm wolf
#

Hey quick question on if I am doing this right...

//add crafted item to inventory
InvItemData cloneItemData = GameObject.Instantiate(recipe.result);
Inventory.AddItem(cloneItemData);

Would something like this work with scriptable objects? I am instantiating a copy of the SO before saving it for later is this correctly how to do this? Will this mess with the original at all?

mighty void
#

exists a channel for profiler theme?

quaint rock
storm wolf
#

perfect thanks

quaint rock
#

i do it all over my code base, got a asset that represents defaults of something or inputs then i make in memory instances to work on

storm wolf
#

yeah lol i had the same thoughts

mighty void
#

i dont know why my fixed update takes 120 ms :T

quaint rock
storm wolf
#

gotcha

proven scroll
#

Can someone help me with figuring out how to pause a time line while using a dialogue box so it only continues after they hit the next button on the dialogue box please

quaint rock
#

should be just a matter of adjusting Time.timeScale as needed and using events to handle anything else that needs to know about it

mighty void
#

just stop the application and continues when the player clicks the dialogue box

proven scroll
#

ima little unsure as to where i would put this code and exactly how, ill send my dialogue box scripts

#

or would i just make a whole new script for this?

mighty void
proven scroll
mighty void
#

so you can do it or

#

make it works with your custom event

proven scroll
#

Okay so make a new script called (PauseTimeline)
i would need a reference to the timeline gameobject and the dialogur box object?

mighty void
#

make a new script, call it whatever you want

#

implements IPointerEvents

proven scroll
#

im sorry im new to coding and very unsure on how to do this.. :/

mighty void
#

dont worry

#

implements PointerEvents

#

when you show your dialogue box stop the timeline

#

in that script where you show your dialogue box stop the timeline

#

in this new script, you have to implements ipointervents

#

and restart or continue your timeline

#

you dont need any reference :T

proven scroll
#

Okay
When try to implement IpointerEvent just keeps red line, i know i need a function for it right?

somber nacelle
#

yes, you need to implement the interface's members. you can also use the quick actions to do it automatically

proven scroll
#

when i do that theres like a bunch of functions it makes

#

Do I need all of these?

quaint rock
#

you sure you want IPointerEvent

#

assuming you want like IPointerClickHandler or something else

proven scroll
#

So just this then?

quaint rock
#

yeah

#

then do what ever you need to do in the OnPointerClick method

mighty void
proven scroll
#

Would I just use an IEnumarator with the waitforseconds?

mighty void
#

using IPointerDownHandler, IPointerUpHandler you can check if you want specific clicks

#

right click, left click, middle click

mighty void
proven scroll
#

nvm guess that wouldnt do cause it would just waitfor some seconds then continue,

#

Honestly I havent no clue what to put here.... ngl 😦

mighty void
#

do you wanna wait seconds and wait for the player click?

#

or continue the game in the next seconds when the player makes click?

proven scroll
#

I want it to pause the time but still have players idle animation playing, but dont want the timeline to keep going unitil the dialogue box is closed

#

I thought it stayed on but it only stayed because the timeline time was over

#

I wanna wait seconds and wait for the player click through th edialogue then continue after dialogue is over

ruby dirge
#

Hello i don't know if this is the right channel to post this in but im trying to setup Vivox and when im reading the docs they say that i need a Dedicated server to authorize the access token for the users?

#

becuse my game is going to use p2p

mighty void
proven scroll
#

so it would have to go by counting the clicks?

golden garnet
#

Trying to get a NavMeshAgent to take knockback, but it won't leave the NavMesh area. How do I get the NavMeshAgent to stop sticking to it?

rigid island
#

it takes over your transform

golden garnet
#

👌

lean sail
cosmic rain
storm wolf
#

Loading issue inventory system

plucky inlet
#

Hey everyone, I am currently trying to get the locationservice to work properly in unity 6 and on ios/editor/visionos. Somehow, everytime I start the locationservice like in the sample method here, its just crashing the app/unity editor

        private async Awaitable VisionOSLocation()
        {
            locationService.Start();

            Dispatcher.Enqueue(() => Debug.Log($"Status: " + locationService.status, Instance));
            await Awaitable.MainThreadAsync();

            await Task.Delay(10000);

            Dispatcher.Enqueue(() => Debug.Log($"Status: " + locationService.status, Instance));
            await Awaitable.MainThreadAsync();
        }
#

The error happens right after start() firing Status.initializing on the next line

thick terrace
#

if you're expecting the function passed to Enqueue to be called from a different thread, you probably don't want to be passing in a unity object as the context for the log message

plucky inlet
thick terrace
#

are you calling this method from the main thread? again, probably not causing a crash, but i think at least one of those MainThreadAsync calls is doing nothing

plucky inlet
#

It is waiting for the mainthread but its being called from another backgroundthread

thick terrace
#

shouldn't LocationService.Start() be called from the main thread since it's a unity API?

plucky inlet
#

Usually I get an error on xcode when it should, but I also tested the start thing to be sure, its not the issue

plucky inlet
#

So starting from a background thread seems to kill it 100%. Starting it off the mainthread keeps the system running but its still stuck on initializing. If anyone had similar experiences with locationservices on mobile, let me know.

runic linden
#

If I have a function bool HasFoo() then you'd expect that function to check if foo exists. Is there a convention for "look for foo and create it if it does not exist yet"?

lean sail
runic linden
#

Yes thats what I ment

gray mural
# runic linden If I have a function `bool HasFoo()` then you'd expect that function to check if...
bool CreateFooIfNotFound();
bool CreateFooIfAbsent():
bool CreateFooIfLacking();
bool CreateFooIfMissing();
bool CreateFooIfNotPresent();

You might take the following methods into a consideration, but since they are pretty long, I would consider simplifying it with Try at the beginning:

/// <summary>
/// Creates foo if not found
/// </summary>
/// <returns>
/// True if foo is found
/// </returns>
bool TryCreateFoo();
runic linden
#

I tend to write out whole sentences sometimes trying to describe the function and was hoping that for this case some kind of convention exists. This is something that is needed regularly so I was hoping for some sort of standard. 😅 Probably overthinking this anyways lol.

#

Thank you both

compact perch
#

chatGPT can help with following naming conventions ;p

gray mural
stoic sluice
#

Has anyone tried using Steam's auto cloud feature for saving game data?

#

I'm scratching my head at what I'm doing wrong causing it to not sync files.

runic linden
#
T UpdateField<T>(string[] guid)
{
  if(guid.Length > 0)
  {
    string path = AssetDatabase.GUIDToAssetPath(guid[0]);
    return AssetDatabase.LoadAssetAtPath<T>(path);
  }
  else
  {
    return default(T);
  }
}```
How do I make this work? The compiler throws an error for return `AssetDatabase.LoadAssetAtPath<T>(path)` because just writing T there is not allowed. typeof(T) does also not work.
stoic sluice
#

You'll need to specify the type constraint probably

knotty sun
stoic sluice
#

Best to supply the compiler error

runic linden
gray mural
#

The method has to be modified as followed:

T UpdateField<T>(string[] guid) where T : UnityEngine.Object
gray mural
#

Make sure to always check the generic argument when using the method

runic linden
#

Not sure what you mean.

gray mural
#

Make sure you always check the type of the generic argument, which, in your case, was UnityEngine.Object

runic linden
#

You mean in the declaration of the method or before calling it in code?

gray mural
#

I mean hovering the method or entering its script

deep stirrup
#

I don't really know where to put this question, but what can lead to GPU Instances not working with light probes?

faint tree
#

spent the whole day trying to get mlagents going but i always get an error when i type this mlagents-learn

#

some python errors ;-/

somber nacelle
faint tree
#

oh thanks

#

ah its one of them rubbish question channels lol

stoic sluice
#

pfftt

#

he linked you to the more helpful channel

somber nacelle
faint tree
#

cheers..

stoic sluice
#

If someone here knew, they'd answer

#

If you're lucky enough for them to be around.

elfin tree
#

What does that circle GIzmo at the bottom of the collider mean?

#

I think it might be the GameObject position/transform

runic linden
lost night
#

I have a very specific problem: I want my player rigidbody object to not get pushed by specific rigidbody objects, but be able to be pushed by specific others. At first I used an kinematic rigidbody but that does not do the trick, as I now want to introduce an object that can push the player. (If you answer please ping me) thanks for any help

somber nacelle
# lost night I have a very specific problem: I want my player rigidbody object to not get pus...

if you want those objects to still collide but not affect each other but still be affected by other objects, then it is something that is kind of complicated. I know someone made an asset that can handle that for you, or you can ask them how they did it or even ask in #⚛️┃physics about how you could potentially set up interactions like that.
Here's that asset: https://discord.com/channels/489222168727519232/1247284826835517450

lost night
#

Thanks for the help! I now went with setting the mass of the I objects that should not push the player to 0 so they still push but with 0 force

frigid turtle
#

Hey guys, i face a weird thing with addressables. I add reference of a texture in a scene. Both texture and scene are part of a remote bundle. So they shouldn't be inside of a build. But build size is increased by 1Mb.

sudden lantern
#

Hi everyone. Does anyone know how to make the camera follow the player's movement direction? Like here in the video. Please don't say "use Cinemachine", I want to make my own fully controllable camera system. Thanks
(also for some reason the video doesn't load in Discord, so download it to watch)

leaden ice
#

You can make a fully controllable camera system with Cinemachine

vagrant blade
#

You should have some idea how you want to achieve if it, if you're so against using the proper method of doing this.

#

Such as, getting a point that is behind/above the player's facing direction (using some simple vector math) and then slerping the position of the camera to it.

leaden ice
#

But yeah it's just some relatively straightforward vector arithmetic

fading umbra
#

I need help with my weapon system, using new input system with invoke method and when I keep my mouse button pressed it wont shoot continuously only once. I use Action and invoke them by subscribing from another script. It seems fine but doesn't work as intended.

vagrant blade
#

The input system only tells you when something has been pressed, not held. You have to manage that yourself with a bool.

violet nymph
indigo tree
fading umbra
fading umbra
#

i knew

worn star
#

hi what are some scenarios where OOP can be used to improve code

#

for a 2d platformer

rigid island
#

thats literally C#

worn star
#

yeah isnt components just classes

rigid island
#

yes well Components are unity specific

#

so classes are Objects, etc..

rigid island
worn star
#

damn thanks man , cuz now that i got a little bit code , stuff is getting messed up

rigid island
fading umbra
# indigo tree Huh?

It worked, thanks. Now the animation for the gun shot is played once, I have a separate script for animations. Ill have to fix that.

rancid frost
#

I am manually creating shapes (in this case hexes) and using shaders to color them inorder to create textures.
What are some things I can do to make the map seamless? I want to remove the shape(hex) outlines

leaden ice
#

It owuld be easier to make a square tiling texture

rancid frost
#

That is a good point, But I need the shape (could be square or hex or triangle) because I need to be sure of the specific biome/data of that specific location

modern creek
rancid frost
#

thats not the problem, I have already done that

modern creek
#

What, perlin noise?

rancid frost
#

the problem is removing the hex outline from the map

modern creek
#

Your perlin noise generator will have to account for the coordinate of each tile, however - like, instead of a perlin noise function that's constrained to one hex, you'll have to broaden it so that any given pixel in the entire world belongs to the same contiguous noise function

rancid frost
#

ahh, I see

modern creek
#

Like I said.. it's not gonna be easy but I think it should be possible since the noise method doesn't really care how big/small the surface is.. but your coefficients will have to be a lot smaller and you might run into issues with floats on the shader if your world is large

#

alternatively you could lean into it and make your hexes have borders - like PB said, if you're just intending to make a smooth texture, you may as well use square based grids since .. you're trying to obscure the borders anyway, and the math'll be a lot easier

rancid frost
#

Right now, im doing something similar to that, but I think the problem is that thesame constant value is used to seed the noise

modern creek
#

yeah I dunno if I have the brain capacity to figure this out but I imagine you're going to need to have to calculate your noise value with a constant for "this tile" (id?) along with a constant for each of the adjacent tiles - such that the border along each of the 6 edges matches the inverted border of the adjacent hex

#

but I'm really shooting from the hip here.. that sounds hard

#

if you're looking for a smooth texture and using perlin noise, I'd probably just make a single square (or hex) and muck with the coefficients until you have a noise value that looks nice for the scale you're operating in

rancid frost
#

I see

#

The goal of this project is to create a realistic texture free map

modern creek
#

hm.. yeah.. it's an interesting problem tbh

rancid frost
modern creek
rancid frost
#

indeed and not 3d 🙂

modern creek
#

perlin noise for the hex type (at the world scale) and then perlin noise for the texture (at the hex scale)

rancid frost
#

lol, yea

#

at the texture scale, perlin noise is used,but its not seamless

#

I dont know why

modern creek
#

yeah I think you're gonna need to dream up a solution for making a perlin noise function for the texture of an individual hex have the world location as part of the input so that the textures between hexes is seamless

#

it's a pretty hard problem (to do in shaders) tbh - i think even if you get it working the issue is going to be float instability because your textures are gonna need to be so small (for a float, relative to your world size) that as you start getting far away from the origin your textures are gonna look more and more pixelated as the floats start resolving/rounding to the same number

rancid frost
#

its getting better....

modern creek
#

you did that just by feeding in the coordinate of the hex instead of the constant?

rancid frost
#

yea, the world pos. but.... let me just send small clip

#

It seems the random range is inverted...

modern creek
#

Hm.. I think you're on the right track but unfortunately it's been a few years since I've done anything with perlin noise - like I said I don't think I have the brain capacity to solve this one

#

but I think basically you need each vertex of adjacent hexes to have the same value and function along the edge.. as far as how, that's above my pay grade 🙂

rancid frost
#

Your idea works, from this point i just have to tweak it among other things.
Thanks for the help!

modern creek
#

I have a mesh that I'm adding a material to (at runtime) to outline it and render it through world geometry. The mesh is in a layer higher than world geometry, and I'm creating a local copy of the material and adding it to the mesh like so:

        [SerializeField] protected SkinnedMeshRenderer OutlinedMesh;
        [SerializeField] protected Material OutlineMaterial;
        protected Material _localOutlineMaterial;
        public void Initialize()
        {
            _localOutlineMaterial = new Material(OutlineMaterial);
            List<Material> mats = OutlinedMesh.materials.ToList();
            mats.Add(_localOutlineMaterial);
            OutlinedMesh.materials = mats.ToArray();
        }

It looks like it works, but when I set the color of this local material using the following, the part that "sees through" the world geometry uses the default color:

        public void SetOutline(Color color)
        {
            _localOutlineMaterial.SetColor("_Outline_Color", color);
        }

In the following shot, the default color is cyan, and the new color is red.

Why?

untold crystal
#

i cant see the gizmos like the camera sqare thing in the scence that tells you what you see in game please help

worn star
#

how do i make something go forward in the direction of its rotation

#

like if i spawn it rotated by 45 degrees it moves in that direction rather than horizontally

#

for 2d

dusk apex
modern creek
#

I haven't tried that but I will.. I'm thinking it's something with meshes not updating materials and that I have to use MaterialPropertyBlock?

worn star
#

nvm fixed

modern creek
#

yeah that fixed it (setting property block)

dusk apex
leaden ice
# worn star for 2d

transform.right or transform.up is the direction it is facing. Have your code move it in that direction.

worn star
#

yeah fixed

#

thanks tho

modern creek
#

yeah.. I don't know exactly how meshes determine that a material needs to be re-rendered, I would have assumed changing shader properties on a material would do so, but apparently not

#

(ignore the blue gun - but now setting the property to red using propertyblock instead of on the material directly works)

#

basically changing this to this:

        public void SetOutline(Color color)
        {
            _localOutlineMaterial.SetColor("_Outline_Color", color);
        }

        public void SetOutline(Color color)
        {
            MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
            propertyBlock.SetColor("_Outline_Color", color);
            OutlinedMesh.SetPropertyBlock(propertyBlock);
        }
#

I don't know exactly why.. I'm still a little hazy on how materials work under the hood

tacit vine
#

So i have a namespace what unity cant find.
I added all the DLL's and the strange thing is visual studio says that he can find the namespace but why cant unity do this?
i added the packages with the visual studio add references
also put it in the plugins folder

dawn nebula
#

I have a value in the range of 0 and 1. This value is my target. It jumps around in this range quickly, I would like to smooth out its motion, where we accelerate towards it the farther away we are, and slow down upon approach. Any built in functions to help with that?

vagrant blade
#

Mathf.MoveTowards(...)

#

If you want it to slow down, you can use Mathf.Lerp(...)

#

Note that using lerp means it will never reach the target exactly, you will have to check that the value is approximately close enough.

#

Alternatively, you can get a tweening library (DoTween, PrimeTween, etc.) and use that to do it for you.

dawn nebula
vagrant blade
#

MoveTowards will keep the speed consistent until it reaches the value

dawn nebula
#

Right but I don't actually want that.

#
        currentZoomRange = Mathf.Clamp01(currentZoomRange + delta);
        var approachScaler = Mathf.Abs(currentZoomRange - currentSmoothedZoomRange);
        currentSmoothedZoomRange = Mathf.MoveTowards(currentSmoothedZoomRange, currentZoomRange, Time.deltaTime * approachScaler);
vagrant blade
#

Lerp will slow down as it gets closer, but honestly would just use the tweening library and use an EaseOut curve (or whichever curve makes sense for you)

woven dome
iron pumice
#

When scripting custom inspectors, how can I get default Unity colors and styles?

iron pumice
#

Oh, thanks a lot! mb.

golden kindle
#
private void FixedUpdate()
{
        _rigidbody.AddForce(-_rigidbody.velocity.y /        Time.fixedDeltaTime *     Vector3.up, ForceMode.Acceleration);
}

I just want to stop the cube from falling by applying the foce in the same direction reversed. But it still falls very slowly, how do I solve this?

lean sail
golden kindle
lean sail
lean sail
golden kindle
golden kindle
golden kindle
#

Here is when I activate the force when at y < 2

#

so I need to change the rigidbody acceleration during the same step I guess

#

or undo the last step

dim umbra
#

just wanted to make sure I'm not messing something up, this is the correct way to have the game run at 60 physics updates per second, right?

#

if there's a more precise way to have exactly 60 that would be preferable, since timer systems will be important to the game

leaden ice
#

The most precise would be to do this in code:

Time.fixedDeltaTime = 1f/60f;```
zinc parrot
#

Hey in webgpu, what rendertexture formats can be written to in a compute shader? I find that neither rgbafloat or rgbahalf can be written to

spare dome
# golden kindle

you would want to set the velocity directly to have more precise control

zinc parrot
#

no, webgpu

#

but its not really about whether or not it supports it, I need to know if its read/writeable for a rendertexture

spare dome
#

is that a unity question then?

#

why dont you look your question up?

zinc parrot
#

yes being built for webgpu with unity
and I have but theres not many resources on specifically webgpu for unity

#

and the webgpu without unity hasnt helped much either

rigid island
#

I think you need unity 6 for webgpu

leaden ice
#

that would be why resources are limited

zinc parrot
#

Yeah

cosmic rain
zinc parrot
#

The only resource I could find really said that it only supported single component for rw
But that it would be fixed in 6000.0.2f1…

#

Can you even run webgpu in the editor?

cosmic rain
#

No. Which is why I'm asking.

#

To make sure it's not an issue with your setup

zinc parrot
#

The only way I could really debug was to inspect the web console in builds

cosmic rain
zinc parrot
#

And it kept saying that argbfloat32 can’t be read/write

#

Vulcan, dx12, and dx11 work fine

cosmic rain
zinc parrot
#

I will have to get the exact error later here, walking home from class

cosmic rain
# zinc parrot Vulcan, dx12, and dx11 work fine

I see. I imagine the final goal is for the webgpu to work the same way as the other graphics APIs. However, it's still not fully released, so I wouldn't be surprised that it doesn't work as intended yet.

zinc parrot
#

Yeee
I wouldn’t be surprised either
But the whole not being able to read write to basically any render texture… how did they manage to get deferred working lol

cosmic rain
#

I don't think you need to write to a render texture from a compute shader for deferred rendering to work.

#

Did you try running the samples that unity provides? Do they work correctly?

zinc parrot
#

So I know it works
If I disable my program completely(it’s a custom pathtracing renderer), it works fine

obsidian anchor
#

Heyah! I'm new here and am currently taking an beginner-level university course on learning Unity and C#, I am having a bit of an issue with case sensitivity for a particular prompt for ZigZagMovement script:

#

What it keeps getting wonky about is the placement of the zigzagMovement as a class reference instead of a function. What do I do?

cosmic rain
obsidian anchor
cosmic rain
#

That sentence doesn't make any sense, but if you got it solved, then 👍

leaden ice
obsidian anchor
cosmic rain
#

In various ways, but generally, the loading is done async, such that the game can update and render at it's normal frame rate.

#

What part of it? I didn't use any complex words.

#

Async means asynchronously and there are various ways to go about. The premise is that it executes in parallel with other code.

#

It doesn't necessarily have to be async await.

#

What I said has nothing to do with wether the game is multilayer or not.

#

As I said, they would usually generate the terrain asynchronously, such that the game can update normally while also generating the terrain.

#

It works for everyone. There's no reason for it not to work if implemented correctly.

#

I don't understand why you think multiplayer has anything to do with loading/generating the terrain asynchronously.

#

Has absolutely 0 relation.

#

Also, I'm not sure why you're talking about "ahead of time". This also has nothing to do with async.

#

You simply need to generate the terrain while allowing the app to update such that it can update and render the loading screen.

#

I can't give you exact steps, since it would depend heavily on your generation implementation.

#

I don't see how that contradicts what I said.

#

It fits in your step 4 and 5. Both of these steps would need to execute parallely.

#

Everything else is unrelated.

#

Ok, then what's the actual question? I thought you have a loading bar or something that is stuck when the terrain is generated?

#

I explained how.

#

But since you don't have a loading it doesn't really matter in your case.

#

You can just load it as you do it now.

#

There's no such thing as "let your computer use max CPU". The app doesn't have control over it. It always uses 100% of the CPU that the os gives it if it can.

#

No. There's no such threshold. The processor simply processes things at its pace.

#

You can't tell it to go faster or slower.

#

Unless you tune the hardware, which is unrelated here.

#

What kind of wait statements?
Even if you yield execution to the next frame, that doesn't change how fast CPU is processing things. It simple tells it "pause this work for now". The CPU would then try to do other work if it has any.

#

I don't think it should crash the server.

#

And if it does, then what is the cause? Did you actually debug it? Is it because the app is not responding to the os?

#

Well, you need to figure that out, because depending on the cause, there might be many different solutions.

#

Ok, then what is it?

#

What threshold is it? What kind of resources are you overusing?

#

What's max+?

#

But you have to. It is your responsibility as the developer and it's also the only way to address the issue.

#

I would understand why it happens first and then act accordingly.

#

A wild guess would be that you're running out of RAM or GPU memory.

#

So it has nothing to do with CPU.

#

Well, then what's right then?

#

The only other thing I can think about is that your server doesn't respond to the os, which I mentioned earlier.

#

How do you know that?

#

Investigate what allocates memory exceedingly and optimize that part using various techniques.

#

It depends on the cause. For example pooling. Or queuing the tasks so that they don't allocate the memory all at once. It depends.

#

Probably irrelevant, since it's on the server side. I forgot about it when I mentioned it earlier. But the answer is the same as with memory.

golden kindle
#

@spare dome setting velocity will allow for less control because I can't for instance break the rigidbody at a specific point only the whole body.

@lean sail The reason was because the gravity was applying in the following tick. So the velocity negating calculation was correct. The thing you see is the gravity applying one tick of force every frame.

The solution is to manually do the gravity force so you can add it to the negating calculation in the same frame.

    private void FixedUpdate()
    {
        Vector3 forcesNextTick = Vector3.zero;
        
        // Manually add gravity
        Vector3 gravity = Vector3.down * 9.8f;
        _rigidbody.AddForce(gravity, ForceMode.Acceleration);
        
        // Convert current velocity Y to acceleration
        forcesNextTick += _rigidbody.velocity.y / Time.fixedDeltaTime * Vector3.up;
        
        // We need to add the gravity force this tick
        // This is because the velocity above does not know about the newly added gravity force
        if(_includeNextTickForces)
            forcesNextTick += gravity;
        
        _rigidbody.AddForce(-forcesNextTick,ForceMode.Acceleration);
    }
golden kindle
#

Here it's simplified

    private void FixedUpdate()
    {
        // Add gravity
        _rigidbody.AddForce(Vector3.down * 9.8f, ForceMode.Acceleration);
        
        // Get current acceleration
        Vector3 currentAcceleration = _rigidbody.velocity.y / Time.fixedDeltaTime * Vector3.up;
        
        // Cancel out all forces
        _rigidbody.AddForce(-(_rigidbody.GetAccumulatedForce() + currentAcceleration), ForceMode.Acceleration);
    }
fading tartan
#

is it possible to display this number as a binary representation?

#

when looking the object

golden kindle
#

algorithm is a very very brought word

#

what kind are you making?

golden kindle
knotty sun
unkempt steppe
#

Do you think this is doable @golden kindle

golden kindle
tired elk
#

Hi ! Is there a way to save changes made in Prefab Isolation Mode through script ? I found how to detect if I am in such a context, but the only method available on the PrefabStage that would make sense is ClearDirtiness(). Do I need to call AssetDatabase.SaveAssets() and then call ClearDirtiness ? SaveAssets on its own does not seem to do anything as the prefab is still marked as dirty with an asterisk (*) but it may not mean the changes are not saved ¯_(ツ)_/¯

plucky inlet
tired elk
#

I make change through script that I want to save. Otherwise I would use the auto-save option.

plucky inlet
tired elk
#

I did but was not sure it would make sense in Prefab Isolation. I saw ApplyPropertyOverride but assumed it would be for changes made on a prefab instance to be applied to the prefab.

plucky inlet
#

Maybe you could show your code how you "open" your prefab through script and make the changes.

tired elk
#

Actually it's not that I open a prefab. More context needed : I have attributes I can put on fields, properties or method to control the way they look in the inspector and extend the serialization to some stuff Unity normally does not handle. At some point, I had an issue that I fixed by dirtying the SerializedObject to force the refresh of the inspector. Outside Prefab Isolation, it's "fine" (not the best solution, but for now it works), but when I enter Prefab Isolation, the prefab is marked as dirty (obviously). Auto save would work, but my colleague wants to have it disable and ask if I can make the default dirtyness disappear.
So I'm checking if I am in a Prefab Isolation context to apply changes but do not know what to use to achieve my objective.

#
for (int index = 0; index < this.inspectorObject.TargetObjects.Length; index++)
{
    if (this.inspectorObject.TargetObjects[index] is UnityEngine.Object unityObject)
    {
        UnityEditor.EditorUtility.SetDirty(unityObject);
    }
}

UnityEditor.SceneManagement.PrefabStage prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
{
    // code underneath is probably wrong
    UnityEditor.AssetDatabase.SaveAssets();
    prefabStage.ClearDirtiness();
}
plucky inlet
#

Does not sound like the best approach, as you are targeting to different ways of modifying them. Maybe you guys should decide, if you want to use isolation mode or not? If not, you can just override as you do. But it also sounds quite counterintuitive to change prefabs that much without creating a variant anyways. Just trying to understand, why you would do so through script

#

Does autosave actually work ir hitting apply or is it still marked * when doing so with your custom serialisation?

tired elk
#

And I agree it's more complicated than it should. The first purpose is to update data that are not manageable with SerializedObject in the first place. The code I shared above is just to "re-sync" everything at some key point (for example: code executed to fecth data by the object that should be replicated in the inspector).

plucky inlet
#

Are you sure you are getting this data and everything in correct order? Just wondering, if you are trying to save the prefab while its probably still fetching data, deserializing itself and therefore triggering new changes after you applied your cleardirtiness etc

tired elk
#

This code is called once the data is fetched, bound to the elements and displayed

#

But heh, there is still room for improvement

plucky inlet
#

Just for testing, did you just change a string or something simple and tried that again?

#

Change string, save the prefab and clear dirtiness, just to get all that custom jazz around out of testing and see, if you can save the preafb with simple changes

#

What I also found was something using

PrefabUtility.SaveAsPrefabAsset(yourInstance, yourPrefabPath);
#

as you got the prefabstage there, you could just get the instance from it and save it back to the path of your raw prefab

#

What I am also wondering. Are your changes saved even if its still marked * ?

tired elk
prisma hatch
#

I.. I encountered this problem and its not even from any of my scripts?

#

can someone help me ith this, it happened twice, none of my script interact with this overlay script whatsoever, only a few has enabling or disabling agents, or ResetPath

cosmic rain
prisma hatch
#

no, it just stops the game and gives out the error

prisma hatch
cosmic rain
prisma hatch
#

thank you

muted schooner
#

PostLateUpdate.PlayerUpdateCanvases take up to 15% CPU usage. Is there a way to reduce it? As I understand from the profiler data, my healthbars are problematic. Each healthbar has it's own canvas, and it seems like it is a bad idea. I have to make healthbar the child of the object so I don't have to fetch it's position frequently, which will result with performance problems as well. So what's the optimal solution?

#

Alright, my solution was making ALL the objects that aregoing to have health bars on them a child of the same single world canvas.

#

In this way, I didn't need to fetch the locations manually and I had them being rendered properly with minimal performance loss

#

You guys are great, thank you so much. With the recent recommendations you made on my other questions, I increased optimal enemy amount from 400 to 1500.

#

sorry for the visual mess, lol. Just stress testing

blissful mesa
#

I'm trying to figure out a decent way to add scripts to my tiles for a mining game. I've painted a tilemap using rule tiles. Now I want to be able to click on a tile to remove it.

This would require me to attach a script to the tile but my brain is breaking. Can anyone point me in the right direction?

muted schooner
# blissful mesa I'm trying to figure out a decent way to add scripts to my tiles for a mining ga...

about script attaching - you can use scriptable objects.
https://youtu.be/XIqtZnqutGg

This tutorial does not directly link a tile instance to a script, I think it's not possible at all, but instead he attaches the tile type to a scriptable object with some data. When X tile gets clicked, he looks for a scriptable object that has the X tile in attached tiles list, then uses the found element to have the data.

In this video I to show you how you can use scriptable objects to store any kind of information in a tile. You don’t have to install any extras or make special tiles, you can use the standard tiles straight out of the box with Unity’s built in Tilemap. As an example I show you how to make those little bugs that check how fast they can crawl base...

▶ Play video
#

if you want to attach a script to a specific tile and not tile type, then that's honestly out of my limits

#

for an instance, the tutorial guy in the video uses two tile types, "Grass" and "Stone". He doesn't attach scripts to tiles manually, but instead uses the tile types

#

the same guy has a tutorial that fits your needs better https://youtu.be/hPsB6MiJPQY

In this video I show you how to set your tilemap on fire, including how to change tiles via script.

Get the full project here (free) : https://github.com/ShackMan2000/TutorialTilemap

The part where the tiles are changed:
http://www.youtube.com/watch?v=hPsB6MiJPQY&t=4m40s

Get the fire prefab:
https://gofile.io/d/EDqHKj

How to make the f...

▶ Play video
#

continuation of the first tutorial

blissful mesa
#

I see rule tiles have a default game object option but wasn't quite sure how to make use of this

balmy nacelle
#

i've been working on a "light gun" game. Aim around the screen and shoot (doesn't rotate character like a normal fps)

I created a way for the gun to follow the mouse.

I am using the PSX shader from the asset store, since the screen is just a raw image / "render texture" the actual "raycast" is completely off and not "straight"

I assume it has something to do with the res, but at the same time there could also be an issue with my tracking / gun pos.

I've added offsets, no matter what. when i put the mouse far left or far right of the screen, its out of wack.

private void PointWeaponAtMouse()
{
    // Get the adjusted mouse position based on the provided offsets
    Vector3 adjustedMousePosition = new Vector3(Input.mousePosition.x + xOffset, Input.mousePosition.y + yOffset, Input.mousePosition.z);

    // Raycast from the camera through the adjusted mouse position to get the world point
    Ray ray = playerCamera.ScreenPointToRay(adjustedMousePosition);
    RaycastHit hit;
    Vector3 targetPosition;

    if (Physics.Raycast(ray, out hit, gunRange))
    {
        // If the ray hits an object, aim at the hit point
        targetPosition = hit.point;
    }
    else
    {
        // If no object is hit, aim at the farthest point along the ray
        targetPosition = ray.origin + (ray.direction * gunRange);
    }

    // Calculate direction from the weapon tip to the target point
    Vector3 direction = targetPosition - weaponTip.position;

    // Rotate the weapon body to look at the target point
    weaponBody.rotation = Quaternion.LookRotation(direction);
}
hard tapir
#

This must be joke, does unity remote config supports arrays?

#

When I tried to get that JSON with array through cloud code then it worked in dashboard, but it doesnt work in unity itself

#

this is very confusing

thick terrace
hard tapir
modern creek
#

I have some TMPro font .asset files which keep being updated/modified by unity and are making my git workflow a bit of a pain in the ass. The files have no modified data. Any tips/workarounds?

gray mural
modern creek
#

Hm, I have a gitignore file in another project with TMP that doesn't have this issue.. what would be different about this project? Also, I'm not exactly sure what to filter here - i'm assuming .asset files are needed elsewhere in the project

native copper
#

I have a question. So I'm using this code to make my simple enemy ai walk around at random points within a circle;

    {
        Vector3 randomPoint = center + Random.insideUnitSphere * range;
        NavMeshHit hit;

        if (NavMesh.SamplePosition(randomPoint, out hit, distance, NavMesh.AllAreas))
        {
            result = hit.position;
            return true;
        }

        result = Vector3.zero;
        return false;
    }

    void Patrol()
    {
        if (agent.remainingDistance <= agent.stoppingDistance)
        {
            Vector3 point;

            if (RandomPoint(transform.position, moveRange, out point))
            {
                transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(point), turnSpeed * Time.deltaTime);

                Debug.DrawRay(point, Vector3.up, Color.blue, 1.0f);
                agent.SetDestination(point);
            }
        }
    }```

But I don't want it to move at random points within a circle, cause oftentimes it'll just keep going back and forth. Does anyone have any tips for how I could make the movement feel much more natural, like having the random point be within it's cone of vison rather than a circle around it?
gray mural
modern creek
#

What, like a full library rebuild..?

#

I mean, I can do that but I'm just not sure why that would prove it - I'm not doing any sort of full rebuild in project B - every time I do something in the scene in B, the .asset files get touched by unity

#

my gitignore from project A doesn't contain anything specific to TMPro

gray mural
#

Hold on, does your another project have the same issue?

modern creek
#

project A & B both use that gitignore, have TMPro, but project B updates the .asset files for some reason

#

project B is unity6, project A is 2022.3

gray mural
#

Project A doesn't, even though the modifications are the same?

modern creek
#

I mean, I'm not modifying the fonts in either project so.. yes?

#

I don't know if I understand the question

#

I'll try to find a minimal reproduceable use case.. I think it's literally as simple as "drag a prefab into a scene that contains a GO with a TMPro component"

gray mural
#

Do you have to save the scene for this issue to appear?

modern creek
#

I think so, yeah.. but I have my unity setup to save the scene on play so I'm sorta saving it (implicitly) all the time

#

Yeah so.. lemme snap a vid. Fresh commit - just add a prefab to a scene (prefab contains a TMPro component and almost nothing else), save the scene.. asset files are mucked with

gray mural
#

It's

[Tt]extMesh [Pp]ro/
modern creek
#

i mean, what's the string I'm searching for? I imagine I can't gitignore .asset files (unity internal files, probably?) - and there's nothing in the path of those modified files that contains anything related to tmpro

gray mural
#

After user settings

modern creek
#

I'd have to move that shit into a textmeshpro folder.. and to some extent, those files belong in git since the project wouldn't build without them

#

i'd rather find out what the root cause is and why this happens in one project but not another..

#

(I haven't found anything in TMPro preferences)

gray mural
#

Yes, supposedly, the git ignore for tmp is triggered only when the tmp file in assets is changed

#

What I think is that you might have troubles with your .meta files

#

I would at least try Refreshing the asset database, reloading unity rebuilding the assembly

modern creek
#

dynamic/static font assets

#

Yeah, that was it. Setting the imported fonts to static for all my fonts worked.

olive bobcat
#

Need help with terrain and noise.
For some reason when I generate the noise I get this result. the texture is rendered for a grid of 2x2 of 513x513 pixel. but it sux 🙄

#

I mean, the problem is about the squares

#

Sorry /AFK

plush ridge
#

So, is it best practice to just never get null reference errors? Or where is the balance the two? I heard something in a video earlier along the lines of "in case the sound manager isn't working for some reason you wont get a null reference" to me, it seems like a sound manager should always be working no matter what

plush ridge
lean sail
#

Oops fixed the wording

plush ridge
lean sail
urban lintel
#

Can someone tell me whether this is a fine practice or whether there's a better way of achieving this effect?

I want to have grid movement (so ideally it's discrete) but want the sprite itself to smoothly follow the movement through dotween. I've separated the gameobject of the entity from the gameobject containing the sprite, and made this second object lerp to the original object in the update loop. This works fine, but I'm reading that in order to use something like dotween, you don't wanna call the dotween in the update loop (and I do get a warning for it in runtime when i do). So my guess was going to be to add an event to the original object along the lines of OnPositionChanged and then subscribe to that from the visual object and call the dotween there.

Is this a fine approach? I could also have the visual object be referenced in the main object script but I figured that if I ever want multiple things to react to the change, this would be a better way of doing it.

plush ridge
outer plinth
lean sail
urban lintel
#

I want the movement of the actual item to be instant and discrete, so only 1.0, 2.0 etc., but want the sprite to tween between the two positions for the course of 1 second for example. I wasn't sure how to separate those two movements so I put the sprite in another object and just made it follow the original object

lean sail
#

Then yea you could use an event and just start the tween from there. Though I'd just use update tbh

urban lintel
#

Update with lerp?

lean sail
#

Lerp if you want it to move a percent over time, MoveTowards if you want it to move a certain amount per second

modern creek
# plush ridge Alright fair enough. Thank you for the info! I guess I shouldn't be getting a bu...

Just to add to what bawsi said, what a "null reference exception" actually is is worth knowing. Little bit of programming history - you used to have to manually declare a block of memory to hold something like a game object, and you'd "reference" to it using a variable that held a pointer to that memory. That block of memory would have variables and so on. Say the size of your object is 100 bytes and the speed variable is located 16 bytes from the start of the block.. the executable would know that speed is defined at the address of the "pointer" plus 16 bytes.. or that it would need to write the new value to that location.

In other languages, if you didn't set your pointer properly, you'd try to set variables in memory where they shouldn't be - leading to your computer crashing usually.

Modern languages (mostly) have this "null reference" checking. So.. yeah, you're not supposed to do it. 🙂 Check to see if the value is null and if so, do the appropriate thing

urban lintel
#

As in use lerp on the sprite object to just transition over time? I was just gonna use dotween to learn it and since it seemed easier to specify my movement in seconds and such tbh

#

Also seemed to have decent APIs for things like animation curves

olive bobcat
# plush ridge I'm here cuz I'm a beginner but, adding a bit of noise to an image with a gradie...

Indeed but I don't get why, if the resolution is correct:

    {
        NativeArray<float> noiseResult = new NativeArray<float>(resolution * resolution, Allocator.TempJob);

        for (int y = 0; y < resolution; y++)
        {
            for (int x = 0; x < resolution; x++)
            {
                float sampleX = (x + seed) / (float)resolution * scale;
                float sampleY = (y + seed) / (float)resolution * scale;
                float noiseValue = Mathf.PerlinNoise(sampleX, sampleY);
                noiseResult[y * resolution + x] = noiseValue;
            }
        }

        return noiseResult;
    }```
#

but the noise at the end sux, in quality and when I render it, looks like the pictures above 😦

lean sail
spare dome
#

using the velocity would give you more control due to the fact that you can set it to whatever you would need

plush ridge
modern creek
#

you probably want to learn the singleton pattern for your game manager so you aren't having to write a lot of boilerplate code through your app

#

Not everyone likes this pattern but I do 🙂 Lemme paste you some code

plush ridge
#

I'm inheriting from a Singleton class B)

modern creek
#

If it's a singleton then you don't need to check if it's null

#

I wouldn't use that .. I'd probably use it as a DDOL and manually managed singleton

lean sail
modern creek
#
    public class GameManager : MonoBehaviour
    {
        private static GameManager instance;
        private static GameManager Instance => instance == null ? FindFirstObjectByType<GameManager>() : instance;
        private void Awake()
        {
            if (instance != null)
            {
                Destroy(gameObject);
                return;
            }
            instance = this;
        }
    }
#

something like that

#

(in a DDOL in your loading scene)

plush ridge
modern creek
#

then your methods are like:

        public static void StartNewGame() => Instance.StartNewGameInternal();
        private void StartNewGameInternal() { ... do the stuff ...}
#

yeah, then you can manually load/destroy it for that scene

#

I just like the singleton approach because it makes interacting with the domain layer (the logic guts) pretty easy from anywhere

#

and then I pub/sub messages out to the UI to react to

#

but again, this isn't everyone's favorite approach and there's a lotta ways to skin this cat

plush ridge
modern creek
#

always, yes

lean sail
#

Well not throw, but LogError which I guess might throw by itself?

plush ridge
plush ridge
#

^ is the solution for this try-catch statements? or what's my next google search? if ya don't mind me asking

lean sail
#

The solution really is just assigning the reference and running the game again. Theres nothing you should do code wise if you just didnt assign it

silk narwhal
# modern creek ```cs public class GameManager : MonoBehaviour { private static ...

Would also like to add a general solution for easier singleton adding. This does confine you to this base class, but you usually do managers etc. as a direct child of MonoBehaviour so this works pretty much every time for me

using UnityEngine;

public class Singleton<T> : MonoBehaviour where T : Component
{
    public static T Instance;
    public bool m_DontDestroyOnLoad = false;

    protected virtual void Awake()
    {
        if (Instance == null)
        {
            Instance = this as T;
            if(m_DontDestroyOnLoad)
                DontDestroyOnLoad(this);
        }
    }

    protected bool isTheOne()=>Instance == this;
}
#

you then do a

public class ShopController : Singleton<ShopController>

for example

#

you can add things like dontdestroyonload like i did, or handling more than 1 instance being detected (e.g. when scene-switching)

runic pawn
#

i have a function from an API that takes as an argument an Action<T, Channel>:

#
        public void RegisterBroadcast<T>(Action<T, Channel> handler) where T : struct, IBroadcast
#

my question is can i pass an async UniTask into this instead somehow, like this:

#
        private async UniTask OnMessageRecieved(RoomBroadcast msg, FishNet.Transporting.Channel channel)
#

currently it only works if its async void

simple egret
#
RegisterBroadcast(async (msg, channel) => await OnMessageReceived(message, channel))

// or

RegisterBroadcast(Handler);
// + 
private async void Handler(RoomBroadcast msg, Channel channel) => await OnMessageReceived(message, channel);
runic pawn
#

well i am trying to use UniTask since that seems to be what works for my webgl app, i'm not sure if another async lambda will work

#

hmmm ok

simple egret
#

The two signatures are incompatible so you cannot do that without a "conversion" first

dim umbra
#

Currently have some code in fixed update that I want to still be able to run when timescale is 0. I tried to do something like this to replicate it since I heard that coroutines still worked at 0 timescale, but I'm not super familiar with them and it doesn't work. Is what I'm trying to do possible?

#

by doesnt work I mean it just prints once

simple egret
#

How are you starting the coroutine?

dim umbra
#

On awake

rigid island
simple egret
#

Post the code, I suspect the issue is there

dim umbra
#

oops

dim umbra
jagged plume
#

If I want to move this mob all around the room (e.g. walking on the walls) and like faster and faster, does it make more sense to do it in Animation > Animation (and create an attack1 animation let's say); or should I proceed programmatically?
If programmatically, how do you handle the 6 body parts ? (since the mob would have to "break" in some sense as some parts would be on the vertical wall while others still on the floor)

#

It's a boss battle room like in Kirby so cam is locked when player is in combat zone

golden kindle
stark fiber
#

hey guys, any idea what might cause the line Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue()); to return a different thing when used in two different scripts, in the same frame? I don't touch anything that would mess with the camera or the mouse

stark fiber
#

one time it's what you'd expect, the other it returns a vector3 with infinity in all positions

#

my only hint for what might be going wrong is that it's infinity when I query sceentoworldpoint in a script attached to the camera itself

stark fiber
#

in update, in a script attached to the camera

rigid island
#

try assigning the Z value to it because if you're using prospective especially the Camera does affect it indeed

stark fiber
#

ah, I rubber ducky'ed my way to the solution, it was shooting errors so fast I didn't see, but I'm actually just stupid i incremented the value of the position of the camera instead of changing it, resulting in infinity after very little time

#

thanks!

rigid island
#

hah nice!

mild dock
#

Does anyone have any tutorial* recommendations for procedural world generation - biome generation? Something 2d but theres very few 2d tutorials in this topic and its just basic noise and not like a real biome generator. And 3d ones have conditions for like air or water, Whereas my terrain does not.

mild dock
#

kinda, it also has air/water/liquid calculations, mine doesnt

#

im trying to fill a map with biomes, But each attempt i keep just randomly getting random results. Like ocean is next to mountain next to plains next to ocean next to plains next to ocean, i think i messed it up bad and just deleted it xD

#

and now i need to refresh on something new here because im doing somethin wrong lol

dire lava
# mild dock im trying to fill a map with biomes, But each attempt i keep just randomly getti...

How To Make A 2D Game Like Terraria / Minecraft in Unity! In this tutorial, I teach you how to make a 2D sandbox game like Minecraft or Terraria in Unity! It's easy to follow even for beginners as we go through how to generate terrain with Perlin Noise, animations, player movement, tiles and an inventory system!
Today we add biomes such as snow ...

▶ Play video
#

Try this

#

İ just looked it up

#

Search "terraria biome generation" or "2d mc generation"

simple void
mild dock
mild dock
#

What im trying to do is populate like a voronoi diagram

#

Which i admittedly iv tried but thats what i threw out xD dont think i did it right or its just not possible to use for what im attempting

paper pine
#

Hey everyone, I'm working on a third-person controller in Unity and need some help with animation blending.

I've got the movement logic done, and my animations for walking forwards, backwards, left, and right are working perfectly. The problem comes in when I try to blend animations for diagonal movement (like walking left-forward or right-backward). I'm using a blend tree in Unity, and while the animation looks good, it plays very slowly during these diagonal movements. Another Problem which i encounter when trying to move diagonally in the backwards directions is that the left and right animations are swapped.

Has anyone else run into this issue or have any suggestions on how to fix it? Thanks in advance!

dire lava
#

Are you using tile maps ?

simple void
mild dock
dire lava
mild dock
#

Like if i said 0.4 to 0.49 is plains, 0.5 to 0.59 deserts, 0.3 to 0.39 is forests, It will consistently be those regardless where you walk, Which does solve the inconsistency with biome grouping placement but makes the world super repetitive and predictable

dire lava
#

Just zoom the peeling noise inside and out for different noises no ?

simple void
#

Also there’s a way to expedite the process don’t check every biome using a list of if-else statements, if that’s what you’re thinking.

#

For a one parameter, let’s say you define your biomes off the terrain height, you can use a binary tree or smthing to determine the Biome in O(log n) for higher dimensions(more conditions) you get a similar performance using R-Trees

mild dock
#

Okay thanks yall

#

Also Gweam you lead me down a new rabit hole, thank you

#

just found Ridge Noise along with this peeling noise topic

simple void
#

Peeling noise?

#

Do you mean perlin noise?

mild dock
simple void
mild dock
#

aside from performance

simple void
#

Less dimensional artifacts

#

It’s hard to explain atm

mild dock
#

fair xD

short hatch
#

guyzz I'm having a bit of trouble with my script. It’s supposed to stop a timer when the player hits the target zone,
but I got a bummer
Any ideas on what I might be missing?

tawny elkBOT
wraith cobalt
olive bobcat
#

The impressive aspect is that the Burst engine is incredibly fast... It blows me away every time! 😂

weak dove
#

Hi, I'm working on making a GOAP AI system for my game, but I'm a little stuck on how to handle types in C#.

#

For example, I have a class called EatAction<IEatable>. I have a bunch of food item classes that implement the interface IEatable (eg. Apple, Chicken etc..)

#

I want to be able to consider EatAction for each of these different food classes (EatAction<Apple>, EatAction<Chicken>) AND after that I also want to be able to set a specific instance of the food class as a target. So the IEatable part of EatAction<IEatable> can refer to the IEatable interface, classes of specific types that implement the interface, and also instances of these specific objects.

#

Tried to just make a list of EatActions with all the different food classes as a target, but I'm getting this error:

olive bobcat
weak dove
#

I guess it should be eatableType?

winter jacinth
#

Is there any toggle to make it so the cursor doesnt move when im doing things in viewport like moving around and turning while holding RMB?

weak dove
#

And then Cursor.lockState = CursorLockMode.None; on RMB up

lean sail
#

If the generic is constrained only to IEatable I dont think you need it to be generic

weak dove
#

I changed it to this:

#

So the variable target should be able to hold classes that implement IEatable, and also specific instances of those classes, I think?

lean sail
#

Not sure what you mean hold classes and instances of the class. It's just a variable, which so happens to be of type IEatable. It will hold any instance that implements IEatable

short hatch
weak dove
weak dove
#

For example, I have classes "Apple" and "Meat" that implement IEatable. In the GOAP planner I want to consider EatAction with each of these classes, without having to supply specific instances of those classes, because there might not even be any instances in scene. Later, it would check if any instances of those types exist, and if so, set the target to one of those instances.

#

Like when the agent is first considering eating an apple, they need to consider doing EatAction to the abstract concept of an apple (ie. the class Apple), not a specific instance of an apple.

lean sail
# weak dove Like when the agent is first considering eating an apple, they need to consider ...

I'm not sure how your system is setup, but still this makes no sense. Are you familiar with c# fundamentals?
If you declare a variable of type IEatable, the only thing you're gonna store in there is an instance of something implementing IEatable. It sounds like you want to store the type of each thing implementing IEatable but this sounds wrong to need to do, unless it's purely for some editor functionality

#

Im also not sure what the goap planner is or looks like. wouldnt it make more sense to consider what foods are available first before looking at every eatable item, then decide what to eat? Rather than having it consider every type just for there not to be an instance

weak dove
#

Yeah, I want to store the type of each class implementing IEatable.

weak dove
#

One workaround I can think of is just to make an instance of each class (Apple, Meat) in the scene, but use them as a reference instead of a target. Then I could have two variables "targetType" and "targetInstance". targetType would hold the reference instance, and targetInstance would only get set when an actual instance of the class is found.

lean sail
weak dove
#

That would still require two separate variables, right? One Type variable and one IEatable variable (to refer to the instance).

weak dove
chilly surge
#

What are you going to do with the type?

#

Are you going to create an instance of it, find components of it, or what?

lean sail
weak dove
chilly surge
#

How do you check the predefined value if you don't have an instance of it to check?

weak dove
#

Now that I think about it, it's not possible to get values of Types, so having a placeholder instance of every item would probably make the most sense.

chilly surge
#

You would be able to do it with static abstract in newer C#, but unfortunately Unity is stuck on an old version of C#.

thick terrace
weak dove
#

Yeah, I think that would make sense too

#

Btw thanks for the advice everyone!

unkempt steppe
#

hey guys, does unity have coding?

somber nacelle
#

wdym by "have coding"

knotty sun
unkempt steppe
knotty sun
unkempt steppe
knotty sun
#

pen and paper

unkempt steppe
#

i need help i'm losing hope for my research...

#

i don't wanna fuck this up

unkempt steppe
knotty sun
#

no, I am not your professor. Did you go and ask him about your research sources as discussed yesterday?

knotty sun
unkempt steppe
cosmic rain
knotty sun
cosmic rain
unkempt steppe
# knotty sun then that is where you start

I already found algorithms from existing papers like parametric modeling, morphing algorithm and SMLP (i'm not actually sure if these are algorithms).

since there are like a 1000 different ways to do what we're describing, the algorithm will be my own, but i can stitch it together based on existing work and existing algorithms.

unkempt steppe
cosmic rain
knotty sun
unkempt steppe
unkempt steppe
cosmic rain
#

This doesn't sound much like an algorithm to me. Just a simple app with ui and and some code.

unkempt steppe
cosmic rain
#

Wdym by unique?

unkempt steppe
# cosmic rain Wdym by unique?

i just don't have to copy and paste the existing algorithms, i have to design my own by stitching together based on existing work and existing algorithms

knotty sun
#

I think you need to go and talk to your professor and ask him for guidance, especially in terms of deliverables because it strikes me you have no concrete idea of what you are even supposed to be doing

unkempt steppe
#

do you know parametric modeling, morphing and smlp btw?

knotty sun
unkempt steppe
knotty sun
unkempt steppe
#

what do you mean?

knotty sun
#

that's the point. the algorithm is the same it's just the implementation of the algorithm that is different

unkempt steppe
knotty sun
#

because the only difference is you are implementing a 3D vector rather than a 2D one, and that is an implementation detail, nothing whatsoever to do with the underlying algorithm

unkempt steppe
unkempt steppe
knotty sun
#

of course they must, so what you should be researching is the underlying concepts of those techniques, not the implementations of them

unkempt steppe
unkempt steppe
knotty sun
#

no, absolutely not

unkempt steppe
#

okay sure

unkempt steppe
#

but it's okay

dusk apex
unkempt steppe
earnest gazelle
#

Should we save the asset (prefab, SO) after changing the value of a serialized field through OnValidate?
I would like to set a sequential value to a field of a component initially

public abstract class PersistenceComponent : MonoBehaviour, IDataPersistence
    {
        [SerializeField, ReadOnly] private int _localId;

        public int LocalId => _localId;

        public abstract void LoadData(DataPersistenceObject dataObject);
        public abstract void SaveData(DataPersistenceObject dataObject);

        private void OnValidate()
        {
            if (_localId != 0) return;
            var ids = GetComponentsInChildren<IDataPersistence>(includeInactive: true)
                .Where(p => p != null)
                .Select(p => p.LocalId)
                .ToHashSet();
            var id = 1;
            while (true)
            {
                if (!ids.Contains(id))
                {
                    _localId = id;
                    break;
                }

                id++;
            }
        }
    }
blissful mesa
#

I have a tilemap with blocks on it. I'm trying to instantiate a GameObject with an animator and sprite renderer at runtime when I click a block. It plays an animation over the block on click.

However, attaching the sprite renderer really messes with the gameobject position. Visually, the tile and mouse position are far apart, but position wise it is similar.

#

gahhh I figured it out. the sprite import setting here is what fixed it. Set the sprite import to local space (I'm guessing before it was using the canvas size i had set up in Aseprite?)

timid comet
#

!ask
ive made a state machine for my game and theres a logic if player grounded you can jump once
im trying to change it to double jump
but im kinda having troble with it

my jump state https://pastebin.com/dTBemRd3
my machine state https://pastebin.com/5qP9dkDB

tawny elkBOT
somber nacelle
lofty summit
#

what is the best way to have all the information for a capsule collider without one? 😅
Can I keep the component disabled and still ask for the radius and height? 🤔

quaint rock
#

you could

#

but if all you care about is Radius and Height could just make your own component for that

spring basin
#

hello, i need some help with the trail renderer component, I want to add a trail effect to my character moving in a grid but trail bends/diagonally draws when my character moves too fast in an L shape. how do i ensure the trail follows the L instead of bending?

opaque vortex
#

Is there any way to test my coding knowledge like a general test for c#? I want to know how much I do know, and do not.

quaint rock
#

that will clearly show where you need to brush up on skills or not

opaque vortex
quaint rock
#

so its hard to generalize, since the skills for working in different domains can change a lot

dawn nebula
#

How do you convert a quaternion to a point on a unit sphere?

mellow sigil
#
quaternion * Vector3.forward
steady otter
dawn nebula
#

I have a quaternion rotation, and I want to split it up into a pitch/yaw. (Angular rotation along X and Y axis). Any tips?

somber nacelle
mellow sigil
steady otter
somber nacelle
#

but I cannot just paste in the code to make a random range
show what you tried? i cannot provide a fix for a problem you have not bothered showing or even describing until just now. but even still, if there is nothing actually in the array then you won't be able to get something from the array

dawn nebula
mellow sigil
#

It's not possible for all vectors. For some (most?) cases you need to rotate along X, Y and Z, or rotate first X, then Y and again X (in local space)

#

in 3D space that is

dawn nebula
#
    void Update()
    {
        var delta = Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;

        var newScale = Mathf.Clamp(currentScale + delta, 1, 100);

        var input = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z);
        Ray ray = Camera.main.ScreenPointToRay(input);

        if (Physics.Raycast(ray, out var hit))
        {
            normalIndicator.transform.position = hit.point;
            normalIndicator.transform.up = hit.normal;

            var angle = Vector3.Angle(Vector3.back, hit.normal);
            var arcLength = Mathf.PI * currentScale * (angle / 180);

            var scaleFactor = newScale / currentScale;

            var arcOffset = (arcLength * scaleFactor) - arcLength;

            float radians = arcOffset / newScale;
            float degreeOffset = radians * (180 / Mathf.PI);

            Vector3 axis = Vector3.Cross(hit.normal, Vector3.back);
            transform.rotation = Quaternion.AngleAxis(degreeOffset, axis) * sphere.rotation;          
        }

        sphere.localScale = Vector3.one * newScale;
        sphere.position = Vector3.forward * newScale;
        currentScale = newScale;
    }

This is the code that's doing it.

#

The issue is that the sphere is also rotating along the Z while it zooms in. I don't want this.

#

I have no idea how to resolve that.

steady otter
somber nacelle
#

you also need to say what errors you get

#

but also you should be using the length of the array, not an arbitrary number like 5 as the max

steady otter
#

Okay how would I set up the array though? I tried replacing targetPrefab for randomNumber and then dropping that into the code but that still just conflicts with the already existing code

steady otter
somber nacelle
#

can you be more specific than these vague phrases like "conflicts with the already existing code". you need to actually provide useful info that might help me figure out wtf you are doing wrong

steady otter
elfin tree
#

I have a WebGL breaks that compresses/decompresses json with gzip, and for some reason, if I build it using "Runtime Speed w LTO" instead of "Shorter Build Time" I get an error at the moment a gzip function is called in the game, thoughts?

steady otter
#

I just can't wrap my head around what I would need to do to have random targets spawn in as everything is runs fine its just the extra targets

somber nacelle
steady otter
#

okay I defined the targetpPrefab with the target class

somber nacelle
#

huh?

steady otter
#

private Target[] targetPrefab; is the exact line of code

rigid island
steady otter
#

yes and from here I do not know how to add on to the already existing definition of targetPrefab to make it an array

rigid island
#

its already an array with []

#

you create a new one with size and assign values if its not serialized

steady otter
#

okay gotcha

rigid island
#

you probably want to expose it in the inspector as [SerializeField]

steady otter
#

Yup got it

#

I set the array to be 3 in the inspector as I have 3 different targets that I want spawning and being treated the same as the targetPrefab

kind carbon
#

how can i send my code that isnt working

steady otter
#

There still is the error with the instantiate saying that it clones the object original and returns the flone

somber nacelle
#

provide the actual error message rather than a description of what you think it says

steady otter
rigid island
# steady otter

yes putting an entire array in an UnityEngine.Object makes no sense
you're putting a box where its a hole for a sphere

open plover
#

            Touch touch = Input.GetTouch(0);
            if (EventSystem.current.IsPointerOverGameObject(touch.fingerId))
            {
                Debug.Log("yes");
                return;
            }
            if (um.gameState == GameState.MainMenu)
            {
                Debug.Log("touch");
                um.DraggedAtStart();
            }
``` This is in Update. "Yes" get logged like 5 times but after that it logs "touch". The touch is over an ui element. No idea why does it first correctly detect it is over an ui (multiple times) but then doesn't
steady otter
somber nacelle
# steady otter

just so you are aware, the error message is that bottom line that starts with CS0311, that first line under the signature is the summary comment on the method that describes what the method does

somber nacelle
spare dome
#

i see no issues with it imo

dawn nebula
spare dome
#

well lucky you that earth does

dawn nebula
#

not incorrect

west bough
#

My car is running away from another car. As it finds the shortest path in the navmesh while running away, it sticks to the side when it is going to turn the street. I want it to move exactly in the middle

#

how can I solve it ?

steady moat
rigid island
#

Use splines

west bough
#

ok let me try that. thanks

rigid island
#

also we have the same city asset UnityChanLOL

west bough
#

ahahah, I think we are doing the same thing on this map

west bough
west bough
# rigid island Use splines

The road splits in two. He'll have to go left or right at random. If I get in front of him, he'll have to run back. Can I do it all using splines? I tried coding it, but it seemed a bit like it was for npc animation.

rigid island
#

it gets really annoying but its possible

#

basically you need to know the specific index you want to go too

cold parrot
# west bough My car is running away from another car. As it finds the shortest path in the na...

if you don't want to code all your navigation yourself, you should look into A*PathfindingProject Pro which gives you a lot of tools for doing this kind of thing. Note however that no astar based pathfinding solution will be able to truly handle vehicles on its own since the algorithm cannot understand an actor that needs steering, so you need an implementation where you can configure the graph in a way that this doesn't matter for your particular usecase. Navmesh is inherently not well suited for vehicles. with APP you get a bunch of path post-processing and steering options what can make vehicles behave quite nicely.

west bough
#

$140 seemed a bit expensive for such a small project. I think I will keep trying splines

cold parrot
#

in any case, point graphs (which is what you need here) are a feature of the fee version, pro is mostly for performance and advanced navmesh usage.

normal sail
#

Question,I've made a Main Menu for my game,made it as a separate scene and when im pressing play it's supposed to send me to the main game scene with ((these dont really matter)a text and a blurry backround) after 3 seconds to unfreeze the scene and let me play,but instead it crashes and stops the run.I've tried testing in Build & Run but it just closed the game.If someone can help me and needs the script,tell me and I'll send it.

west bough
#

Is it possible to start the knot0 in the same position where I started drawing?

normal sail
rigid island
cosmic rain
tawny elkBOT
floral timber
#

Question, how can i code good graphics in unity 5 from scratch? I no longer want to copypaste someone else code, i want to do proper HLSL shennanigans With C# actually coded by me.

rigid island
#

I no longer pírate asset store packs

floral timber
#

Yessir

#

No more

rigid island
#

thats embarassing that people do that

floral timber
#

Why tho?

rigid island
#

because its usually a developer putting work and you're stealing

#

and its not some corpo, its an actual indie dev most of the time

#

not something to be said proudly 🤷‍♂️

floral timber
#

I Know, but doesnt éthics Apply on both sides?

#

I wouldnt sell or distribute the game With those assets Either, i Just was playing and testing them

#

Also im poor and underage so thats my point

rigid island
#

meh its still not something you want to mentioned at all esp in a room full of devs.

floral timber
#

Ooh

rigid island
floral timber
#

Oh crud... i might been a little bit too honest

#

Yeah i realize

#

Well i already sent the message so hopefully nothing bad happens

rigid island
#

anyway if you want to learn C# you learn c# , unrelated to HLSL

#

HLSL is used to talk to graphics/shaders directly. C# is versatile in different things

floral timber
rigid island
#

It depends the end goal. Unity can do that without even needing code, but generally a shader is needed. In c# you would probably not do such a thing

#

ShaderGraph exists also and requires no code, or you can add custom functions

floral timber
#

Ohh let me search shadergraph to see if its What i think it is

floral timber
cosmic rain
rigid island
#

also how would you even aquire the modded version of unity for that console

floral timber
#

I want to do the graphics from scratch becuse of that

rigid island
#

iirc you signed NDA and that gave you special version of unity

#

or that was just nintendo / sony

floral timber
cosmic rain
#

Anyways, you'd either need to learn to write shaders(and pretty archaic ones too), or fake it via a scene setup/render textures(if that's even supported)

floral timber
#

Thats why i went here to seek help

#

Like documentation and resources

#

If theres even any

cosmic rain
steady otter
somber nacelle
#

i assume you mean "null" rather than "full" and you're still not providing the actual error message, so this is really only speculation but i'm going to, once again, assume that your array doesn't actually have anything in it.

#

also you're still using a magic number for the max parameter of Random.Range instead of the length of the array

steady otter
#

never mind I was just being stupid and forgot to put my prefabs into the actual unity inspector

#

thanks for putting up with my probably very frustrating explanations but I learned a lot

hybrid portal
#

does anyone know how to put mods into a minecraft server?

#

if so please dm me

ancient sable
#

Is there a way to efficiently determine, when a mesh collider collides with any non-mesh collider (such as a box collider), what ContactPoints collided within the bounds of what triangles (so I would have some sort of enumerable of all the triangles that had the ContactPoints, and it would incorporate all of the collision points (So maybe something like a dictionary where the key is the triangle, and the value is a list of ContactPoints))

hybrid portal
leaden ice
#

You're lost. This is a Unity server

hybrid portal
leaden ice
#

Ask in a Minecraft server

#

Or Google it

hybrid portal
#

I'm not in one, Don't want any youtubers in my dm's

hybrid portal
# leaden ice Or Google it

I have. Multiple times. I don't want to pay $12 a month when I already have spent $28,000 on my servers.

lean sail
hybrid portal
#

does anyone know how to make a working save file that can branch upon 27 different scenes in a unity fine that also is programed to make a file on the users computer that holds the save data? also that can encrypt the data so that people cannot change the save data?

cosmic rain
#

Wdym by "branch upon 27 different scenes"? That sentence doesn't make any sense.

hybrid portal
hybrid portal
cosmic rain
#

What branches? What does it even mean in the context of save files?

hybrid portal
#

take a tree for example, a tree can have from 0-infinity amount of branches, in the end it is all connected to the stump. in this case, all of the saves can be connected throughout all of the scenes as well as the progress of which the player has made along the story of the game. The classrooms of my game are all put in different sections, kind of how "My Friendly Neighborhood" is set up.

#

in conclusion all of the progress would have to be saved throughout the whole game, location, enemies as well as the amount of coins the player has.

cosmic rain
hybrid portal
cosmic rain
#

You'd get a proper answer right away if you weren't spiting out off topic bullshit.

ancient sable
jaunty sundial
#

I dont get how im still getting floating point errors when im snapping the value to 2 decimal places

vagrant blade
#

You got your answer, be less annoying about it, thanks.

leaden ice
lean sail
ancient sable
# lean sail is Collision.GetContacts what you want? im not really sure what youre trying to ...

No. Basically, one way to see it as I have a cube (not forced to be a cube, really any collider) and a mesh collider. In the OnCollisionEnter I want to determine what triangles in the mesh collider collided with with what contact points from the collision. So lets say there are 100 contact points spread over 3 triangles approx equally, one possible thing to have would be a Dictionary where the key is a triangle, and there are 3 keys with values, and all the values would be something like a List of ContactPoints that have about 33 elements

jaunty sundial
ancient sable
#

so its similar, but I need them split up based on which specific triangle of the mesh collider they contacted with (so which 3 vertices are they contained within from my understanding of how it works. I haven't worked with meshes much)

#

And frankly, I dont even think I even actually need the contact points themselves. Just knowing what triangles is the most important part

jaunty sundial
leaden ice
jaunty sundial
#

So shod i do 1/100

leaden ice
#

So even trying to pass that value into the snap function is problematic

jaunty sundial
#

To be exact

leaden ice
#

There's no such thing as exact here

#

It's like trying to write 1/3 in decimal

#

You get 0.33333... repeating

#

In binary 1/100 and 1/10 are such numbers

#

What you should do is use integers to represent these values in the first place

jaunty sundial
#

How

lean sail
leaden ice