#💻┃code-beginner

1 messages · Page 129 of 1

queen adder
#

Hey fen u seem to be good with physics could help me with something?

slender nymph
#

() to call a method

frosty hound
#

.GetComponent<NavMeshSurface>();

slender nymph
#

but also, just make your navMeshObj variable a NavMeshSurface. you don't need to reference the GameObject just to call GetComponent on it, just reference the component directly

queen adder
#

On line 12 put a [SerializeField] infront of private

coarse compass
slender nymph
queen adder
#

Public or private with a [SerializeField] it doesnt matter

swift crag
#

Unity would be really miserable to use if you couldn't do that.

#

You can drag any unity object into a serialized field

coarse compass
#

An object yes, but not a component that sit on another object. boxfriend is saying that we can but I dont see how.

languid spire
#

a Component is an Object

swift crag
#

Are you trying to reference a scene object from a prefab?

#

we need more context

coarse compass
swift crag
#

No.

#

many things are unity objects

#

GameObject, MonoBehaviour, ScriptableObject, ...

queen adder
swift crag
#

every Component must be attached to a GameObject

#

perhaps that's what you're thinking of

queen adder
#

No matter what i set the gravity scale to the bomb explosion makes the character fall at a really fast speed

coarse compass
#

Ha ok I thought object = GameObject, I come from Blender so that kind of made sense but I see the difference now.

swift crag
queen adder
#

I know this is simple as hell but i can not figure out how to fix it

languid spire
swift crag
#

sounds like you need to look at PlayerMovement, then

languid spire
#

!code

eternal falconBOT
swift crag
#

share the entire script in a paste site

queen adder
swift crag
#

the player movement script, I mean

queen adder
swift crag
#

If gravity scale isn't doing anything, then there must be something else changing the player's velocity

coarse compass
#

Ok I finally understand that by dragging a GameObject to a public variable initialized to a specific type it figure out by itself that I want the component of that type on that GameObject. Is that correct?

queen adder
#

I know im just sharing both for context

swift crag
#

You can also drag a specific component, but that's more annoying, since you need two inspectors up (unless you're dragging between two things on the same GameObject)

coarse compass
#

Cool, thanks everyone

swift crag
#

I almost never store GameObject references

#

only when I literally just want to turn something on or off

coarse compass
#

Yeah it would have felt annoying to reference a GameObject and then have to get the component on that GameObject within the script

#

I'm glad this work this way it's much easier

swift crag
hidden sleet
#

Yeah to kept trying to drag the actual script component from other game objects into the inspector, being able to just drag the object itself is a lot nicer

queen adder
#

Its the animation

#

I figured it out

swift crag
#

ah, yes, that'll do it

queen adder
#

Theres an animation event i realised once he was actually in the air

plucky vapor
#

I want to update the NPC's name with the name given to it. How do I do that?

#

This is the default

hybrid tapir
#

whats the playstations share button called in the new input system

vast ivy
#

my scriptable item script:

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

[CreateAssetMenu(fileName = "Item", menuName = "Scriptable Objects/Item")]
public class ItemSO : ScriptableObject
{
    public string name;
    public string description;
    public Sprite icon;
    public GameObject prefab;
    public enum ItemType
{
    Resource,
    Tool,
    Weapon,
    Consumable,
}
    public int stackCurrent = 1;
    public int stackMax;
}
#

when an object is picked up using another script, it collects the ItemSO info on that item, which then I can add it to the inventory (have to remake this)

soft steppe
vast ivy
#

yea im pretty new too, started maybe a week or 2 ago

soft steppe
#

also can anyone rate this code for me?

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public class LevelData
{
    public int ID;

    public string Name;
    public GameObjectData[] gameObjects;

}

[System.Serializable]
public class GameObjectData
{
    public int id;
    public float x;
    public float y;
}

public static class LevelManager
{

    public static void SaveLevel(LevelData levelData, string LevelFilePath)
    {
        string dataPath = Application.dataPath;
        string levelDataPath = Path.Combine(dataPath, LevelFilePath, ".dat");

        List<LevelData> levels;

        if (File.Exists(levelDataPath))
        {
            BinaryFormatter Bformatter = new BinaryFormatter();
            FileStream stream = new FileStream(levelDataPath, FileMode.Open);
            levels = (List<LevelData>)Bformatter.Deserialize(stream);
            stream.Close();
        }
        else
        {
            levels = new List<LevelData>();
        }

        levels.Add(levelData);

        BinaryFormatter newFormatter = new BinaryFormatter();
        FileStream newStream = new FileStream(levelDataPath, FileMode.Create);
        newFormatter.Serialize(newStream, levels);
        newStream.Close();
        
    

        
        
    }
    public static List<LevelData> ReadLevelFile(string LevelFilePath) {

        string dataPath = Application.dataPath;
        string levelDataPath = Path.Combine(dataPath, LevelFilePath, ".dat");
        List<LevelData> levels = new List<LevelData>();

        if (File.Exists(levelDataPath))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(levelDataPath, FileMode.Open);
            levels = (List<LevelData>)formatter.Deserialize(stream);
            stream.Close();
        }
        else
        {
            Debug.LogWarning("Level data file not found.");
        }

        return levels;
    }

    private static void _LoadLevel(Scene scene, LevelData levelData)
    {
        if (scene.name == "Level")
        {
            foreach (GameObjectData goData in levelData.gameObjects)
            {

                GameObject prefab = Resources.Load<GameObject>(new string("Prefabs/GameObjects/GameObject_" + goData.id.ToString()));
                
                GameObject go = GameObject.Instantiate(prefab, new Vector3(goData.x, goData.y, 0f), Quaternion.identity);
                
                
            }
            SceneManager.sceneLoaded -= (scene, mode) =>
        {
            _LoadLevel(scene, levelData);
        };
        }
    }
    public static void LoadLevel(LevelData levelData)
    {
        SceneManager.sceneLoaded += (scene, mode) =>
        {
            _LoadLevel(scene, levelData);
        };
        SceneManager.LoadScene("Level");
    }

}



#

simple 2d level manager for user made levels

charred spoke
soft steppe
#

anything else i shuld change?

frosty hound
#

Does this code work?

short hazel
#

Use using statements when dealing with file streams, so they're closed automatically even if you return early or an exception occurs

soft steppe
#

not years

frosty hound
#

So does the code work?

soft steppe
#

like 10 months

soft steppe
charred spoke
#

I cant compile the code in my head, if it works it works. You might want to look into using the adressables system rather than loading objects from the resource folder, use a proper GUID rather than a id in the name of the object and I dont like the _ in the method name since it does not follow convention

hybrid tapir
#

how do i have it log it just once and have it update the log msg for however many seconds the button is pressed

frosty hound
#

Also, you can have same named functions provided their parameters are different (as with your two LoadLevel functions)

soft steppe
short hazel
#

Lambdas don't need braces where there is only a single instruction in them

SceneManager.sceneLoaded += (scene, mode) => _LoadLevel(scene, levelData);
hybrid tapir
charred spoke
# hybrid tapir dang

You can toggle collapse in the console window and then then same msg will have a counter

soft steppe
#

but anyway the only usefull part is loadlevel cuz the rest has security risks

short hazel
#

The unsubscription does nothing

swift crag
#

yes -- it does reference equality, iirc

#

I usually just write a named function at that point.

#

(it can still use the => syntax!)

#

Although, this won't work if you need to capture some local variables for that lambda.

coarse compass
#

How would you distribute points randomly on a mesh surface? I'm trying to spawn entities on the navmesh according to a set density per square meters. Is there a built in function for this somewhere?

#

I found this answer but this seem like a lot of code for something so ubiquitous in video games. https://community.gamedev.tv/t/good-way-to-dynamically-and-randomly-spawn-on-navmesh/230492

late burrow
#

how do i make function that edits existing variable rather than putting it inside function

#

like string.replace

short hazel
#

Replace returns a new string, it does not edit the string you pass in-place

late burrow
#

yes just i put it variable.function not function(variable)

short hazel
#

The answer is, it depends on the type of the variable you need to modify

#

what

#

Well to be able to do that, you need to add the method inside of the type (in the class)

#

Then you'll be able to call it on an instance of that type

swift crag
#

uniformly choosing from a point on an arbitrarily complex mesh isn't easy

#

You can pick a random triangle from the mesh and then pick a random point in that triangle

#

but that's biased towards small triangles

timber tide
swift crag
#

I guess you could add up the areas of all navmesh triangles, then use those to do a weighted random choice

