#archived-code-general

1 messages ยท Page 361 of 1

merry stream
#

should I use StreamReader for LoadData aswell?

soft shard
simple egret
errant flame
merry stream
#

what is the difference between ObjectPool.Dispose/Clear? cant find any documentation on it. Also, does anyone know what could be causing a null reference exception when clearing an object pool during a scene change?

somber nacelle
merry stream
#

okay, but I am trying to Destroy everything in the pool as well

#

not just release it

#

is that not what Clear does?

somber nacelle
#

my point is that you destroyed something that is in the object pool prior to calling Clear

merry stream
#

i see

somber nacelle
#

one way this could happen is if your objectpool is stored on a DDOL object but the pooled objects are not and you switch scenes. naturally everything that isn't DDOL will be destroyed

merry stream
#

yes that's exactly what's happening

#

so do I just not bother with clearing it?

somber nacelle
#

why not clear it before you switch scenes?

#

or just create a new objectpool instance so the old one gets GC'd

merry stream
#

well it's subscribed to SceneManager.sceneLoaded

#

so not sure the order

#

I will do that

somber nacelle
#

sceneLoaded is called when the new scene is loaded, so naturally that happens after the old scene is unloaded and all of its non-DDOL objects are destroyed

merry stream
#

got it

wintry jackal
#

Hi there!
I had some code that changed a sprite alpha. It worked all right.
But I created some animations for this gameobject that change the color of the sprite.
This animations are not played at the same time that the code changes the color.
But i'm guessing once you tweak the color of the sprite renderer from an animation, you cannot change it through code anymore (the same happens if you change the scale through animations and code, the code tops working)

Can anyone tell me if this is right? Also, is there any way to avoid it?

somber nacelle
#

that is correct. you can avoid this by controlling the sprite renderer's color in only one place rather than on both the animator and in code

merry stream
#

or do I NEED to make a new instance to remove all the null references

somber nacelle
#

no, why would it be? the object pool has no knowledge of scene loading

wintry jackal
twin yoke
#

do I have to reset the dynamic font asset when the game is closed?