#

it's how a lot of things work :p

#

foo.Bar() is calling Bar on whatever object foo contains

teal gulch
swift crag
#

Yeah, if you're asking how to add a method to an existing type, that's the way to go

distant robin
#

hi why unity keeps giving me this error? NullReferenceException: Object reference not set to an instance of an object
CollectableInteraction.StartInteraction (UnityEngine.Transform objectToInteract) (at Assets/CollectableInteraction.cs:64)
CollectableInteraction.Update () (at Assets/CollectableInteraction.cs:35)

NullReferenceException: Object reference not set to an instance of an object
CollectableInteraction.StopInteraction () (at Assets/CollectableInteraction.cs:88)
CollectableInteraction.Update () (at Assets/CollectableInteraction.cs:26)

my code works fine.

#

its very annoying

eternal falconBOT
coarse compass
timber tide
swift crag
#

It'll also take a random amount of time, so it's not perfect

#

(we'd call this "rejection sampling")

timber tide
distant robin
slender nymph
#

what about that do you not understand

slender nymph
distant robin
swift crag
#

did you go through all of the topics linked on that page?

#

read them.

distant robin
#

fixed that guys

#

thank yall

hybrid tapir
#

why doesnt this set it to 0.0?

vast vessel
#

hey guys. i have it if val1 or val2 are null my function returns false, but im still getting a null refrance exception. why is that?

slender nymph
hybrid tapir
#

but it doesnt go back to 0 before starting again

short hazel
slender nymph
hybrid tapir
#

oh

#

how do i have it wait a few frames

slender nymph
#

if timer is true, set timer to false and timePassed to 0. then you immediately check if timer is false

lofty sequoia
#

If you Destroy() a gameobject that has child gameobjects, is Destroy called on the child gameobjects? Or are they garbage collected later on? What happens to the child gameobjects?

vast vessel
slender nymph
short hazel
vast vessel
tall delta
short hazel
#

It can be true, but it's unlikely

summer stump
tall delta
#

weeeeeelll ok, sure, some people do win the lottery

#

if you want to be pedantic about it 😄

summer stump
hybrid tapir
#

im trynna make it log it only every half a second

tall delta
#

that's not a discussion worth my time

summer stump
short hazel
#

Haha actually you'll hit 0.5 if you get 30 frames at exactly 60 FPS, ignoring the float precision issues

tall delta
#

that's a big thing to ignore 😅 but yeah, the math works out

swift crag
#

It actually works out in your favor!

#

Lots of ways to wind up with exactly 0.5

tall delta
#

eh, maybe 10-15 ways? a trillion ways to not get it. also, you only get one chance to check, and that check is also based on user input

hybrid tapir
#

im trying to hold the button and have it only log once every half a second but this time its instantly going to 999

timber tide
#

ya need to add some time contraint otherwise you're probably logging every update loop

#

look up timer tutorials or how to set a cooldown

tribal pendant
#

do I need to open a ticket to ask a question?

summer stump
tribal pendant
#

can someone help me figure out why the player's velocity gets set to 0 when i touch the ground after falling? and why I get stuck with my head when I touch the platform?

slender nymph
#

show your code

late burrow
#

i do be setting gravity to 0 when on ground so i wont be constantly rolling down on near flat surfaces

late burrow
#

perhaps too low terrain bounciness

tribal pendant
#

this is the code, most of the variables are in italian tho , i can tralsate if oyu need claryfying

slender nymph
#

!code

eternal falconBOT
tribal pendant
tribal pendant
late burrow
#

make new physic material and drop it on collider material

amber spruce
#
public void TakeDamage(float damage)
{
    Debug.Log("TakeDamage");
    if (playerController.isBlocking)
    {
        damage = damage / 4;
    }
    else
    {
        currentHealth.Value -= damage;
        animator.SetTrigger("Hurt");
        Debug.Log(damage);
        if (currentHealth.Value <= 0)
        {
            Die();
        }
    }
}

so i get the first debug but i dont get the second anyone know why i also dont deal damage

tribal pendant
late burrow
#

ofc

#

make it amount you need

rich adder
slender nymph
amber spruce
#

i tried without the else statement because i dont need that i only added it because it wasent working

rich adder
#

something is not working you just throw something else and hoping it works?

#

debug your original problem then

#

what does "wasnt working" mean in that context

sage mirage
#

Hey, guys! I don't know how to set my default screen resolution to my in game resolution when entering the game. How to do that because when I am entering the game I don't see my screen resolution. I made a dropdown for my resolution options and I save them and load as well but the only problem here is to load my default resolution, so the players screen resolutions to its default screen resolution of their monitor inside the game.

Check my code here:

{
    // Every variable or initialization that has to happen when the game starts in here!

    resolutions = Screen.resolutions;

    if (resolutionDropdown != null)
    {
        resolutionDropdown.ClearOptions();
    }
    
    List<string> options = new List<string>();

    for (int i = 0; i < resolutions.Length; i++)
    {
        string option = resolutions[i].width + " x " + resolutions[i].height;
        options.Add(option);

        if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height)
        {
            currentResolutionIndex = i;
        }
    }

    if (resolutionDropdown != null)
    {
        resolutionDropdown.AddOptions(options);
        resolutionDropdown.value = currentResolutionIndex;
        resolutionDropdown.RefreshShownValue();
    }```
amber spruce
rich adder
#

also i was talking about the issue before you changed it

short hazel
#

The stuff in the else only runs if the stuff in the if didn't run.
So if you have blocking enabled, you don't receive damage. You divide the value by 4, and execution exits the method without running anything else

#

Your code editor might even tell you that damage = damage / 4; can be removed as damage is never read after that

rich adder
short hazel
#

(code adapted to compile without Unity)

amber spruce
#

because if its true it has a animation

summer stump
amber spruce
#

yeah but wouldnt just removing the else fix the whole problem with the if else

sage mirage
summer stump
amber spruce
#

well it didnt work before

summer stump
summer stump
amber spruce
#

no it did not

short hazel
amber spruce
#

i found the issue

#
public void TakeDamage(float damage)
{
    Debug.Log("TakeDamage");
    if (playerController.isBlocking)
    {
        damage = damage / 4;
    }
    Debug.Log("damage: " + damage);
    currentHealth.Value -= damage;
    Debug.Log("currentHealth: " + currentHealth.Value);
    animator.SetTrigger("Hurt");
    Debug.Log(damage);
    if (currentHealth.Value <= 0)
    {
        Die();
    }
}

i get all the debugs up till after i change the health value

sage mirage
rich adder
summer stump
short hazel
sage mirage
rich adder
sage mirage
#

I was always working with methods I dont know what those attributes is, I had no time to work with them and learn them actually.

rich adder
#

you never used SerializeField ?

#

thats an attribute

sage mirage
#

I have used

#

Serialize is an attribute right

rich adder
#

it usually goes above class/method/member var

sage mirage
#

ok!

sage mirage
#

There is no method for that functionality? I mean there are only attributes?

rich adder
#

the attribute is what tells the method to run before scene load

sage mirage
#

I was searching for OnApplicationEnter maybe but there is no method called like that XD

rich adder
#

but as SPR2 mentioned, resolutions is usually set to default when running the app first time no?

sage mirage
rich adder
#

unless you changed it in Player settings

sage mirage
coarse compass
#

Why do people use Empties as root in Prefabs? This seems so bad to access Components or public variables on scripts

lavish roost
#

Its to Split Logic from visuals for better structure

sage mirage
#

@rich adder Do we use attributes only for static members?

rich adder
#

the components actually go on the root

#

only GFX get split up

short hazel
rich adder
#

apparently they have and still asked 😆

lavish roost
#

With a serialize field or GetComponentInChildren

coarse compass
rich adder
#

otherwise you get bad sizing

#

simple shapes i keep on root

#

so i just modify their size with gizmos

short hazel
#

Also helps keeping uniform objects when the prefab is rotated. If you try to do that with a root object that's scaled, it will seriously affect its children

quick ruin
#

how do I fix this

#

just trying to set material alpha

short hazel
#

Store the whole color in a variable, modifiy its alpha, then assign the whole color back to the material

quick ruin
#

ty

visual hedge
#

So I can't serialize this one that easily, right?

rich adder
#

prob screwed with the reference types

visual hedge
# rich adder what is "this one"

This one is the list of quite a data... so I can't just give the refference to the list to data saver and hope it will just save it?

quick edge
#

Yo! I have a problem. I have an empty game object (a pivot) and I childed a Camera on it. When I'm not in play mode, when I rotate the pivot the camera rotate around it like supposed, but when I'm in play mode it doesn't work. I don't understand why it makes no sense, and I didn't find any solutions on the internet. Can you help please?

https://gdl.space/luviwaxuwa.cs

north kiln
#

(don't scale mouse delta by Time.deltaTime)

quick edge
#

Why ?

rich adder
#

could be wrong
maybe use scriptable objects??

quick edge
#

Ok interesting thanks!

#

And do you have a solution for my problem?

rich adder
#

Addressables are prob an option too since that assigns an actual address to the asset @visual hedge

#

I have to look back into its been a while xD

visual hedge
# rich adder References afaik are a pain to save

sorry, I think I might express myself wrong:
I have a list of different type of data, here's the screenshot.
And to save that list, I just be like:
public List<CapturedPets> summonList = new();
summonList = character.summonHandler.SummonList;

rich adder
visual hedge
rich adder
#

what is the error?

visual hedge
#

1 min, let me try once again 🙂

vocal sail
#

C# question here:
Does children classes inherit the complete classes' methods without overwrite it from the abstract class? If not, what should I do to accomplish this?

rich adder
#

its probably GameObject ? idk if unity likes saving it @visual hedge

short hazel
#

A child class has access to all its base members, provided that they're accessible (protected or more accessible)

quick edge
vocal sail
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class SceneObject : MonoBehaviour {
    
    public int sequenceID;

    private void Start() {
        gameObject.GetComponent<MeshRenderer>().enabled = false;
        gameObject.GetComponent<Collider>().enabled = false;

        MainProgressManager.mainProgress.OnNPCArrive += Called;
        MainProgressManager.mainProgress.OnSelfDestruction += SelfDestruction;
        MainProgressManager.mainProgress.OnStartUp += StartUp;
        
    }

    public void StartUp() {
        if (sequenceID == 0) {
            gameObject.GetComponent<MeshRenderer>().enabled = true;
            gameObject.GetComponent<Collider>().enabled = true;
        }
        else {
            gameObject.GetComponent<MeshRenderer>().enabled = false;
            gameObject.GetComponent<Collider>().enabled = false;
        }
    }

    public void Called() {
        int progressPhase = MainProgressManager.mainProgress.progressPhase;
        if (progressPhase == sequenceID) {
            gameObject.GetComponent<MeshRenderer>().enabled = true;
            gameObject.GetComponent<Collider>().enabled = true;
        }
    }

    public virtual void SelfDestruction(int progressPhase) {
        if (sequenceID < progressPhase) {
            gameObject.SetActive(false);
        }
    }

}
visual hedge
vocal sail
#

here is my abstract class, so that my child classes will automatically have the called and startup methods subscribe to the actions? Because it seems that it is not the case or I'm doing something wrong

short hazel
#

If the child also declares a Start() method, the base will not be called. Make it virtual and call it in the override

rich adder
vocal sail
visual hedge
vocal sail
#

So make the base method virtual, when my child override the method that will be addition to the method, right?

knotty gust
#

whats the difference between writealltext and writealltextasync?

rich adder
short hazel
knotty gust
rich adder
#

better question you should ask is , what is async ?

knotty gust
#

yhh

visual hedge
knotty gust
#

sorry

visual hedge
#

so I guess saving the list as a list is bad idea in general

#

or something...

rich adder
# knotty gust sorry

async is when you want the code to run parallel to other code or in the "background"

#

so it doesn't block the main thread

#

eg if you have a long list of stuff to get from the internet, you don't want your UI locking up while loading all that data downloading

#

so think of it as "run this in the background"

#

Writing to a file can also take time so its best to use async to not lock up the UI

#

most UI in any app run on the main thread

knotty gust
#

i see

#

thats useful

#

thanks

wanton hearth
#

OK this is likely a dumb question, but how can you easily view the position of each vertex of a mesh?

I want to look at a mesh and know, mesh.vertices[0] is here, mesh.vertices[1] is here, etc.

austere osprey
#

so i have a piece of code that is supposed to launch the player backwards and a little bit upwards upon dying, as well as rotating the player 90 degrees. i think it might work for the most part, but the problem is that the player proceeds to clip through the ground when flipped, and i don't know why. the game is in 2d

#

if (isFacingRight) { rb.AddForce(Vector2.left * 15, ForceMode2D.Impulse); rb.AddForce(Vector2.up * 10, ForceMode2D.Impulse); transform.Rotate(0, 90, 0); } else { rb.AddForce(Vector2.right * 15, ForceMode2D.Impulse); rb.AddForce(Vector2.up * 10, ForceMode2D.Impulse); transform.Rotate(0, 90, 0); }

rich adder
# knotty gust thats useful

they're pretty useful the more you get comfortable with them, ofc you don't want start using it everywhere because you run into other problems

knotty gust
#

Yhhh I’m thinking to use it for my save system for now and since that’s the only place I would really be writing any data to a file I think it would be useful

vocal sail
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PathObject : SceneObject {

    private NPCManager nPCManager;

    public override void Start() {
        nPCManager = FindObjectOfType<NPCManager>();

        MainProgressManager.mainProgress.OnCallNextPath += ReturnPath;
    }
    public void ReturnPath(int progressPhase) {
        if (progressPhase == sequenceID) {
            nPCManager.moveTo = this.gameObject;
        }
    }
}```
but still the gameobject attach to the child script doesn't disable its visual on Start()
rich adder
vocal sail
#

oh adding base.Start to the front

#

yes, it works, thanks

rich adder
#

unity has an entry point for async in awake too, which is useful @knotty gust

knotty gust
rich adder
rich adder
# knotty gust Wdym?
 private async void Awake()
    {
        await Task.Delay(1000);
        //wait a second and move on
    }```
rich adder
knotty gust
#

Damn so I didn’t have to use a coroutine for delays on awake?

knotty gust
#

Thank you

rich adder
#

Coroutines are poor mans async

knotty gust
#

So when would using async awake be better than coroutines?

rich adder
knotty gust
#

Yhhh I’m Ngl idk what an init operation 😂

rich adder
#

like cs private async void Awake() { await LoadSaveClass.LoadSomeWebData() }

knotty gust
#

Ohhhh

#

Getting data from the web basically?

rich adder
#

not only but thats a pretty common usecase

#

since data from web is not instantanious usually

knotty gust
#

Why’s it better to use async awake for that?

#

Yh I thought it would be Smth like that

rich adder
#

particularly UI

knotty gust
#

Nooo I meant over a coroutine

#

Or is it the same thing

#

Like same reasoning

rich adder
#

yes

#

they're both async methods

knotty gust
#

Ahh okay okay

#

Thanks man

upbeat stirrup
#

Should I use Rigidbody.velocity or Rigidbody.AddForce() when making a movement system? I know you shouldn't change the velocity directly, but I see it being used in movement systems a lot.

summer stump
upbeat stirrup
#

Thanks a lot! Also, unity docs states, "In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour - use AddForce instead..."

short hazel
#

If you make unrealistic movements (too realistic is sometimes bad) it's perfectly fine to change the velocity directly
What's not fine is changing the transform.position directly with a Rigidbody on, it ingores the physics system!

amber spruce
#

anyone know what this error means

InvalidOperationException while executing 'performed' callbacks of 'Player/Attack[/Mouse/leftButton,/XInputControllerWindows/buttonWest]'
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)

#

and can i ignore it or no

amber spruce
#

yeah

short hazel
#

This error will be paired up with another error in the console usually

rich adder
#

seems like something u should not ignore then

amber spruce
# short hazel This error will be paired up with another error in the console usually

it is paired with another errror

InvalidOperationException: Client is not allowed to write to this NetworkVariable
Unity.Netcode.NetworkVariable1[T].set_Value (T value) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.7.1/Runtime/NetworkVariable/NetworkVariable.cs:78) MultiplayerHealth.TakeDamageServerRpc (System.Single damage) (at Assets/MultiplayerHealth.cs:64) MultiplayerHealth.TakeDamage (System.Single damage) (at Assets/MultiplayerHealth.cs:55) MultiplayerPlayerController.Attack (UnityEngine.InputSystem.InputAction+CallbackContext ctx) (at Assets/Scripts/MultiplayerPlayerController.cs:242) UnityEngine.Events.InvokableCall1[T1].Invoke (T1 args0) (at <61f56803c0b0466195d97f1cb7494aa1>:0)
UnityEngine.Events.UnityEvent1[T0].Invoke (T0 arg0) (at <61f56803c0b0466195d97f1cb7494aa1>:0) UnityEngine.InputSystem.Utilities.DelegateHelpers.InvokeCallbacksSafe[TValue] (UnityEngine.InputSystem.Utilities.CallbackArray1[System.Action`1[TValue]]& callbacks, TValue argument, System.String callbackName, System.Object context) (at ./Library/PackageCache/com.unity.inputsystem@1.7.0/InputSystem/Utilities/DelegateHelpers.cs:46)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)