dense yoke
#

    {
        MoveDirection = Orientation.forward * VerticalInput + Orientation.right * HorizontalInput;

        if(OnSlope())
        {
            rb.AddForce(GetSlopeMoveDirection() * MoveSpeed * 20f, ForceMode.Force);
        }

        if (Grounded)
        {
            rb.AddForce(MoveDirection.normalized * MoveSpeed * 10f, ForceMode.Force);
        }
        else
        {
            rb.AddForce(MoveDirection.normalized * MoveSpeed * 10f * AirMultiplier, ForceMode.Force);
        }
    }```why does it stop very abruptly when i touch a wall while i'm pressing a,w?
hexed pecan
dense yoke
#

no

hexed pecan
#

Are you going to elaborate? Lol

#

You aren't expecting to either wallrun (keep moving along the wall) or stop abruptly, so what do you need instead?

dense yoke
#

I don't want to do Wall Run, I just want it to run and walk, but I don't know why when I touch a wall when I press a, w or d, w it stops abruptly as if there was a wall in front of me.

hexed pecan
#

Then assign that to the rigidbody

#

And maybe set friction combine to min

dense yoke
#

Ok I'll try that, thanks

merry stream
#

at what point would you guys suggest implementing a dependency injection system? is it bad practice to hold some references (root gameobjects for enemies, loot, etc) on a gamemanager?

rigid island
frosty coral
#

how do i fix this

rigid island
frosty coral
somber nacelle
rigid island
frosty coral
#

spelt it wrong mb

merry stream
rigid island
merry stream
#

wdym

rigid island
#

in your ddol, you didn't make singleton ?
maybe use that instead of FindObject

merry stream
#

no no thats not what i mean

#

im saying getting references FOR the singletons

#

the player, root gameobjects to spawn enemies, etc

rigid island
#

ohh I mean if its a singleton just access the instance

#

there are some objects where i use an event tied to ActiveScene changed or SceneLoaded to pass reference through delegate

merry stream
#

i think youre misunderstanding. for example I have my enemy object pool. It needs a reference to a empty gameobject to parent the enemies to. Since it starts in a bootstrapper scene, these fields within the singleton are null until it gets to a certain scene. Right now, im just using GameObject.Find to find that empty gameObject to spawn the enemies on but i dont really like this way since it needs to check everytime the scene is changed

#

like it works completely fine but I feel it could get messy especially with wrong strings, etc

rigid island
#

hm yeah at least i would not use string / Find. where is the FindObjectOfType? mind as well slap that onto it

merry stream
#

well its just an empty gameobject so findobjectoftype wouldn't work

#

i could just make an empty class but eh

#

i dont like that either

rigid island
#

put a component or have something already in that scene hold reference

#

imo using a component is at least type safe

merry stream
#

true

errant flame
#

can i override plus minus list view button actions in inspector without touching whole inspector editor things

rigid island
#

and they are supposed to what exactly ?

#

doubt any way to do this without editor scripting

soft shard
storm wolf
#

I have a really dumb (probably) question.

So I am currently trying to make save system and I have this setup

    [Serializable]
    private class CoinData : Data
    {
        public int value;

        public CoinData(int val)
        {
            value = val;
        }
        public static CoinData Create(int val) => new CoinData(val);
    }

This is strictly just an example/test I have set up that saves just an int value. Essentially my saver/loader saves the Data type - the base class is literally just empty - my thought is that each saveable thing can derive from this to implement what it saves and then pass it through the save function that takes in a Data . all is well, I went through the debugger up until the point where it gets turned into JSON:

 string json = JsonUtility.ToJson(data);

 File.WriteAllText(dir + fileName, json);

after this writes to the file, instead of writing the derived CoinData class with its value (which I know it has right before writing) it writes an empty Data class and loses the value entirely. Does the JSON parser not support what im trying to do, am I doing something wrong, or am I just stupid. Help would be appreciated, thanks!

Both classes are [Serializeable]

wide terrace
storm wolf
# wide terrace How are you obtaining `data`?
    public static bool Save()
    {
        OnSaveGame?.Invoke();

        SaveData data = new SaveData();

        string dir = Application.persistentDataPath + directory;

        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);

        string json = JsonUtility.ToJson(data);

        File.WriteAllText(dir + fileName, json);

        Debug.Log("Saving Game");

        return true;
    }

and as of now I am using this in my constructor:

    public SaveData()
    {
        UnityEngine.Object.FindObjectsByType(typeof(GameObject), FindObjectsSortMode.None)
        .ToList()
        .Where(x => ((GameObject)x).GetComponent<ISaveable>() != null)
        .ToList()
        .ForEach(saveable =>
        {

            string id = ((GameObject)saveable).GetComponent<UniqueID>().ID;
            idToSaveableItems.Add(id, new(((GameObject)saveable).GetComponent<ISaveable>().GetData(), ((GameObject)saveable)));
        });
    }

heres the json:

{"idToSaveableItems":{"keys":["93f53778-351b-44de-b203-5f8ee2e3f5f4","08c14717-39a1-4a49-86e4-0d8e4641ded8"],"values":[{"Data":{},"GameObject":{"instanceID":31886}},{"Data":{},"GameObject":{"instanceID":31878}}]}}
wide terrace
storm wolf
#

correct

wide terrace
#

So I think the issue is that if you're serializing a reference to a Data, the only members available are those which exist on Data, even if the reference points to an instance of a derived class.

#

There might be a way to make it work using generics... though then you'd need to know the type of Data from within SaveData() ahead of time... hmm...

storm wolf
#

so what then make Data generic and then check for each type that T could be or like

#

damn that sucks ๐Ÿ˜ญ

wide terrace
#

Perhaps you could just have GetData() return the serialized data object?

#

oh but...

#

๐Ÿค”

storm wolf
#

yeah it wouldnt be Data anymore lol

#

im thinking about your generic proposal im not sure kind of approach I could take yet

#

[Serializable]
public class Data<T>
{
    public T data;
    public Data(T d)
    {
        data = d;
    }
}

thoughts on something like this

#

any chance that can get serialized

#

and then like


  public Data<CoinData> GetData()
  {
      return new Data<CoinData>(CoinData.Create(value));
  }

wide terrace
#

...maaaaybe? ๐Ÿ˜…

I think that might have the same issue in that SaveData() still wouldn't know the type, since all it knows is that ISaveable.GetData() returns a Data<T>

storm wolf
#

hmm you are probably right

#

any ideas?

wide terrace
#

Nothing terribly clean or concise... I'll play with something for a bit though and get back to you... I reckon someone else may have more useful thoughts on the matter ๐Ÿ‘€

storm wolf
#

okay ill play around with it too just @ me if you come up with anything appreciate the efforts

wide terrace
# storm wolf okay ill play around with it too just @ me if you come up with anything apprecia...

It sounds like Newtonsoft Json.net might be able to handle this sort of generic serialization/deserialization stuff with it's TypeNameHandling.Auto... Though it sounds like unless you include some sort of validation prior to deserialization, it could enable users to instantiate any type by modifying the Json.

Other than that, in my limited C# experience I don't see a way around using explicit types in at least half of the serialization/deserialization lifecycle ๐Ÿ˜ฆ

storm wolf
#

guess i will need multiple dictionaries ๐Ÿ˜ช

proven jasper
#

There's zero advantage to a json based approach if you dont actually want users to be able to view and edit save game data, might as well save the space and use binary then

#

Also as you said, Json.net will handle this fine

thin hollow
#

I'm not sure if I should be asking it here or in #โœจโ”ƒvfx-and-particles , but seems more like a code question than a particle system setup question...
How do you build pooling system for your particle effects? Or, rather, how do you store and apply particle system setting to particle emitters? I thought you can do it through presets, but it turns out they're UnityEditor and won't be accessible at the runtime.
So I'm not sure how to proceed, either I'll need to make a separate pool manager for every. single. visual. effect. in the game, or just say "fuck it" and instantiate game objects from a prefab ref each time, like a dirty peasant.
Neither feels like a correct solution.

wide terrace
# proven jasper Wanting to prevent user modification is directly at odds with using json at all ...

Oh, absolutely ๐Ÿ‘

The thought that crossed my mind is that if instantiating any type from such a file is enabled, it may be possible to craft an actually malicious JSON file... For things like save files which players may be inclined to share and assume to be innocuous data, that scares me a little bit.

But admittedly it's still probably not much worse than anything else which they might share

#

I guess it would probably also require some intimate knowledge of the game logic to actually do something malicious with those types

#

I'm likely overestimating the threat ๐Ÿ˜…

proven jasper
#

I know at the very least it throws up a warning if you enable this sort of object creation without some additional handling

#

Honestly, I never looked into it more than that though. My philosophy is more along the lines of tossing a disclaimer on the splash and then letting people compile text files to C# at runtime if they'd like

wide terrace
wide terrace
proven jasper
wide terrace
#

That does actually make it seem like validation could be somewhat more novel than I had in my head

radiant kindle
#

Hey, we are facing a crash on our live game and the stack trace is not really helping point to anything specific. Can anyone help me with which channel to post this query?

open plover
#

Is it possible to rotate 2d Colliders? I'm making a 3d top down game but its actually just a 2d top down game with 3d graphics in disguise, so it only requires 2d collision checking. Would be cool if I could just rotate my 2d collider 90 degrees

mellow sigil
#

You should instead rotate the entire game so that it's on the x/y axis

open plover
mellow sigil
#

Then you can't use the 2D physics engine

open plover
mellow sigil
#

nothing that would be reasonable by any measure

errant flame
#

if i add a custom property drawer there is no way to do that i guess do i need to implement also that logics

errant flame
#
        private void OnValueChange(SerializedProperty property, ChangeEvent<string> evt)
        {
            bool isInteger = int.TryParse(evt.newValue, out int value);

            property.stringValue = GPSelectionData.SerializeValue(isInteger ? value : evt.newValue);
            bool needToUpdate = property.serializedObject.ApplyModifiedProperties();
            if (needToUpdate)
            {
                property.serializedObject.Update();
            }
            Undo.RecordObject(property.serializedObject.targetObject, "property");
        }

i made a custom property drawer and use a text field , when i use CTRL-Z on native properties that undo system works well but not for custom ones , so i put a record state on value change callback but when i undo its performed well but there is no graphical changes on property how can i do that

i tried this but not worked after undoRedoPerformed i guess property or serializedObject getting null any idea ?

            Undo.undoRedoPerformed += () => EditorUtility.SetDirty(property.serializedObject.targetObject);
thin hollow
thin aurora
#

Even if you made a mistake in your code, it is unable to detail the issue and would rather return empty objects. Newtonsoft will actually inform you of the issue if there is one. Emphasis on if there is one because JSONUtility can even fail on correct code

#

Note by default Newtonsoft serializes properties, not fields. This is default with serializers so you will have to either add a property to serialize, or configure it to use fields.

wintry crescent
#

does anyone know if the .transform call is cached by unity? Or is it like getcomponent. It wouldn't make sense to not be cached

#

should I make my own cache or is it unnecessary

wintry crescent
knotty sun
wintry crescent
knotty sun
#

no

wintry crescent
#

good

#

thanks

cold parrot
# wintry crescent should I make my own cache or is it unnecessary

It forces a transition into unmanaged code which has a small overhead. If you use the transform in performance critical sections where the transform access is the actual bottleneck you can cache it to gain some performance, that benefit is however gone when you write to it. It would only be noticeable in fully data oriented systems that optimize for cpu cache friendly data access.

timber elk
#

im getting compile errors on this script :

cosmic rain
#

What errors are you getting?

#

Though, I feel like I know...

timber elk
#

how do i check (sorry im new)

gray mural
#

First of all, configure your !ide

tawny elkBOT
gray mural
#

Because the errors are not thrown to you

timber elk
#

ohh

cosmic rain
errant flame
#

@timber elk if(Input.GetKey(KeyCode.Space) && i == 1)

gray mural
#

Is there any difference between these 2 codes?

#if UNITY_EDITOR
    if (Application.isPlaying)
    {
#endif
        Method();
    }
#if UNITY_EDITOR
    if (Application.isPlaying)
#endif
    {
        Method();
    }
timber elk
#

thx

grizzled vine
#

I'll ask this in general I suppose:

I've been trying to optimize my AI recently, as, having 50 Navmesh Agents on screen at once right now, causes Frame Rate Drops. This is mostly due to the amount of NavMesh.CalculatePaths that I'm calling.

public bool CanReachPoint(NavMeshAgent inAgent, Vector3 inPoint) {
        NavMeshPath path = new NavMeshPath();
        NavMeshQueryFilter filter = new NavMeshQueryFilter {
            areaMask = inAgent.areaMask,
            agentTypeID = inAgent.agentTypeID
        };

        if (NavMesh.CalculatePath(inAgent.transform.position, inPoint, filter, path) && path.status == NavMeshPathStatus.PathComplete) {
            return true;
        }
        return false;
    }

At the end of the day, my goal is to find a location where the AI can move to around the player, but also, ensuring they can shoot the player from that position. As, my level design could have no path towards the player, but, they could still shoot the player from that location. The current steps I ended up taking, were basically at the start of a level I will build a bunch of "Tether Points" around the world which would update every X frames to check to see if the AI can shoot the player from that location. From there, they check every X frames if they can reach one of those points (Where the code above is.)

The problem I suppose, is, I'm not sure how to optimize it more? As the calculate path call seems heavy.

#

I guess I could, for example, check to see if the node is apart of the same Navmesh area? Im not sure if thats possible. But the idea being is, if Node A is on Navmesh Area 22, and Node B is on Navmesh Area 23, then checking if they can reach that point is valid. However, if Node A and Node B are both on Navmesh Area 22, there is no point in checking both, as its unlikely they can reach Area22?

cosmic rain
cosmic rain
grizzled vine
cosmic rain
grizzled vine
#

Anything specific you're wanting to see?

cosmic rain
#

Mainly what's taking most of the frame time, how much it's taking and how many calls are made.

grizzled vine
cosmic rain
grizzled vine
#

A lot of GC.Alloc's

cosmic rain
#

Yeah, so the issue is probably not the path calculations

grizzled vine
#

(Nothing else.)

cosmic rain
#

but GC.

grizzled vine
#

I'm not sure what would be causing the GC to build up like that then hmm.

cosmic rain
#

Share the FinisteStateMachine.Update code

grizzled vine
# cosmic rain Share the `FinisteStateMachine.Update` code
void Update() {
        if (healthSystem.isDead()) return;

        if (currentState != lastState) {
            if (lastState)
                lastState.Exit(this);
            if (currentState) {
                currentState.Enter(this);
            }
            lastState = currentState;
        } else {
            if (currentState.ExecuteTransitions(this)) return;
            currentState.Execute(this);
        }

        foreach (var item in stateMachineTimers.Keys.ToList()) {
            stateMachineTimers[item] = stateMachineTimers[item] - Time.deltaTime;
        }
    }
cosmic rain
#

One cullprit is definitely the .ToList()

#

That allocates a list each time.

#

assuming, stateMachineTimers is a dictionary, can't you just foreach a stateMachineTimers.Keys instead?

grizzled vine
cosmic rain
#

Work around it and profile again.

raven basalt
#

When I do poofParticles.Play();, I want the particles to only play once, I don't want it to continuously loop. For the ParticleSystem, the looping is unchecked. So I don't know why it continously loops:

whole plaza
#

Hey guys, is it possible to drag an animated object? I have a group parent with 2 sprites in it, but when i try to drag it, it doesn't work, but with static pictures it works
Here is the script:
``
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Drag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public void OnBeginDrag(PointerEventData eventData) {
Debug.Log("Begin Drag");
}

public void OnDrag(PointerEventData eventData) {
    Debug.Log("Dragging");
    transform.position = Input.mousePosition;
}

public void OnEndDrag(PointerEventData eventData) {
    Debug.Log("End Drag");
}

}
``

open plover
rough sorrel
grizzled vine
#

Though I assume that might be caused by ElementAt now.

night storm
cosmic rain
grizzled vine
vagrant blade
#

If the animation is animating the position of the object, it will override any changes you try to make.

Child the animation to a root object instead and drag the root object. This may require you to reanimate the child so that it's position is local space.

night storm
knotty sun
grizzled vine
grizzled vine
whole plaza
#

but it just doesnt work

knotty sun
grizzled vine
wintry crescent
#

and will everything work, if I just skip the allowSceneActivation thing?

knotty sun
wintry crescent
#

OH WAIT IM STUPID

#

no wait
after switching > to < it still doesn't work

grizzled vine
cosmic rain
#

It could be more than just that part

wintry crescent
#

After this coroutine is done, the scenes load endlessly and don't switch. What am I missing?

private IEnumerator LoadScenes(List<int> scenes)
        {
            if (IsLoading)
            {
                yield break;
            }

            IsLoading = true;
            List<AsyncOperation> loadOperations = new();
            for (int i = 0; i < scenes.Count; i++)
            {
                if (scenes[i] < SceneManager.sceneCountInBuildSettings)
                {
                    LoadSceneMode loadSceneMode = i == 0 ? LoadSceneMode.Single : LoadSceneMode.Additive;
                    AsyncOperation loadOP = SceneManager.LoadSceneAsync(scenes[i], loadSceneMode);
                    loadOP.allowSceneActivation = false;
                    loadOperations.Add(loadOP);
                }
            }   
            
            foreach (var operation in loadOperations)
            {
                yield return new WaitUntil(() => operation.isDone);
            }
            foreach(var operation in loadOperations)        
            {
                operation.allowSceneActivation = true;
            }
                Debug.Log("");
            IsLoading = false;
        }```
grizzled vine
cosmic rain
grizzled vine
#

Yeah was just about to try that.

#

Nope. For loop also causes it.

#

Hmm. Okay, its not from that. Profiler was just, wrong and isn't digging deep enough apparently. Commented out the rest of the code, manually set timers, and no GC.

cosmic rain
wintry crescent
#

I can see them loading in the inspector

#

operation.progress >= 0.9f instead of operation.isDone didn't fix the issue when list is bigger than 1

wintry crescent
grizzled vine
#

Yeah so, back to the

public bool CanReachPoint(NavMeshAgent inAgent, Vector3 inPoint) {
        NavMeshPath path = new NavMeshPath();
        NavMeshQueryFilter filter = new NavMeshQueryFilter {
            areaMask = inAgent.areaMask,
            agentTypeID = inAgent.agentTypeID
        };

        if (NavMesh.CalculatePath(inAgent.transform.position, inPoint, filter, path) && path.status == NavMeshPathStatus.PathComplete) {
            return true;
        }
        return false;
    }

It appears to be due to the Filter and Path as the leading cause of GC.Alloc. I still have SOME commenting it out, but, not nearly as much.

cosmic rain
wintry crescent
cosmic rain
cosmic rain
spare island
#

once progress is at 0.9

wintry crescent
spare island
#

unfortunately can't read the code on mobile

wintry crescent
#
private IEnumerator LoadScenes(List<int> scenes)
        {
            Debug.Log("Starting loading the scenes");
            if (IsLoading)
            {
                yield break;
            }

            IsLoading = true;
            List<AsyncOperation> loadOperations = new();
            for (int i = 0; i < scenes.Count; i++)
            {
                if (scenes[i] < SceneManager.sceneCountInBuildSettings)
                {
                    LoadSceneMode loadSceneMode = i == 0 ? LoadSceneMode.Single : LoadSceneMode.Additive;
                    AsyncOperation loadOP = SceneManager.LoadSceneAsync(scenes[i], loadSceneMode);
                    loadOP.allowSceneActivation = false;
                    loadOperations.Add(loadOP);
                }
            }   
            Debug.Log("Loading started");
            int s = 0;
            foreach (var operation in loadOperations)
            {
                yield return new WaitUntil(() => operation.progress >= 0.9f);
                s++;
                Debug.Log(s + " scene Loaded!");
            }

            Debug.Log("Loading ready");
            foreach(var operation in loadOperations)        
            {
                operation.allowSceneActivation = true;
            }

            Debug.Log("allowed scene activation");
            IsLoading = false;
        }
#

2 scenes are being loaded in this example

spare island
#

I'm assuming you're making a loading screen

wintry crescent
#

and it looks like this

#

ah wait I got an idea...

#

I'm stupid. It works now

#

had to move the allowSceneActivation to the previous foreach loop

spare island
#

I don't get why that works but if it does ๐Ÿ‘

whole plaza
#

can someone help me? I have animated sprites in a parent and i have dragging script. when i try to drag the parent, it doesnt work, but it should

rigid island
#

also !ask

#

๐Ÿ˜ข

gray mural
cosmic rain
gray mural
cosmic rain
#

Yes, the 2nd one is correct

tawny elkBOT
#

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐Ÿ”Žโ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696

gray mural
grizzled vine
#

God I hate GC.

rigid island
whole plaza
grizzled vine
tawdry jasper
#

I'm using a package from github, but wanted to tweak it a bit so just dropped it's source in my Assets/. The package has a namespace - the rest of my code doesn't. I can use the package code in mine no problem via adding a using statement. But I wanted to add variable of my monobehaviours into one of its definitions and I can't, I'm getting error CS0246: The type or namespace name 'RagdollController' could not be found (are you missing a using directive or an assembly reference?) The external code contains asmdef files (one for runtime and one for the editor part) is there a way I can edit the asmdef's to allow referencing my Asset/Scripts code?
(I think I could move the code into my Scripts directory and remove the included asmdef files, but maybe there's a right way to do it?)

spare dome
whole plaza
open plover
#

Unity doesn't accept this mesh

knotty sun
rigid island
#

o is it even code

spare dome
#

click my message above then scroll up

cosmic rain
open plover
rigid island
cosmic rain
cosmic rain
craggy falcon
#

hey, im following a tutorial for a natural-feeling character controller. ive copied the code exactly - the errror I am getting is relating to the MonoBehaviour part of the class. The class is public, the name is exact(yes, including capitalisation) and the script editor does not notice any errors. However, Unity won't let me add it to any gameobjects because, aparrently it doesn't derive from MonoBehaviour. Can somebody explain what I'm doing wrong here? ^^; it seems like it should work, but i just can't see any errors. I've copied working code letter for letter and i've checked 5 times, capitalisation throghout the script is exact.

(The script im working on is a custom InputManager script, and I've created a GameObject to attach it to called INPUT, again copying the tutorial to a T. I've done exactly what he's done, yet it isn't working and I don't quite understand why because as far as I can tell, everything is correct)

cosmic rain
rigid island
rigid island
#

dyno is asleep or sum

tawny elkBOT
cosmic rain
spare dome
knotty sun
spare dome
#

hey man the bot is working real hard for a payout of $0 an hour

open plover
rigid island
open plover
cosmic rain
# open plover

I don't know if it was different at the time of the tutorial writing, or it's simply a mistake, but you need to define the triangles. Look at the next section of the tutorial.

rigid island
#

please use links for large code as it was stated in the bot

open plover
#

I'm guessing I would need 2 triangles for a simple square?

craggy falcon
rigid island
#

do you have another class named PlayerInput

craggy falcon
craggy falcon
# knotty sun can you link the video

Show your Support & Get Exclusive Benefits on Patreon (Including Access to this tutorial Source Files + Code AND the State Machine version for this project) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH

--
Getting a jump to "feel good" is one of the most important things to get rig...

โ–ถ Play video
#

I've just followed the steps he's showing in order

rigid island
#

send link to script again, also yeah half the shit isnt even shown..not a fan of that style

open plover
craggy falcon
open plover
#

added this

rigid island
cosmic rain
grizzled vine
#

Yeah so I'm now back to the following code causing the problems:

public bool CanReachPoint(NavMeshAgent inAgent, Vector3 inPoint, NavMeshQueryFilter inFilter) {
        // if (NavMesh.CalculatePath(inAgent.transform.position, inPoint, NavMesh.AllAreas, path) && path.status == NavMeshPathStatus.PathComplete) {
        //     return true;
        // }
        return false;
    }

Commenting out the CalculatePath, the game runs perfectly fine/smooth. Using the NavMeshQueryFIlter which is cached on Start, causes more GC.Alloc to appear than using NavMesh.AllAreas. However, both cause massive performance hit.

rigid island
grizzled vine
#

The function gets called via:

public bool HasPossiblePoint(NavMeshAgent inAgent, NavMeshQueryFilter inFilter, AITargetSystem.ShootHeights inShootHeight) {
        foreach (var item in tetherPoints[GetHeightModifierAsFloat(inShootHeight)]) {
            if (item.canSeePlayer && CanReachPoint(inAgent, item.point, inFilter)) {
                return true;
            }
        }

        return false;
    }

Where I first check to see if they can even see the player from that point, before checking to see if they can reach it.

open plover
knotty sun
open plover
#

I better follow a guide cuz I had no idea how meshes worked prior to 10 mins

craggy falcon
cosmic rain
craggy falcon
#

okay, thanks for letting me know :)

grizzled vine
craggy falcon
#

OHH i got it

grizzled vine
rigid island
cosmic rain
craggy falcon
#

(I copy it but nothing pastes but what I previouslt had in my clipboard)

rigid island
craggy falcon
grizzled vine
open plover
rigid island
grizzled vine
cosmic rain
#

Also, capture it with deep profiling on.

rigid island
#

since each instance is another MB that needs to call backend code

cosmic rain
rigid island
#

ohh are they ? didn't see the full code , I just assumed from method but yea does seem to take Agent as param ?

storm wolf
cosmic rain
rigid island
#

I just had a crazy epiphany with MB recently through profiling and testing that , eager to share ๐Ÿ˜›

cosmic rain
# grizzled vine

It seems like HasPossiblePoint is what's allocating. Not the CanReachPoint

#

Also, it's allocating just 100 Byte. But you're allocating 12.7kb in total on that frame

#

This isn't even what's taking most of the frame time

grizzled vine
#

There are 50~ of these happening.

cosmic rain
#

Well, there's something really wrong with the way you structured your code and it's really hard to guess from the little pieces of info that you're giving us.,

#

None of the stuff in this screenshot is taking any considerable time.

#

You should Share more of the profiling data, sorted by cpu time and/or the gc allocations as well as the relevant code

languid hound
#

No idea if I'm being stupid but does anyone see something wrong with this coroutine? When I set my duration to something like 60 it only lasts a second

    public IEnumerator SmoothTransitionToZPos(float newPos, float duration)
    {
        float counter = 0f;
        float temp = 0f;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            temp = Mathf.SmoothStep(0, 1, counter / duration);
            zPos = Mathf.Lerp(zPos, newPos, temp);

            yield return null;
        }

        zPos = newPos;
    }
#

I've never used SmoothStep much so I don't know if it's something to do with that

#

I tried dividing the deltaTime that was added onto the counter as well but that gave the same result

rigid island
languid hound
#

How come?

rigid island
#

nvm actually, Mathf.SmoothStep is affecting it so you have to fix that first if its wrong . In example unity uses Time.time

craggy falcon
languid hound
#

I tried without lerp but it seems to go super fast with that too

#

Sorry not lerp I mean smoothstep

rigid island
#

yeah its not lerp, its smooth step

languid hound
#

I don't use smoothstep currently and the issue still occurs

rigid island
rigid island
languid hound
#

Literally just this. I'll try to use the method they use in that doc to elapse time though

    public IEnumerator SmoothTransitionToZPos(float newPos, float duration)
    {
        float counter = 0f;

        while (counter < duration)
        {
            counter += Time.deltaTime / duration;
            zPos = Mathf.Lerp(zPos, newPos, counter);

            yield return null;
        }
    }
rigid island
grizzled vine
craggy falcon
#

ah rats can't rename it

rigid island
#

you just put / duration in wrong spot

#

ur only dividing the time between frame not the accumulated value

cosmic rain
grizzled vine
cosmic rain
rigid island
#

is it trying to rename the other one as well ?

craggy falcon
# rigid island why not

it's just blacked out, alongside delete. I moved one elsewhere, deleted it, and then it replaced itself and it's as if it was never removed in the first place

rigid island
craggy falcon
#

and suddenly I'm getting errors now. I missed a semicolon, but it's telling me that there's still one expected on the line? which is so weird? since it's been updated and saved, ONE error is gone, but there's two others from the same line. damn Unity's not been my friend this week. I've failed 3 different setups. I really hoped this one would work.

cosmic rain
# grizzled vine Correct.

Okay, then one simple solution would be not to update all the agents every frame. Update one or several of them each frame. But to be honest, that many calls to calculate path are really unreasonable. Might be better to come up with a better system.

cosmic rain
# grizzled vine

It's also likely that the GC is contributing a lot to it. Might want to get rid of that 100 byte allocation.

rigid island
#

rename yours instead ofc

#

but that only renames the file

#

open the class and rename that using F2 it *should * rename the file too

grizzled vine
craggy falcon
#

huh... how come it'd let me edit it then? i find that very confusing Unity >:/ (nbh just realising after alot of research Unity has tonnes of non-specific errors and allow things that shouldn't be allowed sometimes lol.)

craggy falcon
rigid island
craggy falcon
#

it blows my mind how people can use Unity as if it's as simple as reading a book ๐Ÿ˜ญ i know one day I will reach that level of mastery, if only Unity had more specific errors and solutions lol

rigid island
#

eventually you will run into the same issues and you ~~slowly ~~ learn how to avoid them altogether