rich adder
#

ahh

#

yes

#

clients cannot write to Network variable

#

unless you set permissions to all

#

idk how thats related to input tho xD

amber spruce
short hazel
#

New Input System also catches the errors that happen in your event handlers, so they're reported twice.
Once for the exception itself caught by Unity, and once for the Input system itself catching it

amber spruce
summer stump
cobalt solstice
#

If I've used an image from somewhere that requires attribution in the project is there a suggested place for that kind of thing? This is an academic project so I've got to write a documentation too if that kind of thing can be linked in the written part if anyone knows?

rich adder
amber spruce
rich adder
cobalt solstice
#

Or the documentation

rich adder
cobalt solstice
#

Ah I'm using it in unity rather than the doc so I wasn't sure where to put the link

rich adder
cobalt solstice
#

Ah alright cool Ty 🙂

cobalt solstice
rich adder
lime mural
rich adder
#

then when you build the game , put that inside the build

cobalt solstice
#

Ohh gotcha

#

Ty

hybrid tapir
#

how do you prevent the default action for gamepad buttons

#

my playstation button on my controller opens steam

low perch
#

Unity is not in play mode but I am getting this like every frame

NullReferenceException: SerializedObject of SerializedProperty has been Disposed.

wintry quarry
#

Probably an editor bug