grizzled vine
craggy falcon
#

GOD i hope so. it's now telling me that the class can't be found. I've renamed it, COPIED AND PASTED the name, so I don't know how it can't match. AND it still has these line end errors depiste me fixing that one. god knows.

rigid island
cosmic rain
# grizzled vine Which was my original question... Lol I was trying to figure out a better System...

For starters, you can split the workload into several systems:

  • update several of the positions every frame and cache the state of whether the player is reachable/hittable from there. Maybe have a separate list of these positions sorted by most desireable(player is reachable) to less.
  • update several npcs every frame. If they need to move to a new position, check if they can get to the most desirable position first. If yes, break the looping and reserve the position.
craggy falcon
craggy falcon
ionic blaze
#

The class 'Editor' was depricated in the latest version of Unity (6.0.15), but the link in the release notes as to why wasn't put in. What should we be using instead of deriving from Editor? It's caused havoc in the project from all the editor scripts that derived from Editor. Anyone know how to handle this yet?

spare dome
cosmic rain
spare dome
craggy falcon
spare dome
craggy falcon
#

OH i fixed it. I had a mistype but the error did NOT specify that the word I had typed was "not an argument" or whatnot. It was talking about the END of the line wierdly enough

#

I have attached the script to the game object now. Hooray for indirect and non-specific unity errors! /sar /silly

#

thanks for your help guys - it was probably more than just that and what I was told has also helped for future projects. Thanks so much <3
Not gonna be the last you see of me though lol. Sure i'll see you soon!

grizzled vine
# cosmic rain For starters, you can split the workload into several systems: - update several ...

I do the first already. The first is if they can shoot the player. This takes my Tether Point count down from 500~ to 140~. So thats already cutting the number of possible points up. I'm also only checking the points that are within Camera View (As they can technically only shoot the player when in Camera View.)

Every X Frames is what I'm doing as well in this case. Though its possible this is bugged looking into it a little bit more right now.

And lastly on your other comment about Game Design: Enemies can change their position, however, only after X seconds. Otherwise, they move, stop for X seconds while attempting to shoot the player there, then move away.

cosmic rain
grizzled vine
#

Right, you're talking more about staggering them.

cosmic rain
cosmic rain
grizzled vine
#

Staggering/Spreading it throughout all the frames.

And 140 Points aren't heavy at all.

cosmic rain
#

Even if you update one out of 50 npcs every frame, updating all of them is less than a second at 60 fps. The player wouldn't be able to notice any difference, unless they have access to debug info and see exactly when the decision of each npc is made.

cosmic rain
#

Anyways I'm off to sleep.

ionic blaze
storm wolf
# thin aurora Consider switching to Newtonsoft. JSONUtility sucks and you should not use it ap...

Hey so I have switched to newtonsoft. Everything saves correctly. The problem before was it was saving the Data class as just empty. This time it does SAVE the data correctly, but the data gets lost when it is loaded.

{"idToSaveableItems":{"08c14717-39a1-4a49-86e4-0d8e4641ded8":{"value":66789},"93f53778-351b-44de-b203-5f8ee2e3f5f4":{"value":1423}}}

heres the json that is in the file, but when the json gets converted back into a SaveData this is what I get:

(cc @wide terrace ) #archived-code-general message

grizzled vine
#

At the end of the day, is it possible to check what Navmesh Section a point is on? Take for example these two areas. If a agent is unable to reach the bottom right corner of the navmesh, they are obviously unable to reach anywhere else on it due to the navmesh gap shown inbetween the red and the purple.

If its possible to know if a point is apart of the red navmesh vs the purple one, I feel as if I could improve performance greatly in this case.

grizzled vine
odd void
#

i want to implement a third person camera wich looks at the player when moving the camera, it works on the x-axis but not the y-axis... what can i change about my code?

https://hastebin.com/share/jerikujeba.csharp

knotty sun
storm wolf
#

Save/Load system parsing issue

grizzled vine
knotty sun
lean sail
grizzled vine
north vine
#

does anyone else experience bugginess when using gameobject arrays in inspector? i have to restart my editor whenever i want to add something to an array, is there a workaround?

north vine
gray mural
# north vine

Works fine on my device. What exactly is not right for you?

north vine
gray mural
gray mural
#

And it's not fixed every time?

north vine
gray mural
#

Why do you ask the question if it's fixed?

north vine
gray mural
#

The majority of Unity bugs are fixed by reloading Unity once

gray mural
#

Please, show the code

#

Is it a simple array of GameObjects?

north vine
gray mural
#

The issue is probably in one of your packages

north vine
gray mural
storm wolf
#

Or try upgrading your editor version too if looking into the packages doesnt work

knotty sun
lean sail
#

Thatd imply no collision avoidance on other agents though

knotty sun
north vine
knotty sun
#

definitely, 2022.3 was not stable before .11

craggy falcon
#

why would this code need a comma? Error is telling me Syntax error, ',' expected

[Range(0f, 1f)] public float HeadWidth 0.75f; (From an earlier post in #๐Ÿ’ปโ”ƒcode-beginner)

#

0.75f; is underlined red but im not sure what the error is?

knotty sun
#

did you configure your IDE?

spare dome
#

you need an =

#

before the 0.75f

craggy falcon
knotty sun
craggy falcon
# spare dome before the `0.75f`

Oh. thanks, i missed that. it's not in his code and his doesn't have an error! man im noticing these tutorials must have something that nullifies their errors. it's been like 3 different tutorials that seem to show no errors when they're coding when there are mistakes i've had to correct in mine before

#

god my mind slipped that

#

(plus why can't Unity tell me i'm missing an equals sign ๐Ÿ˜ญ over a comma)

spare dome
knotty sun
#

because. following C# syntax, it thinks you are trying to decalre 2 varaibles rather than one and 2 variables would be seperated by a comma

craggy falcon
#

ahh right.

north vine
stone echo
#

Having trouble figuring out tweening for my project. I have a camera that zooms in and out on button press using tweening over 0.2seconds (zoomto is a tween call):

gray mural
#

Is it possible to get the distance between the Vector2.zero and Vector2.right anchors in local coordinates without reassigning the anchors twice or enumerating through every parent's parent?

stone echo
rigid island
gray mural
gray mural
rigid island
#

oh wait I think I misread what you're asking

gray mural
rigid island
#

not sure what that means, wouldnt you just store it in a var ? then change anchor min and max, assign pivot then use old pos again

tacit lance
#

I'm aware this is super niche, but I'm kinda just playing around with what I might turn into a package later.
I have a scriptable object that allows you to add elements to a list, and some data associated to each element. They are then stored in a dictionary to be accessed in runtime.

Obviously, later accessing specific things through code by indexing the dictionary by their name is super error prone, and something to avoid. In an ideal world, I would be defining the keys in an enum instead, but in the interest of making it a standalone package I'd like it to be possible to define things with little to no code.

This brings me to: is it possible to use source generators to generate an enum with variants according to the scriptable object? Is this an acceptable solution? Is there a better one?

knotty sun
#

tbh using a source generator for something this trivial is a bit of overkill

primal raptor
#

how do I make the texture random

cold parrot
craggy falcon
#

ugh man. So i followed the guys code, completed it. One error.
I'm getting what is said to be the most common of all - "object reference not set to an instance of an object". It has prevented anything I have coded from working.

I have my InputManager(named PInputManager) where the error is supposedly. I will link the code now.

Reminder, I've followed this guy's code exactly. I don't understand what's wrong.

#

I hope it's understandable that I'm confused. Anything I find on this says "Find what's null, find why it's null" but I'm not too sure why it's null. Movement is brought up a few times throughout and VS isn't finding any issues. Whatever this is has completely stonewalled the rest of the code. Nothing works, I can't move the character whatsoever. Shall I just restart hours of work? Or is there a super simple solution I'm not seeing/can't find?

#

The comments to the tutorial do no good either. nobody else in the comments have had this issue but me

somber nacelle
#

your PInputManager is probably not attached to a GameObject that also has a PlayerInput component

craggy falcon
#

I have attached it, just now. no change

somber nacelle
#

are you reading the first error in your console?

#

also when you attached it, you did so outside of play mode then tried it again, right? you didn't just attach it during play mode after the error appeared and expected it to magically call Awake again, right?

craggy falcon
craggy falcon
somber nacelle
#

show the exact error message

#

also you are following a terrible tutorial if it is telling you to make everything static just to access the values from the input

craggy falcon
craggy falcon
somber nacelle
#

well it's terrible if that is how it wants you to set things up. don't abuse static just for easy referencing

craggy falcon
#

alright, i didn't know, sorry

somber nacelle
#

put this line on line 23: Debug.Assert(PlayerInput != null, $"PlayerInput is null on {name}", this);

craggy falcon
#

i was simply following the tutorial, that's it

craggy falcon
#

oh wait im stupid sorrry

#

blind that is

somber nacelle
#

oops i missed a t in the method name

craggy falcon
somber nacelle
#

obviously the one with the error where you have a PlayerInput variable

craggy falcon
#

i was gonna finish this and go to bed like an hour ago but then ADHD kicked in realising it would just... not be working so im running on a single marshmallow from like 30 minutes ago

somber nacelle
craggy falcon
#

i would probably be like this anyway since im a little newer to how C# works, but im also just wanting to get this done. i've been working at different styles of player movements for absolute days and this is the one im closest to finally managing since it turned out my software was out of date because my PC is due a fix.
I'm not too unfocused to comprehend instructions, im just a bit cautious in case i ruin it more since in the past that's how it's been - i'm so close to managing this. I only wanted a bit of help/an explaination, sorry if that's an issue or anything, im not a total beginner but when i've been trying to fix 1 thing for hours i kind of have to resort to help at some point

somber nacelle
#

okay well have you bothered adding the line i suggested so we can see what is going on?

craggy falcon
#

im working on it, on top of helping a friend with something

#

debug is a new concept to me, i'm assuming the {name} field is where i'd put the "move" in the line i got an error on in right?

#

it's different to the other code im used to with debugging so i'm just making sure

somber nacelle
#

you don't change anything at all, you just copy/paste it exactly as is

craggy falcon
#

it uh... almost froze my computer, wow

#

gdi my memory just maxed out

#

hang on i gotta shut some things down and try that again

somber nacelle
#

that is entirely unrelated to the Debug.Assert call

craggy falcon
#

i know, my computer just has some memory maxing issues, as i'd mentioned it's due a fix up soon

#

i just have to restart. common daily issue i'm having as of late

#

okay im gonna have to restart my computer. whole taskbar is duplicating anything i do over and over. brb

#

On startup. will check again shortly

craggy falcon
somber nacelle
#

it's supposed to print another error before the one that was already happening

craggy falcon
#

That has not happened, just the error that was originally there

somber nacelle
#

show the full stack trace for the error then and screenshot the *inspector for * the object that this component is attached to

craggy falcon
#

i'll copy+repaste incase i accidentally added/removed anythig then give that a go

#

Okay, looking up how to find the full stack trace and it seems people have been having to manually enable it in more recent versions of Unity? Anything I find on it says that. I'm confused.
Im a little more versed in older versions of Unity but this is different than it used to be. I had to do this once before a few years back and it was easy.

#

How do i go about finding full stack traces for errors? (might help for the future too. im still learning)

somber nacelle
#

just click the error message and look at the extended information for it in the console

craggy falcon
#

i am clicking it. and right clicking it. nothing changes unless I double click it, where it just takes me to my code editor. it doesn't dropdown, for whatever reason

craggy falcon
somber nacelle
#

screenshot your entire console window then

#

with that error message selected

craggy falcon
#

this is it. i have clicked it. in every place i can

#

it just repeats it below.

#

which doesnt change on clicking,

somber nacelle
#

and just to be clear, you did save the code and let it recompile to test with the Debug.Assert call, right?

craggy falcon
#

yes, thats when my computer froze. i re-pasted in case anything went wrong keyboard-wise, saved, and let it recompile since it didn;t get a chance.

somber nacelle
#

and you put it on line 23 like i asked and not perhaps after the line that is throwing the exception?

craggy falcon
#

just so you know I know how all this works, I know how coding software and game engines work. Unity and C# are just newer to me, and the way it debugs. I'm used to a visual novel maker, which uses the same save/manual reload/etc etc.

#

yes.

somber nacelle
#

okay well i'm still waiting for you to show the inspector for the object with that component on it

craggy falcon
#

was only trying to sort out the first issue.

#

this is exact to the tutorial, too.

somber nacelle
#

i guarantee it is not because you missed a step

#

compare what the tutorial's Player Input component looks like with what yours looks like, you missed something

craggy falcon
#

i am beginning to realise how non-specific unity errors are, eventually i'll learn what it could be... unity seems to like to keep things a mystery and make things difficult for learners. lol

#

but, im willing to learn

#

let me check. though i did check several times, i'll check again. sometimes it's that ooone check that does it

craggy falcon
somber nacelle
#

in the inspector

craggy falcon
#

ah. there we go. one thing he didn't mention

somber nacelle
#

yes, there's also a helpful message in your screenshot that should have made that fairly obvious

craggy falcon
#

i'm aware, but i was not looking at his inspector before since he just briefly swung past it and didn't mention anything needed adding

somber nacelle
#

sure but your inspector is the one with the helpful message telling you that nothing had been assigned

craggy falcon
#

again, unity's errors are pretty vague i've noticed. it takes me to a line in a script when the issue's sat in the inspector on a different app.
i think my issue is that the software I'm used to is alot more specific with it's errors and what percisely is wrong, and where it is. The engine is entirely coding a game, without all of the assets and stuff like Unity. So that's probably why I'm a little more confused with this than what I'm used to

craggy falcon
#

issue is, he says nothing of what that item is, what it contains or where it's even stored...

somber nacelle
#

like i said before, it's a bad tutorial.

craggy falcon
#

i'll figure out from here im sure. thanks

#

well it's better than the other ones i've used - this is the only one left with a single error that i can fix

somber nacelle
#

it's teaching terrible coding practice and apparently not explaining what it is doing, so if that is somehow the only one you've found that you can follow, then perhaps start smaller

craggy falcon
#

i have tried, but again, this is the only one that's actually a) been one I'm almost able to complete and b) does what I want

#

I'm not making anything too serious out of this. im simply going to just learn from it - examine the working code, learn what makes it tick, what does what, etc

#

then i can just find other ways implementing the same kind of logic down the line as I learn more

#

it's how I did it with the other program anyway

somber nacelle
#

if the tutorial isn't explaining any of what it is doing, then how do you expect to learn from it? also you're learning how to do things the wrong way anyway. so it's just overall a shit tutorial that you won't learn anything useful from

#

but if you want to continue with shit tutorials instead of learning how to do things the proper way, you do you. i won't be helping you further

craggy falcon
craggy falcon
somber nacelle
#

you're the one insisting on following a terrible tutorial that is teaching you incorrectly just because you can't comprehend other tutorials because you also refuse to start smaller like was suggested. there are beginner courses pinned in #๐Ÿ’ปโ”ƒcode-beginner
start with those if you don't want to learn how to do things correctly

craggy falcon
#

okay, jeez. i was only practicing and fiddling around and wanted a bit of help. i'll continue fiddling around with other code and such. im not refusing anything, i want to finish what i've spent hours on before moving onto something else. i don't really see why that's an issue - everybody's different. I'm just learning, analysing and experimenting in my own way and asking for help along the way. you really don't have to be rude about that.
thank you for the suggestions.

#

i'll probably just find some resources and then leave the server. I don't exactly feel welcome here with the way you've said some things in a patronising manner when all i needed was a bit of help and guidance. just seems to be a progammer server thing - if one does not know all, one is not worthy of knowledge. it's been every programming server i've been in, and i have had to learn two other languages by myself without outside help like these servers because everybody just seems annoyed that im asking for help. I will find ways to learn outside of this server. It doesn't feel like a productive environment to learn after looking through some chat history. It just feels like other toxic enviroments i've found myself in. Thanks for the help, but i'll find my own way out from now own. clearly this was not the right way to go about finding help.

#

we were all beginners once, but it just feels like a sin in the programming community to be a beginner or someone who doesn't know every corner of something, even a little bit. its not just here but Ren'py and some HTML servers ive been in too. and not just with me. I've sat back and watched it happen. In forums and everything. Maybe i'll just stick to myself from here on out

#

again, thanks for the help. farewell

somber nacelle
# craggy falcon i'll probably just find some resources and then leave the server. I don't exactl...

if one does not know all, one is not worthy of knowledge
considering that is literally the opposite of what i'm saying, you're just bitching just to bitch at this point.
my entire point is that the resource you are currently using to learn from is teaching you incorrectly. the knowledge you gain from that will only hinder your development because it is wrong. I pointed you to resources that would actually be beneficial to you. but if you're just going to cry about being bullied because i'm pointing out that you refuse to actually learn how to do things correctly then i am absolutely blocking you. i don't help people who actively refuse to learn.

tacit lance
#

This is a stupid question, and I have no idea where to ask this, but...
When the inspector has the * to indicate unsaved changes, how do I save? I've just been selecting different things to force the inspector to switch to something else and open the dialogue to save or discard lol

#

Surely there's a keybind or something?

somber nacelle
#

things like asmdefs (like what is in your screenshot) have an Apply button to apply changes. also not a code question

tacit lance
somber nacelle
rugged grove
#

is it against the rules to offer to pay someone for help with coding in this disc

spare dome
tawny elkBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โ€ข Collaboration & Jobs

ivory pasture
#

how do i interact with drawn tiles on a tilemap in runtime? as in stretching existing tiles like a square tool

cosmic rain
ivory pasture
#

unfortunately ๐Ÿ˜”, i figured out a workaround with CellToWorld though, so at least i could get a list of the cell positions

swift falcon
#

Hello friends, I have a question about the Particle System in Games. What is the best way to create Particles for the game? Should I learn Unity Particle System or do you recommend a 3rd party program?

stable osprey
#

Anyone knows why it freaks out at angles near -90 even if I use the proper way? Here's my code:

IEnumerator AttackWithSword() {
    canAttack = false;
    Debug.Log("Started"); // Verified this only runs once

    var t = 0f; // Raise the sword up slightly -- charge the attack
    while ((t += Time.deltaTime) < chargeTime) { sword.eulerAngles = sword.eulerAngles.WithX(Mathf.LerpAngle(-90, -110, t / chargeTime)); yield return null; }

    t = 0f; // Drop the sword down in a slashing motion
    while ((t += Time.deltaTime) < dischargeTime) { sword.eulerAngles = sword.eulerAngles.WithX(Mathf.LerpAngle(-110, 15, t / dischargeTime)); yield return null; }

    t = 0f; // Recharge and bring the sword back to its original position
    while ((t += Time.deltaTime) < 0.5f) { sword.eulerAngles = sword.eulerAngles.WithX(Mathf.LerpAngle(15, -90, t / 0.5f)); yield return null; }

    canAttack = true;
}
#

I've verified that LerpAngle returns the correct angle, but the actual value in game is still janky. Same if I use ..rotation = Quaternion.Euler(..); or just use localEulerAngles

#

... and same if I just add 360 to all negative angles like so: Mathf.LerpAngle(360 - 90, 360 - 110, t / chargeTime)

mossy snow
stable osprey
mossy snow
#

don't do your rotations in world space; don't read from eulerAngles; store the initial local rotation and modify that using Quaternions (see Quaternion.AngleAxis)

stable osprey
#

I currently fixed by keeping the Y and Z components locked so it won't freak out, but I couldn't make it work with Quaternions since my animations are in EulerAngles and Quaternion.Euler didn't work

var (t, originalAngle) = (0f, sword.eulerAngles); // Raise the sword up slightly -- charge the attack
while ((t += Time.deltaTime) < chargeTime) { sword.eulerAngles = new(Mathf.LerpAngle(-90, -110, t / chargeTime), originalAngle.y, originalAngle.z); yield return null; }

t = 0f; // Drop the sword down in a slashing motion
while ((t += Time.deltaTime) < dischargeTime) { sword.eulerAngles = new(Mathf.LerpAngle(-110, 15, t / dischargeTime), originalAngle.y, originalAngle.z); yield return null; }

t = 0f; // Recharge and bring the sword back to its original position
while ((t += Time.deltaTime) < 0.5f) { sword.eulerAngles = new(Mathf.LerpAngle(15, -90, t / 0.5f), sword.eulerAngles.y, sword.eulerAngles.z); yield return null; }
mossy snow
#

that looks like the same code, just without using your extensions

stable osprey
#

the difference is that this one uses originalAngle instead of currentSwordAngle

mossy snow
#

but you're still reading from sword.eulerAngles every frame

stable osprey
#

no, that's inside a coroutine and originalAngle is initialized only at the beginning. Sorry for the weird formatting

mossy snow
#

the last while loop reads sword.eulerAngles.y and .z on each loop, so it has the potential to glitch out. And you're still doing the rotations in world space which is weird to me unless your player is absolutely locked into place with no chance of turning, moving, or getting hit