uncut dune
low perch
#

ok

rocky canyon
#

dont ignore it, just restart it

#

it'll vanish until the editor bugs out again

#

usually you can spot unity errors by the way they are..

#

they'll usually have a specific namespace

#

like Unity Editor. blabla

#

= editor bug (not ur fault)

#

unlike the previous error (this one is ur fault)

slender nymph
#

that's not always the case though. for example, writing editor code could lead to UnityEditor related errors

rocky canyon
#

thats true..

#

but if its an unusual error.. (ur not working with editor scripts etc) + seeing that library.. then most likely bug

#

gyro and accelerometers are both inputs i can use w/o having that allow permissions pop up?

#

getting started with mobile and walking into a whole new world 😅

low perch
#

I restarted it and found out it happens after I exit playmode every time I add/remove an inventory slot.
When an inventory slot is added (ex: from 1 to 2) I have a set thing that updates inventoryLimit = value and also calls updateInventorySlots() which I suspect is the issue however the methid is called on awake and has no issues when I exit playmode. I wrote no editor code either

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

deep quarry
#

Hey,
This is my code to move my character:

moveDir = transform.forward * vertical + transform.right * horizontal;
rb.AddForce(moveDir * moveSpeed * Time.deltaTime, ForceMode.Force);

I get this message above the moveDir on the second line:
Re-order operands for better performance

How may I re-order the code to get better performance?

low perch
#

I believe vectors should be multiplied at the back and floats at the front

rich adder
#

IDE iirc will help you do it

deep quarry
#

Ohh, I see. That actually makes sense.

Thank you very much, both of you! :)

visual hedge
#

general question: Is someone doing like mentoring / teaching about unity stuff?
Basically what I mean is theoretically me hiring a mentor that will help me with solving different problems with my project on request.
That's not a hiring message. I am just curious if something like that exists.

visual hedge
ionic zephyr
#

what does "Monobehaviour" do?

#

like what´s it´s purpose

timber tide
#

it makes game

rich adder
summer stump
teal viper
ionic zephyr
summer stump
summer stump
dreamy epoch
#

Hey there! I am trying to use the Rewired API to take in inputs from a Logitech G290 steering wheel and cannot get the steering wheel to cooperate. Any suggestions or better place to get info? Thank you so much!

robust condor
#

Do mesh collider vs box collider performance matter if nothing is colliding with the objects? If I spawn 1000 objs that really wont collide with anything

timber tide
#

mesh requires more operations to check collision, and it's concurrent so it doesnt matter if it's not colliding

hushed rose
#

I have ~ 4k terrain trees on map. I want save info about each of them (position, rotation etc), then remove and Instantiate prefabs on their position - any advice to performance?

arctic harbor
#

trying to set some default values for some variables within the script in case i forget to manually adjust the values in the inspector. for some reason if i have leftLimit declared first, the default value for rightLimit set via script seems to be ignored in the editor, but if i declare rightLimit first, it seems to be fine. why is this so?

north kiln
timber tide
arctic harbor
north kiln
#

Are you resetting the component via the context menu to see the default values in the inspector?

arctic harbor
#

oh that works thanks. not sure why rightLimit was going to zero when declared second though

north kiln
#

(also those are some bizarre magic numbers to use for defaults)

arctic harbor
#

well, the decimals specifically is so i can have the walls snug against the sides of the screen

#

the 999 part of rightLimit is just some arbitrary large number that probably won't be reached

robust condor
#

There are better ways to do this

arctic harbor
#

i'm sure there are, but this is working and simple enough

deep quarry
#

Hey,
Quick question. I am making a Player Controller script based on Rigidbody.
If I want to rotate the Player, can I use the transform.Rotate() method or should I use a Rigidbody based rotation, such as Rigidbody.MoveRotation?

teal viper
deep quarry
boreal tangle
#

Is it worth it to restart the script for player movement if the code is messy and only works 95% of the time.

rich adder
#

refactoring is important sure

boreal tangle
#

Okay thank you

last grove
#
        get => _Health;
        private set {
            if (value < _Health)
            {
                if (UIContainer.enabled != true)
                {
                    UIContainer.GetComponent<Canvas>().enabled = true;
                    StartCoroutine(Wait(3));
                    UIContainer.GetComponent<Canvas>().enabled = false;
                }
            }
            _Health = value;
        }
    }```I am trying to make a health bar appear when an object is damaged. No errors but the canvas is not being enabled
supple wasp
#

I don't know why I get this mistake if you can help me, making the text big when you enter and get little when you already enter the screen but this comes out

summer stump
last grove
#

ohhhhhhhhhhhh

#

that would make a lot of sense

supple wasp
summer stump
# supple wasp

You have LeanTween imported?
Never used it, but are you sure that is the Namespace you need?

north kiln
#

Don't use notepad++ to program.
!ide

eternal falconBOT
summer stump
#

Oh god, how did I not notice that?!

north kiln
#

No idea, you should have noticed their error was not underlined at least 😛

summer stump
spiral glen
#

Is the access to Animator, Vector2 and Rigidbody2D aggregation, composition or neither?

north kiln
#

Is this a test 🤔

spiral glen
#

Yes, maybe? idk, I just need to figure this out

rich adder
frosty hound
#

Figure this out ... for a test?

spiral glen
#

No It's not for a test

#

So are they composition, aggregation or neither. I'm trying to figure this out.

supple wasp
rich adder
spiral glen
#

Should I ask this in the general or advanced or something, I need to figure this out by saturday.

supple wasp
#

I will be able to use the unity and the visual Studio 2022 well when my improved new laptop arrives

#

Well there are the mistakes that come out

north kiln
spiral glen
rich adder
#

btw DOTween highly superior Imo

north kiln
#

maybe I shouldn't have been specific and just asked if it was for homework; because it's obnoxious as hell to be asked multiple-choice questions

slender nymph
#

have you considered reviewing your course materials to find the answer?

supple wasp
spiral glen
#

I have, I know what aggregation and composition is but the actual application in figuring out if something is or isn't either is confusing.

#

I mean I guess aggregation is dependancy so I'll just call it that and stop flooding chat, gracias.

swift crag
#

these are nitpicky OOP buzzwords. very annoying to think about

rich adder
supple wasp
north kiln
#

it's a mystery

rocky canyon
#

Unity comes pre-packaged with many things..

#

like these two...

#

NaughtAttributes is not default

#

i'd have to install that

supple wasp
#

I just put the unity package and now

rocky canyon
#

for you the error is Under "LeanTween"

#

i wonder wat package its expecting..

rich adder
#

GPT code 💯

rocky canyon
#

look at this.. its in the Unity Asset Store..

#

if u check the Documents it shows all these parameter's and functions each one is following a LeanTween.

#

thats what the using LeanTween means..

#

it means when u call any of these. it knows where to look.. until you install it.. it doesn't exist

rocky canyon
abstract pelican
#

tell me how I should be here?

swift crag
#

It's just suggesting that you use those two newer methods.

#

The old one will continue working (for now, at least)

summer stump
#

SoundManager sounds like a fine thing to make a Singleton with a static accessor though, negating the need for a Find call

amber spruce
#
 SamuraiButton = GameObject.Find("SamuraiButton").GetComponent<Button>();
 KnightButton = GameObject.Find("KnightButton").GetComponent<Button>();
 WizardButton = GameObject.Find("WizardButton").GetComponent<Button>();
 ButterButton = GameObject.Find("ButterButton").GetComponent<Button>();

why doesnt this work they never get assigned to stuff

slender nymph
abstract pelican
nimble apex
#

this should relate to code , sorta UI design

my team is using a pretty bad UI deisgn rn, basically we call and stack UI one by one, so in order to make thing less chaotic, we will put a panel for the top UI

nimble apex
#

so it will hide other UI under it

abstract pelican
#

Is there something wrong here?

nimble apex
#

is there a way , to allow only one panel exists, but that panel can always under 1 level of the top UI

#

for example

abstract pelican
#

@summer stump

nimble apex
#

UI 1
panel
UI 2
UI 3

#

without calling gameobject.findbytype

#

or get componentbychild

cosmic dagger
# abstract pelican

You're adding an AudioSource component for every sound you have on one GameObject, why?

abstract pelican
#
soundManager.PlayClip("Backpack close");```
#