stable osprey
#

yeah that's fine I think since the object rotates.. and the reason it works is the angle.x never surpasses -90, so the quaternion can only be read one way

#

how would you suggest doing it with a quaternion multiplication and local space?

mossy snow
#

unless you know a lot more about how Unity has implemented its rotations than I do, that seems a weird and bad assumption to make. There are multiple ways to represent any euler rotation

stable osprey
#

would ideally like to have it work with abstract rotation/just follow the parent's rotation (the sword's rotation except the X axis), so totally interested in doing that

while ((t += Time.deltaTime) < chargeTime) {
    LookAt((target.position - transform.position).WithY(0)); // What I would have liked to work. but doesn't cause of cached angle
    sword.eulerAngles = new(Mathf.LerpAngle(-90, -110, t / chargeTime), originalAngle.y, originalAngle.z);
    yield return null;
}
#

hm I guess I could use .forward = like always, since the sword's end always points forward ๐Ÿ˜†
.forward never failed me and this is the first time I need this weird thing.. just thought it'd be quicker to make the animation prototype via code lol little did I know

something along the lines of Quaternion.LookRotation(desiredSwordForward, -transform.right)

#

๐Ÿฅณ thanks @mossy snow

LookAt((target.position - transform.position).WithY(0)); // Rotate towards the target
var desiredForward = Quaternion.Euler(Mathf.LerpAngle(0, -20, t / chargeTime), transform.eulerAngles.y, transform.eulerAngles.z) * Vector3.up;
sword.rotation = Quaternion.LookRotation(desiredForward, transform.right);
#

literally not a clue why this works and what would I have to do to change it.. just bruteforced it.. definitely need more coffee for this

mossy snow
#

you shot yourself in the foot again by reading from euler angles, and you're still doing world space rotation. Did you try rotating your test cylinder around +Y?

stable osprey
#

yeah it works on seemingly all angles ๐Ÿ˜ Open to finding better ways though, I currently don't like the fact it takes 2 lines and still isn't really readable lol

mossy snow
#

does sword have any parent transform?

stable osprey
#

Sword's parent is the test enemy

#

I know my setup is doomed.. was really hoping for 5 min prototype before slapping in assets/anims but then math got the better of me

stable osprey
royal marlin
#

Is it still not possible to configure two actions for a single-click (using the Press interaction) and a double-click (using the Multi-Tap interaction) on the same button without writing custom logic such as a coroutine? I'm using Unity Input System version 1.8.2, and have activated the flag for pre-empt actions. Independing of the settings, the single click is always notified.

knotty sun
#

do not cross post

leaden ice
#

Btw the press interaction is not necessary most of the time

stable osprey
# stable osprey ๐Ÿฅณ thanks <@155166991408168960> ```cs LookAt((target.position - transform.posi...

@mossy snow with some adjustments I made a horizontalAttack variant as well ๐Ÿ˜†

var t = 0f; // Tilt the sword backwards slightly -- charge the attack
do { AnimateSwordRotation(-50, 20, t / chargeTime); yield return null; } while ((t += Time.deltaTime) < chargeTime);

t = 0f; // Swing the sword towards the middle in a slashing motion
do { AnimateSwordRotation(20, -100, t / dischargeTime); yield return null; } while ((t += Time.deltaTime) < dischargeTime);

t = 0f; // Recharge and bring the sword back to its original position
do { AnimateSwordRotation(-100, -50, t / rechargeTime); yield return null; } while ((t += Time.deltaTime) < rechargeTime);

// Helper methods
Vector3 GetSwordAngle(float angleY) => Quaternion.Euler(0, angleY, 0) * transform.right * (rightHanded ? 1 : -1);
Quaternion GetSwordLookRotation(float angleY) => Quaternion.LookRotation(GetSwordAngle(angleY), transform.up);
void AnimateSwordRotation(float lerpMin, float lerpMax, float currentT) {
    if (!rightHanded) { lerpMin *= -1; lerpMax *= -1; }
    sword.rotation = GetSwordLookRotation(Mathf.LerpAngle(lerpMin, lerpMax, currentT));
}
#

not ideal since I don't have full control of the angles there but happy this works so far.

stable osprey
# stable osprey

Context for anyone game-math-savvy: I'd like to animate the sword as shown here, but ideally in a way that'll allow me to work directly with local angles without relying on hacks like transform.up/right to acquire the rotations. Issue with code above is that it's a pain to include other axises in the animation. I don't really have to include them, but it'd be nice.

knotty sun
lean sail
#

the transforms would store everything directly, and lets you visualize it in inspector.

gray mural
#

Also, you can create an IEnumerator, if dealing with more your-like approach

private IEnumerator AnimateSwordRotation(float lerpMin, float lerpMax, float time)
{
    float t = 0f;

    yield return new WaitUntil(() =>
    {
        AnimateSwordRotation(lerpMin, lerpMax, t / time); 
        return (t += Time.deltaTime) > time;
    });   
}
#
yield return AnimateSwordRotation(-50, 20, chargeTime);
yield return AnimateSwordRotation(20, -100, dischargeTime);
yield return AnimateSwordRotation(-100, -50, rechargeTime);
stable osprey
gray mural
#

So, you prefer repeating yourself as much as possible?

stable osprey
stable osprey
#

e.g.: for vertical attacks, the helper methods were these:

#

very slightly different than the ones for the horizontal attacks, but require different code anyway

gray mural
stable osprey
#

I'd like to turn this in a unified system that could straight up animate from/to any angle without needing new code

stable osprey
#

-- or meant to say it lol.. sorry, I'm kinda sleep-deprived

lean sail
gray mural
#

I don't think animator can be used when the player chooses how to wield the sword themselves

lean sail
#

nothing being done here needs to be done this way. Id even first opt for using empty game objects as a start/end point for these "animations" before whatever this is. But it most defintitely can be done via animations or at least animation rigging

stable osprey
#

yeah pretty sure my issue was chaining logic & making modular animation sequences -- nevermind injecting some parts into the animation (like timed thrust in this case)

open plover
#

How can I make the mesh collider on the floor align

hard estuary
errant flame
#
    [CustomEditor(typeof(GPNodeData))]
    public class GPNodeDataDrawer : Editor
    {
        public override VisualElement CreateInspectorGUI()
        {
            VisualElement defaultInspector = new VisualElement();
            InspectorElement.FillDefaultInspector(defaultInspector, serializedObject, this);
            defaultInspector.Add(new Label("asd"));
            return defaultInspector;
        }
    }

Does anyone know why i cant add extra label to defaultInspector in this block ?

hard estuary
errant flame
#

@hard estuary I just want to make this if node type is selector than i need to add 2 selection data fields more to that block what is the easiest way to do that add property drawer on NodeData class or add custom editor or something to SO script

#

if i was get it i can use custom editor on only mono and so files right ?

hard estuary
errant flame
#

@hard estuary I would like to say that I am a little confused, how can I reach the goal I want to reach in the shortest way as I explained on the visual?

hard estuary
# errant flame <@313011730525585415> I would like to say that I am a little confused, how can ...

Try this:

    [CustomPropertyDrawer(typeof(GPNodeData))]
    public class GPNodeDataDrawer : PropertyDrawer
    {
        public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            VisualElement defaultInspector = new VisualElement();
            InspectorElement.FillDefaultInspector(defaultInspector, property.serializedObject, this);
            defaultInspector.Add(new Label("asd"));
            return defaultInspector;
        }
    }
errant flame
hard estuary
# errant flame In FillDefaultInspector last parameter want an editor instance that not accpect ...

I should've checked it before sending it. ๐Ÿ˜“ After making several attempts, don't think there is a way of drawing the default property drawer. base.CreatePropertyGUI returns null, other ways either miss something or draw everything recursively. But there is a chance I'm missing something.

I think I would just draw every property by hand. It's more work (especially if you have a lot of fields/properties), but at least it's a stable solution.

errant flame
#

i guess i move forward with custom editor window for that and draw everything one by one with my ui elements and bind them to the serialized properties other methods wont work at least i cant

#

yea I agree with you ๐Ÿ˜„

tame smelt
#

I built my unity application and distributed it. People are able to play the game with windows. However, with windows 7 and 8 specifically, the following error is appearing for them: DllNotFoundException: FirebaseCppApp-12_0_0.

I appreciate any help on this as I tried so many things and searched the internet but no luck

#

Unity is not able to find this although in the game files it does exist

knotty sun
tame smelt
#

its just Unity C#, no other scripts

#

with compression method of default

knotty sun
#

SO you don't know how you built your project

tame smelt
#

I am trying to understand you question

knotty sun
#

it's simple enough, Unity has several options to build your code with, which ones did you use

tame smelt
#

the default one, I tried other compressions as well

knotty sun
#

try
Project Settings->Player->Other Settings->Configuration

tame smelt
#

alright

knotty sun
#

So you are using Mono and .Net Standard 2.1 which is not supported by Windows 7 or 8

tame smelt
#

I see

#

what versions can support them if you don't mind me asking

knotty sun
#

.Net Framework, you can try Mono or IL2CPP

tame smelt
#

thanks

knotty sun
#

Just make sure your Firebase plugin supports .Net Framework, you may need to replace it with an OLDER version

tame smelt
#

hmm thats true thanks for that

knotty sun
#

fyi the framework version you are looking for, if required is 4.7.2

tame smelt
#

alright

ivory pasture
#

how do you draw the circle made from physics2d.overlapcircle?

knotty sun
ivory pasture
#

wow, well that's unfortunate

#

thanks for the info though

knotty sun
#

yes it does and is against server rules

haughty lance
#

ah, sorry

#

should i delete the message or

knotty sun
haughty lance
#

there we go

ivory pasture
#

what's the use of Vector2 direction in CircleCast?

night storm
ivory pasture
#

there's already Vector2 origin, float radius, where is the direction supposed to go to?

night storm
ivory pasture
#

oh my god ๐Ÿคฆ, thanks for the explanation

undone leaf
#

why is W moving me backwards and s moving me forwards here?

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

public class SpaceshipControl : MonoBehaviour
{
public float moveSpeed = 20f;
public float rotationSpeed = 100f;
public float mouseSensitivity = 1f; // Sensitivity for mouse look
private float pitch = 0f; // Current pitch angle
private float yaw = 0f; // Current yaw angle

void Update()
{
// Handle movement forward and backward
float moveDirection = Input.GetAxis("Vertical");
transform.Translate(Vector3.forward * moveDirection * moveSpeed * Time.deltaTime);

// Handle rotation left and right (Yaw)
float rotationDirection = Input.GetAxis("Horizontal");
transform.Rotate(Vector3.up, rotationDirection * rotationSpeed * Time.deltaTime);

// Handle pitch up and down (using E and Q)
if (Input.GetKey(KeyCode.E))
{
    transform.Rotate(Vector3.right, -rotationSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.Q))
{
    transform.Rotate(Vector3.right, rotationSpeed * Time.deltaTime);
}

// Adjust speed dynamically
if (Input.GetKey(KeyCode.W))
{
    moveSpeed += 1f * Time.deltaTime; // Increase speed
}
if (Input.GetKey(KeyCode.S))
{
    moveSpeed -= 1f * Time.deltaTime; // Decrease speed
}

}
}

hard estuary
undone leaf
#

how do I rotate it without making it face a diferent direction?

spring creek
#

You have to make sure the model is rotated in the right direction before exporting it from blender or wherever

undone leaf
#

understood

hard estuary
#

The model is facing the right direction, if it's the same as the blue arrow here.

#

Moving it forward will move it in the same direction as blue (Y axis) arrow.

undone leaf
#

didn't work

#

it was working before, but it just kind of stopped

hard estuary
#

It's also worth noting, that the transform's Forward is a local variable.

hard estuary
# undone leaf it was working before, but it just kind of stopped

How is your Vertical Input configured? If it includes W and S, then it will change both direction and speed. In such case, if your speed becomes a negative number, then the movement will be reversed (because negative moveDirection multiplied by negative moveSpeed will result in a positive value).

spiral palm
#

how would i press a button in code?

#

like emulate the press function

spring creek
hard estuary
spring creek
#

Hmm, write a wrapper function, have the input call that function, or call it externally

Ah, a ui button

spiral palm
#

yes

#

i have a render textue which im using to emulate button presses and i need to tell a button to act like it's pressed

#