and that's how I add where I need to

cosmic dagger
# abstract pelican

I understand the array of Sound, but why add an AudioSource component for every single sound? Say you have 100 sounds; youre adding 100 AudioSource components to the sound manager GameObject . . .

summer stump
# abstract pelican

I generally do the reverse:

public static SoundManager Instance { get; private set; }

    void Awake()
    {
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
    DontDestroyOnLoad(gameObject);
    }

But that should be fine.
Is it getting destroyed though?

Also note that the static variable (where you put the //singleton comment) is not the singleton, the class is. A singleton doesn't even necessarily need the static accessor

cosmic dagger
#

You can replace the properties of an AudioSource with the fields from the Sound instance before playing the clip . . .

boreal tangle
#

Does dependency injection mean using serialize to add the reference to a script?

slender nymph
#

that is a basic form of dependency injection, but is not the only form of dependency injection

boreal tangle
#

do you know a place I can see the diffrent ones

swift crag
#

it's a very broad concept

#

it's really just when you give something another object, instead of that thing having to create its own object

slender nymph
#

dependency injection is just the concept of injecting a dependency into an object. this can be done any number of ways. you can do so by simply assigning a reference via the inspector, pass a reference to an object via method parameter or directly assigning to a property/field, use a full on dependency injection framework, etc

swift crag
#

if you want to give yourself a heart attack, look at the readme for Zenject

boreal tangle
#

ok thank you

cosmic dagger
#

Oh dear, not Zenject . . .

abstract pelican
swift crag
# abstract pelican

you have written a local function called Awake and stuffed it into your Awake method

abstract pelican
#

I was trying to make some kind of general sound manager for each object so that I could then turn down the sound for all of them with one slider

swift crag
#

You should look at sound mixers.

#

You can route all of your audio sources into a mixer and then control its volume

abstract pelican
#

Now I can't find the sound, as it was before

#

everything works fine with this

abstract pelican
#

maybe there is some great video? So that I can get rid of him

slender nymph
#

i mean you don't need a sound manager. especially not to just easily control the volume of a group of different sounds

abstract pelican
#

I just don't understand where to store the sounds.

summer stump
# abstract pelican

Do that in Start. Instance is set on Awake, so you're grabbing the reference too early

slender nymph
#

although apparently audio mixers don't work in webgl so that's a consideration

abstract pelican
slender nymph
#

do what? because it seems like we are referring to different things

slender nymph
abstract pelican
cosmic dagger
slender nymph
abstract pelican
#

I'm sorry, of course, but as a beginner, can you tell me if I need this sound manager?

swift crag
#

let me ask you a question

#

why do you think you need a sound manager?

abstract pelican
#

as they usually do in large projects so that I can expand it later without rewriting the code

#

I just now noticed that it creates 5 audio tracks

#

even opening the inventory, although I didn't use it

slender nymph
#

wdym it creates 5 audio tracks? or are you referring to the 5 different AudioSource components? because that has been the concern everyone else has been pointing out this entire time

abstract pelican
#

I decided to check if it was true.

slender nymph
#

that's the whole point of this entire conversation. have you just not been paying attention?

cosmic dagger
# abstract pelican

This is what I mentioned earlier. Your code adds an AudioSource component to the GameObject for every Sound in your array . . .

abstract pelican
abstract pelican
slender nymph
cosmic dagger
abstract pelican
neat bay
#

does anybody know why this while look crashes my unity?

slender nymph
#

because its condition never changes

neat bay
#
1 / cooldown * elapsed <= 1

this?

abstract pelican
slender nymph
swift crag
abstract pelican
swift crag
#

I am working on a reasonably sized game that's been pleasant to develop so far. Perhaps you'll be interested in how I'm handling sound in it

abstract pelican
swift crag
#

I have an AudioSource on each "thing" that can produce sounds. Each thing will either directly reference AudioClips or reference another asset that holds AudioClips.

abstract pelican
swift crag
#

Each AudioSource has a sound mixer set on it to route the sound to the correct category

abstract pelican
#

I'm always glad if someone shares their cool experience.

slender nymph
swift crag
#

Ambient/Speech/SFX/Music/etc.

swift crag
abstract pelican
swift crag
#

e.g. a computer has a looping fan noise and also randomly plays beeping sounds

#

that'd be two audio sources

swift crag
#

The game also has a hand-rolled spatial audio system that tries to add reverb and adjust the position of audio to sound more realistic...but that's out of scope 😉

abstract pelican
swift crag
neat bay
swift crag
#

and give it an AudioSource component that it references

gaunt ice
#
1 / cooldown * elapsed <= 1
```this line shouldnt freeze your unity btw since the elapsed is incremented by time.deltaTime, the only reason casuse the line of code always false is 1/cooldown=0 (cooldown=infinity ?)
#

btw 1/infinity will not give you segfault and crash your unity

north kiln
#

it's a while loop without a yield in it

swift crag
#
[SerializeField] AudioClip closeClip;
[SerializeField] AudioClip openClip;
{SerializeField] AudioSource audioSource;
north kiln
neat bay
cosmic dagger
swift crag
#

The loop shouldn't freeze Unity forever.

#

It will just execute all of its iterations instantly

north kiln
#

If Timescale is 0

swift crag
#

True. Or if it happens in a frame with a deltaTime of zero

#

I know turning on the recorder causes one of those.

neat bay
swift crag
abstract pelican
#

Thanks guys, I would have sat there and continued to be stupid.

swift crag
#

(it does not work on ARM hardware)

neat bay
abstract pelican
gaunt ice
#

someone has already told you use coroutine

north kiln
slender nymph
swift crag
#

I calculate a path from the source to the listener and compare its length to the straight-line distance

#

I also count how many corners the path has and how sharp they are

neat bay
swift crag
#

That's used to compute a "directness" value

#

Low directness causes the audio source to get a strong reverb and low-pass filter applied to it

#

I also shoot a raycast and cut the directness if it hits a wall

swift crag
#

I measure paths from a few different positions to help blend it better as well

#

The more difficult thing I then do is actually reposition the audio source

#

I still need to work on that logic. I forget exactly what I did, actually...not at my laptop right now

#

I think it does a weighed average of the path points and slaps the audio source there

calm coral
swift crag
#

heavily weighing the points closer to the player

#

I originally wanted to compute a graph of 3D volumes (so, box colliders) and do A* to navigate from the source to the listener

#

I might try that again, but having unity make the navmesh and do the pathfinding for me is pretty nice...

cosmic dagger
swift crag
#

like, in real life 😨

#

listen to how the sound changes as you walk behind obstacles

#

you'll get a low pass filter (high pitched sounds go away)

#

fountains are a good source of noise. i notice the effect when i walk past a wall

#

Then you mix in reverb. The more indirect the path, the more reverb you want to mix in

#

more wet, less dry

#

wet = the result of the reverb filter, dry = the original audio

gaunt ice
#

high frequency (low period) signal not easily bend?
completely forgot the physics term

summer stump
swift crag
#

No, I'm not considering that at all. I guess I partially account for that with audio reverb zones

#

I'm not doing a lot of clever stuff that Steam Audio is

summer stump
# gaunt ice high frequency (low period) signal not easily bend? completely forgot the physi...

They attenuate more strongly on reflections, while low-end frequencies retain more of their power. So it's not about the spread (or bend as you say), but the build up of reverberation and possible standing waves (which are less likely in high frequencies due to their wavelength being so small).
So in essence, the direct sound is blocked. The early reflections contain less high end, the reverberant sound is going to contain WAY less high end.

swift crag
#

due to physics

#

#

I need to revisit the system. I wrote it almost a year ago :p

boreal tangle
#

would zenject be a good idea to learn or is it better to just used unity's serialize

slender nymph
#

do you need an entire DI framework?

boreal tangle
#

Say I had 14 days to create a game. would it be worth to learn it. I dont know if I need on ever not seen Ive never used one

slender nymph
#

don't just go adding a giant complex framework to your project if you cannot currently see why you would need such a thing

swift crag
#

I have never touched Zenject and I've never really felt the burning desire for it

boreal tangle
#

ok i wont use it

swift crag
#

make your game.

cosmic dagger
boreal tangle
#

ok

nimble apex
#

can i modify gameobject hierachy under certain gameobject

like this

A
obj1
obj2
obj3

and then make it like this

A
obj2
obj1
obj3

teal viper
#

In code you mean?

nimble apex
#

why? doing it for UIs

#

yes

teal viper
#

Sure, you can set the sibling index(was it) of a transform.

#

Look at the Transform docs. It's responsible for placement in the hierarchy.

nimble apex
#

so my team has implemented a very bad UI design , which is common in every dev team in my city

we basically make a parent UI canvas , and then put every single UI we need under it, and we not even doing any sorting layers to any UI

gaunt ice
#

no hierarchy structure?

#

i mean some sort of subtree or just a list under canvas

nimble apex
#

it has, its just all UI are put under same big canvas u know

nimble apex
#

so , in order for me to do that, without sorting layers, and a script to store all UIs called, i will need to find every UI i need , and then put the mask under it

teal viper
nimble apex
#

way better than previous team

#

aight lemme try it

nimble apex
# teal viper This sounds fine.

but u cant do sorting layers as the whole UI is almost finished, and they all rely on current structure and without sorting layers

#

u need to add another canvas on those sub UIs under the canvas right? in order to use sorting layers

teal viper
#

Or you could probably add canvases without it affecting stuff.

nimble apex
#

not necessary, but it will be better to have i guess

signal trail
#

Hey Guys, if I want to make a player do an animation when taking damage, Is it better to do things:

A) from the damage script(Enemy Script that handles collision damage) and set a flag on the PlayerController to deal with animation changes
B) Somehow do this directly on PlayerController
C) Other way

slender nymph
#

make the enemy script tell the Player that it is dealing damage. then the player will do whatever it needs to in reaction to that. don't make your enemy control your player

signal trail
#

So A, idk if I worded it right but thats basically what I first had in mind

#

How would you handle this in your player script? As of now Im just thinking of a variable that when true, triggers the animation in the animator, but Im curious if theres a better way

slender nymph
#

well it sounds like with A you are making your Enemy object tell the player that it should animate. but that shouldn't be the case. the Enemy should only care about dealing damage. So create a method on the player that receives damage and have the enemy call that method. Then the player can do whatever it needs to from that method

signal trail
#

Yeah, I worded that weird, the enemy collision script just triggers a TakeDamage(value) right now

slender nymph
#

that's really all the enemy should be doing. so then your TakeDamage method can notify your animator (or some other component on your player that controls your animator if that's how you have it set up) that it needs to do the damage animation

queen adder
#

Can anyone help me with being able to zoom with the mouse in my camcontroller?

dense willow
#

I just got here and read a bit of the read me, but I'm still confused on if we post questions here or if there is another channel

slender nymph
signal trail
slender nymph
#

the latter probably

signal trail
#

Thanks a lot boxfriend

slender nymph
#

or slap an event on it that the player controller subscribes to

dense willow
dense willow
queen adder
#

Sorry, you're right. I already have some initial code, I don't know if it's right but I want to change it in a way that actually works haha

slender nymph
#

then you should share the !code and explain what isn't currently working about it

eternal falconBOT
slender nymph
#

please read the bot message again

dense willow
#

Okay, thanks. I'll delete my message here then?

slender nymph
#

yeah, you're technically supposed to when you move a question to another channel to avoid being moderated for crossposting

dense willow
#

Cool, thanks friend yobaman

#

What are the odds of anyone answering my question there though, it seems kind of quiet

#

nvm, probably in the morning lol

slender nymph
#

at this point you should just use a paste site @queen adder

queen adder
#

these protected fields are so tempting to inherit from 🤤
Anyone ever inherited contentsizefitter to implement their weird thingies?

#

where the 'if' statement starts is where the scrollwheel is meant to work.

slender nymph
#

you probably want to change the transform.localPosition rather than the transform.position
but also i recommend swapping to cinemachine for camera controls. and also not making your camera a child of the player

queen adder
#

ok, thank you!

vast ivy
#

Anyone know why I might be getting the wrong mouse position when I try to drag? Like to drag the first slot I have to be like 100pixels to the left of it to pick it up?

    public void OnDrag(PointerEventData eventData)
    {
        // Convert event position to canvas space
        Vector2 position;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            canvas.transform as RectTransform, 
            eventData.position, 
            canvas.worldCamera, 
            out position
        );
edgy fox
#

3rd image is from a second class, if I have a debug.log in the first class and I click on a button placeMode = [the correct mode] and CurrentMode when called from that class outputs [the correct mode] but when I call CurrentMode from another class and I debug.log(mode it outputs "none"

gaunt ice
edgy fox
#

I know what enums are how does that relate to static classes?

gaunt ice
#

you can put enum where ever you like

edgy fox
#

so just make placeMode an enum and it works you say?

gaunt ice
#

yes, since you wont mistype room to Room (or vice verse)

slender nymph
#

simply changing to an enum instead of a string won't fix the issue you've described, but it is still a good idea
your issue is also likely due to the order you do things in or other objects changing the value of your static variable. since anything can access it and change it at any time, you need to examine all locations that are accessing it. you also need to make sure you are assigning to it before you try logging it

edgy fox
#

and it is only modified in the SelectPlacement function

slender nymph
#

if you are certain that the two locations you have shown that access and modify that variable are the only locations that do so, then the issue is the order your code is running

gaunt ice
#

btw having public static is not good idea as boxfriend said since everything can change it

edgy fox
#

what should I do to make it so only that function can set it but any other function can read it's value

slender nymph
#

you probably want the variable to be private

gaunt ice
#

i think control accessibility down to method level is impossible in c#

#

so be carefully

edgy fox
slender nymph
#

you're exposing it through the method that is declared directly below it. read it from that

gaunt ice
summer stump
gaunt ice
#

if you want other class can read but not wirte it

edgy fox
#

It turns out it wasn't a code issue

#

I hadn't pressed the button when testing to change the mode

#

it was a failure of UI all along

#

I really should add some visual cue that the button is/isn't pressed

#

alrighy I'm confused

slender nymph
#

put it inside of a method

edgy fox
#

debug has to be in a method?

slender nymph
#

any expression that is not a member or type declaration has to be

edgy fox
#

in hindsight that seems extremely obvious

#

I've apparently never tried to use a debug statement outside of a method

little garden
#

why does OnTriggerEnter only happen when a rigidbody accelerates towards my game object

slender nymph
little garden
#

what would be the best way to detect if my player touches another game object?

#

for example, like the crash nitro boxes that instantly kill you when you touch them

slender nymph
#

well the easiest would be OnTriggerEnter or OnCollisionEnter or if you are using a CharacterController then OnCharacterColliderHit or whatever its special collision message is

little garden
#

that only works when
the player explicitly moves towards the object (character collider hit)
or
the object explicitly moves towards the player (trigger/collision enter)
right?

slender nymph
#

what?

#

if you are referring to the CharacterController's collision message, then yes. that only occurs when the CC performs a Move. the other two do not rely on that

little garden
#

seems like we would need to use both

OnTriggerEnter to detect an object pushing against us
OnControllerColliderHit to detect us pushing against an object (standing on top counts due to gravity i assume)

but im not sure how to detect contact with an object that is not pushing against us nor that we are not pushing against

slender nymph
#

well trigger colliders, which are required for OnTriggerEnter do not physically collide so there is no "pushing against us" there. and you would use that or OnTriggerStay to detect overlaps with trigger colliders.
otherwise colliders that are moving that are not triggers will need their own rigidbodies to produce OnCollisionEnter messages, which will be sent to the CharacterController. the CC just doesn't produce OnCollsion messages on its own

little garden
#

yea

#

what if both objects have a rigidbody

#

eg, detect a game object resting against another game object

slender nymph
#

charactercontroller and rigidbody do not mix

#

but what you've described would be covered by OnCollisionStay. you should consider reading the documentation, you'd figure this stuff out easier

little garden
#

they do if we use a kinematic rigidbody that does not use gravity

slender nymph
#

and yet you still don't need a rigidbody on a CharacterController. as long as the other object has a rigidbody it will send an OnCollision message to the CC

little garden
#

hmm it doesnt seem to trigger OnCollisionEnter

slender nymph
#

show both objects

little garden
slender nymph
#

naturally a trigger collider does not produce a collision message because as we've established they don't collide

#

but also two kinematic bodies coming in contact with each other also do not produce a collision message

little garden
#

hmm Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached

little garden
#

should i just assume unity cannot do this level of precise interaction

slender nymph
#

what "level of precise interaction" are you unable to achieve?
if collision messages aren't working for you because you refuse to set up your objects in a way that would allow them to work (you should really just be using OnTriggerEnter/Stay at this point considering you want to use kinematic rigidbodies anyway) then just use physics queries and check it manually

slender nymph
#

great! now read the rest of my message

little garden
#

would i do var col = Physics.CheckCapsule(_controller.height, _controller.height + _controller.radius + _controller.radius, _controller.radius);

delicate pewter
#

Basic question: If I instantiate a GameObject in runtime and that prefab has a script attached to it. How can I access that script?

slender nymph
#

instead of using a GameObject reference for the prefab variable, refer to the component directly. then Instantiate will return a reference to the instantiated instance of that component

languid spire
#

GetComponent on the instantiated GameObject

delicate pewter
#

"go.GetComponent<Agent>().layerGoal = goalLayer[i];"

Like this? Didn't work, says it can't find layerGoal, but its just a basic public int in Agent.cs

#

go is the instantiated object

slender nymph
#

show the Agent class and share the actual error message

delicate pewter
#

Its as basic as it gets

public class Agent : MonoBehaviour
{
    // Start is called before the first frame update
    private int layerGoal;

    void Start()
    {
        
    }

    public void setLayerGoal(int t){
        layerGoal = t;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.layer == layerGoal){

        }
    }
}

I just changed it to try and use a function to set it instead and change the variable to private

#

Still same issue

slender nymph
#

now show the line of code producing the error

delicate pewter
#
                GameObject go = GameObject.Instantiate(prefab, spawnPosition, Quaternion.identity) as GameObject;
                go.GetComponent<Agent>().setLayerGoal = goalLayer[i];
slender nymph
#

there you go. setLayerGoal is a method not a variable

#

also make sure that your !IDE is configured to help prevent these basic syntax errors

eternal falconBOT
neat bay
#

Does anybody know how I might be able to the the rate of change at a point of an animation curve?

delicate pewter
#

i mean like I said above I did try as a variable first, by directly accessing layerGoal (and it was public then)

#

This was just a change to try and use a method instead to see if it would work

#

Same issue

#
                GameObject go = GameObject.Instantiate(prefab, spawnPosition, Quaternion.identity) as GameObject;
                go.GetComponent<Agent>().setLayerGoal(goalLayer[i]);
slender nymph
#

you're probably using the wrong Agent type then

#

hover over the type Agent on that line and make sure it shows the correct type

delicate pewter
#

Ah.. the name of the prefab is also Agent

#

sorry

slender nymph
#

that's irrelevant. prefab names are not types

delicate pewter
#

I mean it works now, changed the scriptname to AgentController

slender nymph
#

then you were using the wrong agent type

delicate pewter
#

Strange, oh well it works, ty

little garden
#
void Update() {
    if (cached_character_controller != null && Physics.CheckCapsule(cached_character_controller.center, cached_character_controller.center, cached_character_controller.radius)) {
        if (!ragdoll_was_forced && canRagdoll && !in_ragdoll) {
            ragdoll_ms_remaining = ragdoll_duration_ms;
            turn_ragdoll_on();
        }
#

would this do?

#

oof i instantly ragdoll

slender nymph
#

use a layermask for your CheckCapsule

#

otherwise it's likely going to find its own collider

#

still though, i don't see why you don't just use OnTriggerEnter or OnTriggerStay if all you care about is coming in contact with another collider

little garden
#

how tf is a bool considered a and returns detailed information on what was hit.

slender nymph
#

where are you seeing that at

little garden
#

OverlapCapsule seems to be better

little garden
slender nymph
#

that's not even the method you are using

#

and anyway, it populates an out parameter of type RaycastHit for that info

little garden
#

would OverlapCapsule be less expensive than CapsuleCast

slender nymph
#

you can use the profiler if you have concerns about performance

#

but they aren't really substitutes for one another. one checks if anything is within the capsule's area. the other casts the capsule in a direction. if you do not need to move the capsule for the query, then you do not need capsulecast and can just use overlapcapsule. if you do not need any of the info about what was hit then you can go back to using checkcapsule. no matter which of these you use though you will have to use a layermask

little garden
#

imma assume an overlap check is less computational than a raycast

timber tide
#

CapsuleCast has a direction

little garden
#

oof

var cols = Physics.OverlapCapsule(cached_character_controller.center, cached_character_controller.center, cached_character_controller.radius);
foreach(Collider cs in cols) {
    if (cs.gameObject == cached_character_controller.gameObject) {
        continue;
    }
    bool collider_is_ragdoll = false;
    foreach(Collider c in ragdoll_colliders) {
        if (c.gameObject == cs.gameObject) {
            collider_is_ragdoll = true;
            break;
        }
    }
    if (!collider_is_ragdoll) {
        if (!ragdoll_was_forced && canRagdoll && !in_ragdoll) {
            Debug.Log("overlap: " + cs.gameObject);
            Ragdoll(cs);
        }
    }
}

this doesnt trigger at all x.x

timber tide
#

start debugging

little garden
#

i already know its cus every collider returned is one that is the pleyer itself or inside the player

timber tide
#

good thing though is you don't have to deal with trigger method bs this way

little garden
#

otherwise it should have ragdolled

little garden
#

all layers are Default

slender nymph
#

So change them on either the player or whatever type of object you are trying to detect

queen adder
slender nymph
#

By avoiding a layermask and swapping to overlap capsule from CheckCapsule you've started creating way more garbage (especially since you aren't using a nonalloc version)

queen adder
#

ok

little garden
#

oof error CS1061: 'Collider[]' does not contain a definition for 'toList' and no accessible extension method 'toList' accepting a first argument of type 'Collider[]' could be found (are you missing a using directive or an assembly reference?)

#
var cols = Physics.OverlapCapsule(cached_character_controller.center, cached_character_controller.center, cached_character_controller.radius);

frame_colliders = cols.toList();

frame_colliders_game_objects = frame_colliders.ConvertAll(new Converter<Collider, GameObject>(c -> c.gameObject));
slender nymph
#

Spell it right

little garden
#

'Collider[]' does not contain a definition for 'ToList' -_-

slender nymph
#

Now use the quick actions in your configured !IDE to add the relevant using directive

eternal falconBOT
little garden
#

enables the C# extension and gets this -_-

slender nymph
#

Well having a configured IDE is required to get help here so if you don't want to deal with whatever vs code is doing you can switch to a real IDE 🤷‍♂️

nimble apex
#

if you have a configured IDE u will know whats wrong

#

btw, tolist is a linq function

timber tide
#

how long have you been here that you're posting pics from your phone

nimble apex
#

lol im at work

#

i cant download discord on my working pc

#

i dont use laptop, so either phone or working pc in my workplace

little garden
#

shouldnt this be at least detecting ANY colliders?

#

Collider[] cols = Physics.OverlapCapsule(capsule_center, capsule_center, capsule_radius);

this should detect at least one collider, right?

#

or would start == end yield a 0 distance overlap check regardless of the radius and thus optimize for

if (distance == 0)
    return empty;
#

maybe Collider[] cols = Physics.OverlapCapsule(transform.position, transform.position + new Vector3(0, cached_character_controller.height, 0), cached_character_controller.radius);

#

welp it detects the ground

#

but doesnt seem to detect the cube unless we actually stand on top of it

#

welp imma just ignore for now

#

its good enough, doesnt have to be perfect

little garden
#

how do i get my character to move with my ragdoll instead of freezing in place until it respawns

#

eg

#

additionally how do i get a timer to be timescale dependent?

if (old_fps != 60) {
    old_fps = 60;
    ms_per_frame = (int) (1000.0f / 60);
}

if (ragdoll_ms_remaining >= ms_per_frame) {
    ragdoll_ms_remaining -= ms_per_frame;
} else {
    ragdoll_ms_remaining = 0;
}

if (ragdoll_ms_remaining == 0) {
    turn_ragdoll_off();
}
gaunt ice
#

i finally found the place that states time.deltatime is affected by timescale

#

read the "Time Scale" section

little garden
#

like, i would do 1000.0f / 60 / cached_third_person_controller.world_current_scale right?

gaunt ice
#

where is the 60 comes from?

little garden
#

or rather

(1000.0f / 60 / cached_third_person_controller.world_current_scale) * cached_third_person_controller.player_current_scale

to also account for the player time scale in relation to the world scale ?

#

60 is the assumed target fps

#

as i currently use targetFrameRate for simulating heavy load

gaunt ice
#

then how you know your machine is actually running your game on 60fps?
btw get the deltatime first then further manipulate it

gilded pumice
#

can I invoke repeating in start with a delay like a coroutine?

#

or does invoke repeating always call the method every single second with nothing you can do about it?

little garden
#

i use 60 as an assumed target fps, later this would be changed to a game option to toggle between different target frame rates

#

not sure tho

#

since targetFrameRate affects how often Update is called and how much render time we get

#

(eg, 120 fps on a 120 hz monitor)

gaunt ice
#

as i said what if your machine not running your game in your targeted framerate...

#

eg if the cpu is busy

little garden
#

i guess i should rename it to

int target_FPS; // affects render + timers

int simulated_target_FPS; // affects render only
gilded pumice
#

is there a way to check a compare tag but only every so often?

novel shoal
#

what’s the input.getaxis axis for the keys A,D and W,S?

golden otter
golden otter
golden otter
#

You can add alternative buttons

novel shoal
#

ok ty

languid spire
#

of course it is, your code makes no sense

#

what do you think this

        if (Input.GetKeyUp(KeyCode.Space))
        {
            jumpForce = 10f;
            jumpForce = 0f;
        }

does?

novel shoal
#

it adds a force only once

languid spire
#

no it does not

novel shoal
#

bc otherwise it would give a constant speed on the Y

novel shoal
dire torrent
#

youre assigning it a value of 10f and then setting it to 0f on the same frame so at the end its the same as just doing jumpForce = 0f;

languid spire
#

it sets a variable to 10 then immediately back to 0, nothing more

novel shoal
languid spire
#

how would that help?

novel shoal
#

this way it will add a 10f force to the rigidbody in that frame, and the next will have an 0f force

languid spire
#

you are not even adding force you are just setting velocity

dire torrent
#

you need to "apply the force" when the key is pressed instead of applying it anyway

novel shoal
languid spire
#

not in this context it is not

novel shoal
#

i just modify it if the key is pressed

novel shoal
novel shoal
dire torrent
#

yes thats what you need to do but currently you're modifying the velocity regardless of if the key is pressed or not

novel shoal
#

i know i can just use rb.addforce but i wanted to try other things

dire torrent
#

you dont need to use rb.addforce if you're going for a certain type of movement

languid spire
#

velocity is the result of force not a force in itself

novel shoal
dire torrent
#
Rigidbody.velocity = new Vector3(horizontalInput, jumpForce, 0);

you're constantly applying the jumpForce here
what would be better is to only apply the jumpForce when the key is pressed

novel shoal
golden otter
#

could do += instead of =

dire torrent
little garden
#

why does 16.66667f / 0.999999f result in zero ?

warm fog
#

can someone help make 2d top down car which player can handle like in old GTA games
i am making a open world survival 2d topdown game in unity 2d
can someone help

dire torrent
#

a better way would be to ```cs
Rigidbody.velocity = new Vector3(horizontalInput, 0, 0);
if (space)
{
Rigidbody.velocity += new Vector3(0, jumpForce, 0);
}

novel shoal
dire torrent
#

dont need to
just keep it at 10f

#

whenever space is pressed, it should set velocity.y to 10f for 1 frame and then let physics do its thing

novel shoal
#

but this way the speed on the Yaxis remains 10 after the key is pressed

dire torrent
#

physics should reduce the speed automatically unless you have gravity disabled

novel shoal
#

i don't get it but ok

#

ty

dire torrent
#

oh actually there's gonna be a small issue lol

#

it's gonna reset velocity.y to 0 the next frame so its gonna be buggy. The way to fix it would be to not change the velocity.y at all when space is not pressed```cs
Rigidbody.velocity = new Vector3(horizontalInput, Rigidbody.velocity.y, 0);
if (Input.GetKeyUp(KeyCode.Space))
{
Rigidbody.velocity += new Vector3(0, jumpForce, 0);
}

dire torrent
#

is this a 3D game btw?
wondering why z velocity is always 0

dire torrent
#

oh i see

novel shoal
#

but it's my first game

dire torrent
#

yea that code should be fine

novel shoal
#

kind of a copy of another platform game

#

i hadn't other ideas about any other kind of game

#

oh hold on

#

i need to multiply the horizontalinput for the value of the force i want to add for time.deltatime

#

right?

dire torrent
#

yea multiplying horizontalInput by time.deltatime is better since it should make the movement in your game not be dependant on frame rate
actually it shouldnt matter if you use time.deltatime on it or not since you're setting it to a constant velocity

little garden
#

oof i was forgetting to set cached_third_person_controller to an instance

novel shoal
dire torrent
novel shoal
#

tried, now it works, thanks @dire torrent

wicked blaze
#

I dont really know how to fix this issues and it has always happens to me before but when i try to add an new feature all the other ones stop working and only the new one does, here is the code:

novel shoal
#

Cameraposition = GameObject.Find("Main Camera").GetComponent<Transform>().position;
is this a good way to make the camera follow the player? instead of using another script, just finding it and using its transform?

wicked blaze
dire torrent
novel shoal
dire torrent
dire torrent
wicked blaze
dire torrent
novel shoal
#

but then i still need to find the player gameobject to attach the camera to it

dire torrent
wicked blaze
dire torrent
novel shoal
dire torrent
# novel shoal 1 it is on the player script 2 i did bc the learn.unity tutorial used it a lot 3...

i did bc the learn.unity tutorial used it a lot
also forgot to reply about this, Find methods are a big beginner bait. It sounds really easy to just get the object you want by its name but there's lots of issues to this. What if you changed the name of the object at some point, you would have to go everywhere in your code where you referenced it by name and replace it. And find methods are very expensive too... If you have a whole bunch of objects in your scene, its gonna take longer for the Find method to get the object which is gonna make your game slower the bigger it gets.

novel shoal
dire torrent
novel shoal
dire torrent
#

so you're assigning playerTransform the value of gameObject.GetComponent<Transform>(). So it assigns the transform of the camera itself

distant robin
#

hi can someone tell me why the planes gameobject on my ""tree"" have such a weird behaviour?

dire torrent
#

just assign it through the inspector, and remove the line in Start

novel shoal
#

and with that code it works

#

no, wait it does not

dire torrent
#

yea it shouldnt because in Start you assign playerTransform back to the camera's transform itself

novel shoal
#

ok, i used playerTransform.GameObject.GetComponent<Transform>(); and it works

dire torrent
#

why though if you're already assigning it through inspector lol

#

playerTransform already has the value through the inspector. Assigning it again in Start wont do anything except maybe extra redundant calls

novel shoal
#

oh ok

#

transform.position = playerTransform.position + cameraOffset;
so i need just this line, right?

dire torrent
#

yes

novel shoal
#

ty dude for being patient

#

also, if something is private, does it mean it's less expensive?

dire torrent
# novel shoal also, if something is private, does it mean it's less expensive?

no but its better to make things private that arent being referenced from another script/class
good thing you ask because if your only purpose to make something public is to expose it to unity's inspector, you can use [SerializeField] instead.
so something like ```cs
[SerializeField] private Transform playerTransform;

novel shoal
#

but if the only purpose to make something public is to show it in the inspector, what's the point of making something show while making it private

wicked blaze
#

because its confusing