(it's a render texture because the menu is rendered onto a 3d mesh

stone echo
#

Having some trouble with async scene loading, heres my script:

#

but when I check my hierarchy, GameScene is loading forever

#

if I remove the allowSceneActivation=false, the scene switches to GameScene immediately, but with the allowSceneActivation=false, it doesnt actually preload, does anyone have any ideas what could be causing this?

#

For the record, when I press PlayGame (when the async.allowSceneActivation=true is uncommented), it finishes loading the scene

#

but not asynchronously^

merry stream
#

im having issues with simultaneous couroutines bypassing my cooldown system. For example, two different abilites share a cooldown, this works fine when one ability is pressed within a few ms of the other, but when I hold both keys, both abilities are used at the same time, bypassing the cooldown check. I believe this might have something to do with how couroutines function? not sure. This also occurs when I activate both abilities sequentially in an update loop. It seems the cooldown isn't being checked for the 2nd ability and is applying it second time

merry stream
cosmic rain
# merry stream

Debug the longestCooldown here before returning. Then reproduce the issue and see what value it has.

leaden solstice
#

Are you trying to do Unreal GAS on Unity

merry stream
craggy oyster
merry stream
#

the cooldown is being checked twice since its checked before input and after activation

craggy oyster
#

how would i setup a script to disable a component of type i dont know?

cosmic rain
# merry stream

Step through that method to see why longest duration remains 0.

cosmic rain
craggy oyster
#

is there a way to do this without getting the type of the component

cosmic rain
craggy oyster
#

i need to do this for my inventory system

#

i cant disable my items because i need to get references for them

#

so im opting to disable the components that make them an item instead

merry stream
cosmic rain
merry stream
cosmic rain
craggy oyster
#

all items are childrens of the player

#

and all are disabled

#

until you equip them use them etc.

cosmic rain
#

Or on an inventory component if you have one.

craggy oyster
craggy oyster
cosmic rain
cosmic rain
craggy oyster
#

i can sense it

cosmic rain
#

Wat, why adding a new field would make problems?

craggy oyster
#

it wouldnt be organized for one

#

if want to make a new item for my game with my plan i just create it and make it a child of the player

cosmic rain
#

Wdym..? How is it organized now if you even don't have a reference to your items??

craggy oyster
#

it will be once i figure that out ๐Ÿ˜…

merry stream
#

therefore, it allows it through and applies another identical cooldown

cosmic rain
craggy oyster
#

see i didnt have to do all that thnks steve

cosmic rain
#

And if it doesn't, that probably means that you don't yet apply cooldown at that point.

merry stream
#

i dont see how thats possible since the first ability should complete beforce the second one is activated

cosmic rain
merry stream
#

thats why I thought it was a couroutine issue but i could be completely wrong

cosmic rain
#

It is most likely. I see that you're yielding in several places. If the cooldown is applied after the yield, it would happen on the next frame.

#

While the other ability is started on the same frame.

#

That's just an assumption though. You need to debug properly

merry stream
#

i believe you're right, ill continue debugging but could yield new WaitForEndOfFrame solve the issue?

cosmic rain
#

No, that would have the same problem, as the other ability would start right away, before the end of frame. Honestly, I don't see why you need to yield there in the first place.

merry stream
#

where?

cosmic rain
#

In TryActivate. That's the only code you shared that has yield return.

merry stream
#

they are all couroutines since some abilities are done over time

#

im not sure how i could avoid using them

cosmic rain
#

I don't think basing the whole system on coroutines is a good idea. But that yield return in itself is not the problem. The problem is where you apply the cooldown. You should apply it right away when the ability is passing the can activate check.

merry stream
cosmic rain
merry stream
#

so using Time.time within loops etc

cosmic rain
#

Wdym?

#

What loops?

merry stream
#

update loop

cosmic rain
#

Mmm... Yes, but I'm not sure we're on the same page.

#

I'd have something like an AbilityManager plain class instance on the player controller. And I would call it's Update method from the player controller MonoBehaviour.Update. The AbilityManager would then in turn call the update of any active ability that it manages.

merry stream
#

hm, thats completely different to how i have my whole system setup so not sure

#

i fixed the issue by doing this but now of course pre activate won't work since it wont wait for it to finish

cosmic rain
merry stream
#

why is it a bad idea exactly? just for the issue i was having or are there other issues that might come up down the line?

#

i still dont really see how your suggestion would achieve the same effect though

cosmic rain
#

The issue that you were having is a symptom that it's going in a wrong direction. Coroutines have many limitations, like them being canceled as soon as the executing object is disabled. It can also be confusing how unity chains coroutines and in what order it executes what. If you update the abilities yourself, you have full control of that and don't need to delegate anything to unity and hope that it does it correctly.

cosmic rain
merry stream
#

being able to abstract whatever preactivation the ability may use and wait for it before activating the ability itself

cosmic rain
#

Sure, super easy.

merry stream
#

but yeah i do see that you could avoid coroutines

cosmic rain
#

Just have a state machine in the ability with state like PreActivate, Updating, Ending or something and call the corresponding virtual methods.

merry stream
#

let me try it

#

something like this?

cosmic rain
# merry stream something like this?

No. Why does the state machine need to be in the TryActivate. It should be in Update or something. TryActivate should just make a check and set the ability state to Started/PreActivate or something. And probably set the cooldown as well.

merry stream
#

this is not a monobehaviour

cosmic rain
#

It doesn't need to be. I already covered the update part in details a few messages ago.

merry stream
#

i see

cosmic rain
#

PlayerController.Update => AbilityController.Update => all active abilities update.

#

Anyways, I'm off to sleep. Good luck.

merry stream
#

thanks

#

good night

leaden solstice
#

If you are not doing multiplayer it could be much simpler

merry stream
#

my system is not as complicated as GAS

#

its just to have modularity and ability to make stuff with the inspector

#

i do need a system like this though since my game is and APRG similar to path of exile etc

#

it would be a nightmare to calculate everything cleanly without it

toxic vault
#

Is there a way to programmatically decrease shadow quality in URP? I have baked shadows using bakery and use mixed for my character and enemies.

I want to add a graphics settings allowing to have both realtime and baked on, only baked (disable all realtime) and another option to disable all shadows (realtime and baked)

frosty coral
elfin tree
#

I'm using the Unity Splines package and I can't figure out how to set all the knots tangents to auto at runtime (through code)
The knots (and the spline) are being generated at runtime from transforms and I'd like to smooth out the result

Edit: Using spline.SetTangentMode(TangentMode.AutoSmooth) does an okay job but is limited, wondering if there's more tweaking possible

solar wigeon
#

!code

tawny elkBOT
solar wigeon
#

https://gdl.space/luxuwedobe.cs hello i am having this problem where my raycast isn't working basically it dose not render the hit is not getting counted i feel like the error is here

     private bool OnSlope()
    {
        //first perfome a raycast to see if the player is hitting the slope
        if(Physics.Raycast(transform.position, Vector3.down, out slopeHit, playerHeight * 0.5f + 0.3f))
        {
            float angle = Vector3.Angle(Vector3.up, slopeHit.normal);
            return angle < maxSlopeAngle && angle != 0;
        }

        //if it dosent hit anything
        return false;
    }
    private Vector3 GetSlopeMoveDirection()
    {
        return Vector3.ProjectOnPlane(moveDirection, slopeHit.normal).normalized;
    } ```
craggy oyster
#

hey i was using scriptable objects to define data for my guns

#

and now that im making an inventory system i realized it doesnt work for my situation as different guns using the same scriptable object would not work

#

what solution is there?

vagrant blade
#

Create a different SO definition for each gun?

craggy oyster
#

you mean making a new SO for each duplicate of the gun?

vagrant blade
#

No, you create a unique SO for each unique kind of item/gun, and when you spawn that item, you use that SO definition to set it up.

craggy oyster
#

yea i know that works great but what happens when you have two of the same gun as an item

#

they will share each others data

vagrant blade
#

Well, you should have one item with a Quantity property set to 2

#

But if in your case you have unique ones, just count them. Have items store a reference to the SO they're using, so you can iterate and count.

craggy oyster
vagrant blade
#

Because you can show the item in your inventory with X2 on it? Otherwise, I don't understand what your actual issue is.

craggy oyster
#

ok

vagrant blade
#

I'm going off "I realized it doesn't work for my situation" where you don't actually describe said situation.

craggy oyster
#

omg im so stupid

#

i dont know why im even trying to do this

#

i was using SO's to handle all gun information like damage ammo and etc

#

so when i had two guns of the same SO they would share the ammo

west lotus
#

So real qucik queation. i have a SO that holds a list of a class and that class holds a list of other SOโ€™s. Im trying to parse the second level soโ€™s from a file. It works but in the inspector it says type missmatch and the data does not survive domain reload. I suppose I need to actually create the editor assets right?

craggy oyster
#

when i can just make the ammo variable local to the script

#

๐Ÿ˜ญ

merry stream
#

is there a way to use physics2d to draw a quarter circle or something similar to simulate a sword slash. Right now im just using overlap circle to take a circle some distance infront of the player but the shape is off

#

if not, what way is generally used

somber nacelle
#

overlap circle to get all objects in a circle around the area you'd like to check. then loop through them and use something like Vector3.Dot to determine how close they are to straight ahead of the object (or the direction of the slash) they are, if they are within some threshold apply the damage

merry stream
#

great thanks

west lotus
#

The answer was yes I need to actually create the scriptable object assets first

winged magnet
#

hey guys, long time unity dev, but bad at math and low level gfx

#

im trying to have a dynmaic cuboid

#

and i have the mesh working.

#

but i can seem to get the uvs right

#

basicly i want it locked to ints for 1 unit mesurment, and have the same probuilder style texture on all sides

#

ive try a few things, even asked chatgpt for help. but i cant seem to get all the sides uv's proper

#

any help would be very appericated

sturdy thorn
#

Hello! I'm having an issue in my game... I have the player (blue) and a key which opens the door. The player must grab the key with the spacebar and keep it pressed to carry it. Everything seems correct but when I go to another scene the player is okay but the key wouldn't follow. What can I do?

spare dome
#

well lets see some code

#

remember to do your !code like this

tawny elkBOT
spare dome
#

ah the bot is working now ๐ŸŽ‰

sturdy thorn
#

oh!

spare dome
#

you gave me a player controller?

sturdy thorn
#

Player

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

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;
    public LayerMask floorLayerMask; // Set this to the layer your floor colliders are on
    public float checkDistance = 1f; // Distance to check for the floor

    private void Start()
    {

    }

    private void Awake()
    {
       


    }

    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        Vector3 direction = new Vector3(horizontal, 0, vertical).normalized;
        Vector3 newPosition = transform.position + direction * moveSpeed * Time.deltaTime;


        if (direction.magnitude >= 0.1f && IsFloorBelow(newPosition))
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.Euler(0, targetAngle, 0);

            Vector3 moveDirection = Quaternion.Euler(0, targetAngle, 0) * Vector3.forward;
            transform.position += moveDirection * moveSpeed * Time.deltaTime;
        }
    }

    bool IsFloorBelow(Vector3 position)
    {
        Ray ray = new Ray(position + Vector3.up, Vector3.down);
        return Physics.Raycast(ray, checkDistance, floorLayerMask);
    }
}

sturdy thorn
spare dome
#

i dont see anything about a key

#

or scene

#

wait

sturdy thorn
#

PickUp

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

public class Pickable : MonoBehaviour
{
    private Transform playerTransform;

    public bool isYKey;

    private void Start()
    {
        playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Collider[] hitColliders = Physics.OverlapSphere(transform.position, 1f);
            foreach (var hitCollider in hitColliders)
            {
                if (hitCollider.gameObject.CompareTag("Pickup"))
                {
                    GameManager.instance.SetPickedObject(hitCollider.gameObject);
                    hitCollider.transform.SetParent(playerTransform);
                    hitCollider.transform.localPosition = Vector3.zero;
                    break;
                }
            }
        }
        else if (Input.GetKeyUp(KeyCode.Space))
        {
            if (GameManager.instance.GetPickedObject() != null)
            {
                GameObject pickedObject = GameManager.instance.GetPickedObject();
                pickedObject.transform.SetParent(null);
                pickedObject.transform.position = playerTransform.position + playerTransform.forward * 1.5f;
                GameManager.instance.SetPickedObject(null);
            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if(isYKey && other.CompareTag("GateY"))
        {
            Destroy(other.gameObject);
        }
    }
}
spare dome
#

so what does this have to do with a key not following player into another scene

#

also please use a bin site

#

for big code blocks

#

!code

tawny elkBOT
sturdy thorn
#

Change Scene

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


public class Go : MonoBehaviour
{
    public string sceneToLoad; 
    public Vector3 playerSpawnPositionInNewScene;

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            GameManager.instance.SetPlayerSpawnPosition(playerSpawnPositionInNewScene);
            SceneManager.sceneLoaded += OnSceneLoaded;
            SceneManager.LoadScene(sceneToLoad);
        }
    }

    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        GameManager.instance.SpawnPlayer();
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }
}
sturdy thorn
spare dome
#

my suggestion is to spawn the key again on the player when in new scene

#

if you know they would have it

sturdy thorn
spare dome
#

when loading into a new scene you can check if a player had a key or object then spawn the key again on the player, or you can just spawn key on player when entering new scene if you know that the player already has a key

warm aspen
#

For scalability I would try to make a system that stores whatever the player is carrying at the moment and loads it on the next scene with the player. Then it can work with other items and makes opportunity for other level design choices in the future

sturdy thorn
#

okay, will try

#

thanks!

long scarab
#

hey there, i'm making a resolution dropdown for my game's settings and was wondering if theres a simple way to filter Screen.resolutions by aspect ratio? i could make a predetermined list and call indices from there, but it would be nice to grab available refresh rate from the player's machine

waxen jasper
#

Do skyboxes work in 2D URP? I've read they don't yet there seems to be documentation on it and haven't had any luck

lean sail
leaden ice
worldly hull
#

i know unity default video player is AVfoundation

#

but somehow it seems that this built in features is encrypted and i cant access any codes regarding to this

#

which is normal tho, u cant access the engine source code anyway

#

the problem is, the video player is not working as expected in M2 silicon imac

#

is there an alternate way for me to change the code without using another video player?

thick terrace
worldly hull
#

like at least i need to access the script file for the video player

lucid hollow
#

Do someone know why the object dont destroy itself even if the value is the right value ?

  {

      if (GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Coincounter>().currentCoins == 1)
      {
          Destroy(gameObject);
      }
  }
knotty sun
gray mural
lucid hollow
#

i mean i try and he is not but i dont knwo why

gray mural
#

Well, it's not the problem with the Destroy method

#

Also, I don't know what you mean by "i try and he is not"

queen saffron
#

Hi, is it possible to create highlight effect on Game Object Elements (Vertices and Faces) in runtime without deconstruct the object into seperate vertices and faces of each one describe a complete entity of vertex or face?
like assigning individual face to unique color

lucid hollow
lucid hollow
gray mural
gray mural
lucid hollow
#

the object stay in the scene and in the game when current coins get a value of one

lucid hollow
gray mural
lucid hollow
#

i'm stupid i don't know why y was using trigger the colison was to upgrade the current coins score but not the method to destroy it

#

so my problem is resolve thanks you all

lean sail
chilly surge
#

Is there an editor tool for monitoring UnityWebRequest? Something like browser dev tool network tag, where you can inspect each request, headers, payload, response, timing, etc.

gray mural
#

Is it possible to check whether a type is serializable in Unity's Inspector? Type.IsSerializable returns True if System.SerializableAttribute is added, but despite returning true for decimal, its serialization is not supported by Unity

#

So, I have an Inspector for generic struct, and I want to check whether the type is serializable, because, otherwise, it throws an error in GetPropertyHeight

late lion
#

But you could copy the class, if you don't find any other way.

gray mural
chrome mural
#

helo :>

#

i need help :<

vagrant blade
tawny elkBOT
#

:thinking: Asking Questions

:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐Ÿ”Žโ”ƒfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696

chrome mural
#

i have a path

#

a bezier path

#

i store the curve data into 2 List<Vector2>

#

List<Vector2> anchorPoints
List<Vector2> controlPoints

#

how do i make something move along :<

#

i have the formula for the bezier

#

but it works for 2 anchor and 2 control points!

#

i have many ๐Ÿ˜ข

indigo tree
knotty sun
#

you can query a Bezier curve for any point along the curve

chrome mural
#

altho the bezier formula looks something like this

#

Bezier(anchor1, anchor2, control1, control2, t)

knotty sun
chrome mural
#

yes

#

tho this are 4 curves in the photo

knotty sun
#

I meant that is what you feed in, it will return the necessary point

chrome mural
#

how do i know if the thing is on 1, 2, 3 or 4

knotty sun
chrome mural
#

wat

static matrix
#

how can I refer to a button in its script?
i have this code:

public void MenuNav(GameObject Activate){
        gameObject.SetActive(false);
        Activate.SetActive(true);
    }

on a script im using to hold all the functions for my buttons on the menu, but when I place it on a button and click, it turns off the buttonlogic object, not the button
how can I make it turn off the button clicked?

#

ofc I could just make another script

indigo tree
static matrix
# chrome mural wat

its one curve, and its defined by the four points

1+2+3 is just one number, defined by three numbers

static matrix
#

ill just make a different script though, it'll be faster

chrome mural
#

Movement along Bezier

indigo tree
static matrix
#

well of course I could do that, but that means creating a new variable whenever I want to make another menu screen

indigo tree
#

Trying to avoid boilerplates and such?

static matrix
#

well i'd like to avoid adding an additional script component to every single button I have that disables itself
its cool, I just opted to do that instead, really not that bad

chrome mural
indigo tree
static matrix
#

ah
ok

#

ill look into that

chrome mural
#

plz help ๐Ÿฅน

static matrix
#

help with what????

#

what do you need to know

static matrix
#

you have one bezier

#

comprised of four (actually looks like its five) points

#

five is a single number
composed of five ones

chrome mural
#

wat

knotty sun
static matrix
#

beziers (to my knowledge) look at the points and angles you've provided it, and creates a curve

chrome mural
static matrix
#

bezier shouldn't take a specific number of points, it should be able to use as many as it needs?

chrome mural
#

this is 1 bezier curve

static matrix
#

correct

spare dome
#

yes thats how beziers work

chrome mural
#

so i can make a formula with as many points as i need?

#

ahhh

#

silly me

#

im tired

static matrix
#

im not sure
but that bezier clearly has two points
(unless the green dots are also counted as points)

static matrix
knotty sun
#

Ah, finally, the penny dropped

vagrant blade
#

At this point, you should just use Unity's spline package

chrome mural
#

and its just overkill for what i need also

spare dome
#

better to use spline then

static matrix
#

forumists on their way to tell people that doing anything by yourself is a terrible idea:

spare dome
#

a challenge is not what you want

static matrix
#

well you can use spline if you want
probably more powerful
but if your are more comfortable manually making the curves, then do that

vagrant blade
#

Challenging yourself is fine, as long as that's all it is. It isn't the approach if it's also being used as progress to complete something.