#archived-code-general

1 messages ยท Page 398 of 1

hidden compass
#

all sorts of casts out there.. i've barely begun to scratch the surface

robust trout
#

I'll see what I can figure out, that dark souls video is pretty helpful

halcyon swallow
#

why is colliderInstanceID 0 no matter what it contacts
it detects its hit a collider
it can tell me what the id of the cube is
but it wont tell me the id of the collider its just intersected with is

rustic rain
#

is there a callback I can get for when a component is added to a gameobject?

leaden ice
#

that's your own custom field

#

and presumably you never set it to anything except 0

halcyon swallow
#

is this not it?

leaden ice
#

hmm, that's a new one.

Can you try hit.collider.GetInstanceID()?

#

maybe there's a bug with that property. I've never seen it before

fast dune
#

is it safe to use a float as Dictionary key?

leaden ice
#

but it's "safe", and makes sense in certain specific circumstances.

#

what are you trying to do?

leaden ice
fast dune
# leaden ice what are you trying to do?

I have a mesh that stores a groupId for each vertex in UV2.x. the groupId is a timestamp value (float). I want to store the amount of vertices for each groupId. I was thinking of using a Dictionary<float,int> that maps groupId to vertex count

halcyon swallow
leaden ice
#

where are you populating hit

#

you're supposed to pass it as an out parameter to the Raycast

#

that also explains why that property is 0

halcyon swallow
leaden ice
#

nothing has written any data to it

#

if (Physics.Raycast(ray, out hit, 100))
For example

fast dune
leaden ice
#

Anyway the float will work just fine as a dictionary key, as long as you are using the exact same float when you try to retrieve the data later. It won't work well if you recalculate the key from something later.

#

So if you have a List<float> somewhere or something and you want to use those as keys and they will be exactly reused later, it's fine

#

If you are doing something like adding two floats together to count time up, and you want to use those as keys, that won't work well.

halcyon swallow
viscid atlas
#

any ideas for why my transform is set at the Player object instead of the selected Capsule?

viscid atlas
#

oh thank you, i feel dumb now haha

hexed pecan
#

"Center" mode just tries to guess the center of your object based on its renderer bounds and collider bounds

viscid atlas
#

i must have accidentally changed it at some point

rustic rain
#

does disallow multiple component attribute count for inherited classes too?

heady iris
#

misread as "added to more than one GameObject"

#

finally, highlander mode

rustic rain
#
float unscaledTime = Time.unscaledTime;
        float unscaledDeltaTime = Time.unscaledDeltaTime;
        Shader.SetGlobalVector("_UnscaledTime", new Vector4(unscaledTime, unscaledDeltaTime, 0f, 0f));
        print(Shader.GetGlobalVector("_UnscaledTime"));
#

am i using unscaled delta time correctly?

heady iris
#

it's a small number

#

a Vector4 gets printed with only two decimal digits by default

#

I think you can do...

#
vec.ToString("N4")

?

#

I don't actually remember..

#

N4 would be part of a numeric format string that means "normal number, 4 digits of precision"

#

but I could be making this up

hexed pecan
#

I use F4 but never bothered to look up the difference of N, D, F etc.

rustic rain
#

I just swapped around the unscaledDeltaTime and unscaledTime and it seems to work for what i want so

#

im not gonna pry any further lmao

heady iris
#

unscaledTime is time since startup

#

ish

#

the latter is true time since startup, and changes during a frame

#

generally not desirable

distant cypress
#

is anyone using VSCode (mac) and using tab for completions seeing completions have missing characters when accepting the completion?

#

I've tried all sorts of settings with completions, triggers, snippets, etc. and it just doesn't ever seem to complete with the whole suggestion - it always seems to miss a couple of characters depending on how much I've typed before accepting a completion using tab

rigid island
#

wonky lol but it has happened to me before though

distant cypress
#

yeah, it does the same thing when clicking, so it's not just the use of 'tab' as the completion key

#

it's driving me nuts having to go back and correct it all the time

hexed pecan
#

I never saw that issue with VSCode, what version of VSC are you running and what version of C# dev kit (if you have that)?

distant cypress
#

VSCode 1.96.2, c# 2.55.29, c# devkit 1.14.14 (macOS)

#

all latest - it's been happening for a while but can't remember when it really appeared

hexed pecan
#

Mine is 1.96.0, C# 2.31.19, C# dev kit also 1.14.14

#

Windows though.

distant cypress
#

I'll sync up the versions with a windows machine and see if it does the same thing

hexed pecan
#

I suggest taking a look at Rider, it became free for noncommercial use recently

distant cypress
#

I doubt it though as I'm sure more peeps would have noticed and reported it

hexed pecan
#

And when you start it up first time you can easily import settings and hotkeys from VSCode

distant cypress
#

yeah, I saw Rider went free. I have it installed but not tried it out yet

hexed pecan
#

Very painless transition

distant cypress
#

good to hear. Other devs I know use it and love it

hexed pecan
#

The only minus for me is the performance occasionally. But it's worth it imo

#

It doesn't like freeze completely, just chugs a bit sometimes

distant cypress
#

I was ready to jump when vscode and unity debugger were deprecated and finally going away, but then MS added a bunch of supported unity tooling again

hexed pecan
#

Yeah same, that made me stick to VSC for a while longer

distant cypress
#

it's become my all purpose text editor so it's hard to move ๐Ÿ™‚

hexed pecan
#

I used vsc for years but instantly rider feels like home already

#

And so many little QOL changes that just make me smile

distant cypress
#

I'm sure they wouldn't be misspelling code completions ๐Ÿ”ฅ

#

thanks for the reminder to check it out

kind willow
#

how do you access things from within your singleton FSMs?

#

I only create instances of states on the game start

#

I don't get why people tell to recreate them in guides, anyway, that's not what I am talk about

#
        public override void OnUpdate()
        {
            if (Inputer.instance.inputs.isStartingInput)
            {
                instance.fsm.ChangeState(instance.goingToStart);
                instance.playerMovementController.StartingGame();
            }
        }
#

I am having something like that

#

and need to typing the "instance" bugs me out a bit

#

what would you do instead?
or do you need more context?

#

instance is a singleton where all states, the FSM, and relevant data I want to interact within FSM being stored

#

I feel like I am getting into some kind of code structure management mistake

rigid island
zenith acorn
#

I'm kinda confused ๐Ÿ˜ญ

#

I have a code as below that uses the unity pool system

#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;

public class BulletPool : MonoBehaviour
{
    [SerializeField] private GameObject explodingBullet;
    [SerializeField] private GameObject forceFieldBullet;


    public static Dictionary<BulletType, ObjectPool<GameObject>> bulletPool;

    public enum BulletType
    {
        Explosion,
        Forcefield
    }

    private void Start()
    {
        bulletPool = new Dictionary<BulletType, ObjectPool<GameObject>>();
        ObjectPool<GameObject> pools;

        Debug.Log(explodingBullet);
        pools = new ObjectPool<GameObject>(()=>CreateBullet(explodingBullet), OnTakeBulletFromPool, OnReturnBulletToPool, OnDestroyBullet, true, 100, 1000);
        bulletPool.Add(BulletType.Explosion, pools);


        //pools = new ObjectPool<GameObject>(() => CreateBullet(forceFieldBullet), OnTakeBulletFromPool, OnReturnBulletToPool, OnDestroyBullet, true, 100, 1000);
        //bulletPool.Add(BulletType.Forcefield, pools);
    }

    private GameObject CreateBullet(GameObject bullet)
    {
        //Instatiate a new bullet if no bullet exist
        GameObject normalBullet = Instantiate(bullet);
        Debug.Log("Hello" + bullet);
        //normalBullet.SetPool(pool);

        return normalBullet;
    }

    private void OnTakeBulletFromPool(GameObject bullet)
    {
        //Set transform and rotation
        //bullet.transform.position = 
        //bullet.transform.right = 
        //Reset velocity

        //Activate
        //bullet.SetActive(true);
        Debug.Log("Hello" + bullet);
        Debug.Log(explodingBullet);
    }

    private void OnReturnBulletToPool(GameObject bullet)
    {
        bullet.SetActive(false);
    }

    private void OnDestroyBullet(GameObject bullet)
    {
        Destroy(bullet.gameObject);
    }
}
#

For some reason inside the ontakebulletfrompool it takes grenade out of nowhere

#

like it was supposed to be a explosion bullet pool

#

the grenade literally apppeared out of nowhere

#

๐Ÿ˜ญ

kind willow
open plover
#

How to check if Iโ€™m using a simulator in the editor

zenith acorn
#

It was working perfectly fine

#

until it start passing in grenade as a bullet parameter

#

I tried to debug and it says that the explodingbullet is still ExplodingBullet

#

but the bullet that was passed into the ontakebulletfrompool is a grenade

cosmic rain
arctic holly
#

Hi I am trying to use the TextMeshPro function isTextOverflowing but it keeps on giving me false when my text is obviously overflowing. Does anybody know why?

unkempt meadow
#

I don't know if this is the right channel but I'm having trouble with how I should set up the logic for my ik constraint environment interaction

#

so I have a system where the player will grab the environment once close to the wall, floor etc

#

it works great and I've got all kinds of things set up, such as rotation of the joints when player rotates while grabbing so you have no bone breakage etc

#

actually nvm this is the wrong channel for that

zenith acorn
#

Thanks for the info

hexed pecan
#

Do you understand the usecase of a singleton and is there a reason it is one?

hexed pecan
cosmic rain
# kind willow *bumps*

Honestly, I don't get the question either. If you're just looking to get rid of instance because it bugs you, I can't say that's reasonable.
Other than that, it seems to be super dependent on your whole implementation, so we can't help without seeing the code.

kind willow
#

yeah it's sheer fact of typing instance every time makes me feel like I am doing something wrong

kind willow
#

by whole gamestate I mean like what's going on, is game paused or playing normally or player is dead and can't do much but restart

cosmic rain
kind willow
#

I have a MonoBehaviour with a bunch of methods and fields, and a bunch of states and an FSM

#

where fsm do basically nothing but fiddle with those methods and fields

#

does that sound reasonable?

cosmic rain
cosmic rain
hexed pecan
#

Yeah this is all very vague to me

kind willow
#

"You shouldn't be chaining that many reference accesses that often"
Yeah, I figured already some time ago when I made myself deal with really really big chains of dots...
Trying to avoid that since, this one of two the reason I find this situation to typing instance weird

cosmic rain
cosmic rain
kind willow
#

yeah I just kinda ashamed of my code plus I don't think people like to read the whole files, but if you insist

#

I hope pastebin will do?

#

or whatever this is

#

it's not pastebin right

#

readme had a link on that tho

#

this is not exactly the case where main class have alot of fields and methods FSM uses

kind willow
#

on rethinking I should ve just made static fields there

cosmic rain
#

Mmm... Static fields is usually a bad idea.

kind willow
#

I mean, less dots?

cosmic rain
#

Are you planning to add many other states? Because, if not, then just keep it as is. There's not much point redoing something that works already.

kind willow
#

yeah I am not planning to add more stuff there

#

well, much more

#

some bits maybe

#

still feels kinda unnecessary to type instance. every time

cosmic rain
#

Then maybe keep it as is.
For future reference, you could have constructors for your states and pass in all the required dependencies and references at that point. That way you'll be able to call methods directly on the dependency.

astral nexus
#

(Initially posted into wrong channel by mistake, lel)

I want to implement some sort of a system that gives "capabilities and constraints" for every game entity in my game based on their current state. For example: if player is in moving state - they can attack or jump, but not talk with NPCs or pick up items. I hope that explains what I mean by capabilities and constraints for objects.
How can I achieve it? I was thinking about combining state machine and feed into states some commands from command pattern, so I don't need to use some sort of bool flags in my states, etc. Is it good approach or there are easier/more "practical" ways to achieve it?

kind willow
#

does that feeling wrong?

kind willow
cosmic rain
cosmic rain
cosmic rain
kind willow
cosmic rain
# kind willow trying to avoid pitfalls too hard

The biggest pitfall you might ever have is wasting too much time on things that don't matter as much and unable to complete your game because of that. Worrying about non existing performance issues is one such pitfall.

#

Get something working. You can always refactor it.

kind willow
#

oh I made something working

cosmic rain
#

That being said, it's fine to ask about things that you're worried about. I hope the conversation gave you some insights.

kind willow
#

I already released one shitty game and now trying to do stuff more properly

pearl burrow
#

Hi! When to consider using a simple animation vs updating some value in the update function? My use case is I need the animate a little icon on my gameobject, the icon would slowly float up and down so really simple.
For things like this what's the best to do? updating the transform in update or just a plain animation?

leaden ice
#

but it's up to you.

cosmic rain
pearl burrow
#

thank you!

dire crown
#

Hellu, I've made a Terrain Data file in the editor through code, I would like to be able to save everything I configured as a .asset that can be reimported, without losing referencces to the Terrain Layers, details or trees. How can I properly do that?

I tried this which saves the terrain data asset, but all the references are lost

var data = terrain.terrainData;
string path = string.Format("{0}/Exports/{1}", Application.dataPath, generator.graph.name);
if(!Directory.Exists(path))
    Directory.CreateDirectory(path);
string relativeFolder = "Assets" + path.Substring(Application.dataPath.Length);
string filePath = string.Format("{0}/{1}.asset",relativeFolder,data.name);
AssetDatabase.CreateAsset(data, filePath);
AssetDatabase.SaveAssets();
dense swan
#

Where am I supposed to save this file if I wanted to use "Something" namespace?

wheat spruce
dense swan
wheat spruce
#

well thats more to give a warning as its a good practise for the folder names to match the namespaces

#

its mostly there as VS can be set up so when you create a new file, it uses the folder directory to automatically fill in the namespace

chilly surge
#

(VS Code can also do the same)

#

But yes it's a convention to match file system structure with namespace structure so it's easier to know where everything is, but it's not required for it to work.

#

The diagnostic is mostly there for the purpose of refactoring.

dense swan
wheat spruce
#

you can right click the warning to supress it

heady iris
chilly surge
#

I'm not sure if the diagnostic properly takes into account Unity's Assets folder structure, but if it does, then you would need to move your namespace to Scripts.Something or move your folder to Assets/Something rather than under Scripts.

heady iris
#

Using an asmdef can make it explicit

#

I have all scripts in Assets/Scripts/, and there's an asmdef in that folder that defines the root namespace,

#

so something in Assets/Scripts/Foo/Bar winds up being RootNamespace.Foo.Bar

wheat spruce
#

or maybe it'll do assets/scripts

chilly surge
#

Yeah I don't do the "organize by file type" like Scripts/Textures/AudioClips/whatever, I find that to be largely pointless.

heady iris
#

I organize by type for things that don't have much of an identity

wheat spruce
heady iris
#

all assets for a characater go in a folder for that character, since they cleraly belong together

wheat spruce
#

hell, I dont even like calling the main .cs folder folder "scripts"

#

I used to do it, but now the idea of referring to C# code as "a script" made me think something doesnt sound right

#

I feel like that was some legacy thing back when Unity supported Javascript

viscid atlas
#

does anyone have ideas as to why my camera target moves to the feet of the player capsule despite the parented camArm object being at the player's head?

void Update()
    {
        camTarget.position = transform.forward.normalized * -1 * camDistance;
        camTransform.position = Vector3.Lerp(camTransform.position, camTarget.position, positionLerpSpeed);
        camTransform.rotation = Quaternion.Lerp(camTransform.rotation, camTarget.rotation, rotationSpeed);

the script is attached to camArm

wheat spruce
#

"source" or "src" makes far more sense over "scripts"

warm badger
#

is there any way to take control of detail distance of particular detail instance of terrain using script or something?

heady iris
#

Perhaps you meant to set localPosition!

#

That would set your position relative to your parent

viscid atlas
#

oh i guess that makes sense now that i look at it, i was trying to put the camera behind the forward axis of the camArm gameobject with that line

heady iris
#

Note that you won't want transform.forward in that case

#

since that's a world-space direction

#

You'd just do Vector3.back.

viscid atlas
#

woah, thank you! that's a lot simpler than what i was trying haha

#

works perfectly now, thanks :D

spare swallow
#

I've got quite a strange issue which is likely due to improper initialization?

Debug.Log("Debugging Place/Swap, GetItem: " + menu.storage.items[slotNumber]);
if (menu.storage.items[slotNumber].GetItem() == null) // if no item in this slot (Place): (ERRORS)

This is a part of my storage system, where a storage container (such as a chest) is given a "StorageInteractable" class/component which contains a "StorageContainer" class which is initialized upon being placed, and upon interacting with the "StorageInteractable" class, a menu will be opened which passes the "StorageContainer" variable stored on the "StorageInteractable". However, on the second line of the menu slot class I get a "NullReferenceExceptionError" which is very odd considering the fact that the line above confirms that the "menu.storage.items[slotNumber]" is not in-fact null. The only fix I have found is to manually click on either the "Chest" gameobject or the Chest's menu gameobject, both of which contain a reference to the Chest's "StorageContainer" class.

spare swallow
knotty sun
#

but what if menu, menu.storage and/or menu.storage.items are null?

#

and you could be trying to call GetItem on a null

leaden ice
spare swallow
#

Yeah, I'll try to ensure I've checked everything again. But I am nearly certain everything is initialized and correctly set.

knotty sun
#

nearly certain means you are assuming, dont

heady iris
#

"close" only counts in horseshoes and hand grenades (:

spare swallow
#

Just adding a log to everything in the tree of functions to check for nulls

knotty sun
heady iris
#

are you certain that the exception isn't actually happening in GetItem()? what does the stack trace look like?

#

also make sure that you don't have Collapse enabled in the console, which could produce misleading logs

#

but yes -- if you can evaluate menu.storage.items[slotNumber] without an NRE being thrown and without getting a null result, then none of those references are null

#

assuming none of these are actually properties, at which point all bets are off (:

heady iris
#

I think it's trying to guess what is "your code" and what is "library code"

spare swallow
# heady iris Unity will sometimes open the wrong file when you double click on an error.

Yeah the error is being thrown in my "MenuItemSlot" class, which is a part of my menu class, I have logged everything in said class now and:

            if (menu == null)
            {
                Debug.Log("Menu is Null"); // NO ERROR
            }
            if (menu.storage == null)
            {
                Debug.Log("Menu Storage is Null"); // NO ERROR
            }
            if (menu.storage.items[slotNumber] == null)
            {
                Debug.Log("Menu Storage Slot Number: + " + slotNumber + " is Null"); // NO ERROR
            }
            if (menu.storage.items[slotNumber].GetItem() == null) // ERROR
            {
                Debug.Log("Menu Storage Slot Number: + " + slotNumber + " GetItem() is Null");
            }
spare swallow
# spare swallow

77:

if (menu.storage.items[slotNumber].GetItem() == null) // ERROR
heady iris
#

what does GetItem do? I have to wonder if it's getting inlined. I could be hallucinating, but I think I've seen that happen before.

spare swallow
#

GetItem():

public ItemClass GetItem() { if (item != null) { return item; } else { return null; } }

^ Current:

public ItemClass GetItem() { return item }

^ tried

heady iris
#

notably, show that all of those log messages did not get printed

spare swallow
#

Is there a way to copy the entire console?

heady iris
#

Just show a reasonable number of messages before the error.

#

Also ensure that Collapse is disabled.

spare swallow
#

Alright, sec.

heady iris
#

(and that you aren't hiding any of the log categories)

#

e.g. this hides informational log entries

spare swallow
knotty sun
#

there is your answer right in front of your nose

heady iris
#

lol

spare swallow
#

Yes, but why is that null.

#

Only when I click in the inspector does it populate is the assumption

knotty sun
fossil blaze
#

hey

heady iris
#

I believe you'll get an empty string.

heady iris
#

I was under the impression you'd checked the log message!

spare swallow
heady iris
#

well, it's null because...it's null

#

put something in it

heady iris
#

e.g. creating an empty list to put in a List<int> field

#

viewing it in the inspector would cause this

spare swallow
#
        newDeployable.AddComponent<StorageInteractable>();
        newDeployable.layer = LayerMask.NameToLayer("Deployable");
        newDeployable.GetComponent<StorageInteractable>().storage = new StorageContainer(new SlotData[20]);
#

This is called after being created, is this not sufficient?

heady iris
#

what do you expect that array to contain?

#

if SlotData is a reference type, it will contain 20 null references

#

it doesn't immediately try to construct 20 instances of SlotData

spare swallow
heady iris
#

(what if SlotData has no default constructor?)

#

You need to actually put things in the array

spare swallow
#
    public SlotData()
    {
        item = null;
        quantity = 0;
    }
knotty sun
heady iris
fossil blaze
#

Hi everyone! How can I make the button trigger only in this case?

heady iris
#

it would also be ridiculous to construct a bunch of instances of the type if you were going to immediately fill the array with your own instances

knotty sun
#

new SlotData[20] is 20 nulls which MAY contain a SlotData

fossil blaze
#

because the push I'm doing right now could go either way.

spare swallow
#

The intended result is creating 20 Empty "SlotData" with a default of "item == null", "Quantity == 0"

heady iris
#

context.performed , specifically

heady iris
knotty sun
heady iris
#

Wishful thinking has no effect on the .NET runtime!

#

alas

fossil blaze
heady iris
#

I thought you meant it was triggering both when you pushed and released the button

fossil blaze
spare swallow
heady iris
#

Sounds like you need to have UseComputer check something before doing anything

heady iris
#

Why doesn't int x; have a default value of 10?

knotty sun
heady iris
#

If it was a value type, then yes, you'd have an array of 20 objects in some sort of default state. That's because value types aren't referenced. They're stored directly.

#

default for any reference type is a null reference

fossil blaze
spare swallow
#

This isn't a great example since "int" is not a class, but my "SlotData" is a class with variables and a default constructor to assign those variables to all instances? What would be the point of a constructor at all?

fossil blaze
#

right here

heady iris
#

Why would this create 20 SlotData objects?

fossil blaze
#

I also don't understand why the camera doesn't change when you press it?

#

it doesn't even display logs.

knotty sun
fossil blaze
#

about what, how do I know?

spare swallow
heady iris
#

This is conceptually identical to expecting this to work:

SlotData foo;
foo.quantity = 123;
#

(different kind of error, same premise)

spare swallow
#

May I then ask what is the point in ever setting the "Quantity" Of an array of a type?

heady iris
#

because an array has a fixed size...

knotty sun
heady iris
#

i would suggest reading the docs

heady iris
#

such as...

#
foreach (var item in items)
  item.quantity = 100; // error

SlotData item = items[0];
item.quanity = 100; // items[0].quantity is still zero
knotty sun
#

as OP doesn't seem to know the difference between value and reference types I doubt that will be a problem

spare swallow
#

It was, in-fact a problem.

#

I'm just gonna figure this one out. Appreciate you guys.

#

This ended up being the solution:

        SlotData[] slots = new SlotData[20];
        for (int i = 0; i < slots.Length; i++)
        {
            slots[i] = new SlotData(null, 0);
        }

        newDeployable.AddComponent<StorageInteractable>();
        newDeployable.layer = LayerMask.NameToLayer("Deployable");
        newDeployable.GetComponent<StorageInteractable>().storage = new StorageContainer(slots);
heady iris
#

That looks reasonable, yes.

spare swallow
#

I was hoping there would be a way to by default add "default" values but I guess it really doesn't matter either way.

heady iris
#

Well, you kind of did get default values (:

spare swallow
heady iris
fossil blaze
knotty sun
# fossil blaze why?

How is anyone but you supposed to know why based on the snippet you posted. It's not being called because you are not calling it

fossil blaze
#

how do you do it?

knotty sun
#

what call a method?

fossil blaze
#

I need to be able to use it here if it's successful.

#

and also for some reason it doesn't work even logs.

knotty sun
#

So, managerComputer is null. Why?

fossil blaze
#

where?

knotty sun
#

and, please do NOT post screenshots of code\

#

post the code correctly and I will show you

#

also, just look at the code you posted. Where do you use managerComputer? what does ? mean ?

fossil blaze
#

I use it on the manager's computer

knotty sun
#

where in the code you just posted?

fossil blaze
knotty sun
fossil blaze
#

can I post the code here?

knotty sun
#

why would you need to. You already did albeit it badly

#

so in the line of code you highlighted what does the ? mean

fossil blaze
#

NullReferenceException: Object reference not set to an instance of an object
PickUpAndDrop.PlayerInputHandler.UseComputer (UnityEngine.InputSystem.InputAction+CallbackContext context) (at Assets/Scripts/PickUpAndDrop/PlayerInputHandler.cs:127)
UnityEngine.InputSystem.Utilities.DelegateHelpers.InvokeCallbacksSafe[TValue] (UnityEngine.InputSystem.Utilities.CallbackArray1[System.Action1[TValue]]& callbacks, TValue argument, System.String callbackName, System.Object context) (at ./Library/PackageCache/com.unity.inputsystem/InputSystem/Utilities/DelegateHelpers.cs:46)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)

#

Now I'm getting an error

knotty sun
#

ok, so as I said. managerComputer is null

fossil blaze
#

private void UseComputer(InputAction.CallbackContext context)
        {
            Debug.Log("Interacting with computer...");
            managerComputer.UseComputer();
        }
gray mural
#

Within my tilemap, I have specific blocks, which each take 1 cell. The gravity can be applied at the beginning of the game and when the blocks are moved by the player. While falling, the block's position will not be an integer, and will be an integer, when the fall is over.
How should I implement this behavior? I don't think you can apply gravity with Rigidbody on tiles.

knotty sun
#

and by adding the ? you added a non fail null check

fossil blaze
knotty sun
#

explain to me what this line of code does

managerComputer?.UseComputer();
fossil blaze
#

finds this method in the managerComputer script to use it on the mouse key

knotty sun
#

no

fossil blaze
#

Why? What am I doing wrong?

#

public void UseComputer()
        {
            Debug.Log("Switching to computer camera");
            mainCamera.SetActive(false);
            computerCamera.SetActive(true);
            isUsingComputer = true;

            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;

            DisableOutline();
        }```
knotty sun
#

this

managerComputer?.UseComputer();

is the same as

if (managerComputer != null) managerComputer.UseComputer();
#

and as managerComputer IS null the method is never being called

fossil blaze
#

How do I then call this method when I click?

knotty sun
#

find out WHY managerComputer is null and fix it

fossil blaze
knotty sun
#

ok, so where do you declare managerComputer

fossil blaze
#

public class PlayerInputHandler : MonoBehaviour
    {
        private PlayerInput playerInput;
        private ItemHandler itemHandler;
        private CarryHandler carryHandler;
        private PickUpDropPanels pickUpDropPanels;
        private WarningPanelManager warningPanelManager;
        private AudioSource pickUpSource;
        private ManagerComputer managerComputer;

        private void Awake()
        {
            playerInput = new PlayerInput();
            itemHandler = GetComponent<ItemHandler>();
            carryHandler = GetComponent<CarryHandler>();
            managerComputer = GetComponent<ManagerComputer>();
        }
knotty sun
#

ok, so that's the declaration and this

managerComputer = GetComponent<ManagerComputer>();

is doing the assignment.
Obviously the assignment is failing.
Is the component ManagerComputer on the gameobject to which this script is attached?

fossil blaze
#

No, this script is attached to the object I'm looking at, and PlayerInputHandler hangs on the player.

knotty sun
#

so why would you expect the GetComponent to work?

fossil blaze
knotty sun
#

you can Serialize the variable rather than making it public (preferred option) and set it in the inspector
or there is the FindObjectOfType method at a pinch (not recommended)

simple saffron
#

This is going to be such a stupid question, I know it right now, but how on earth does

grappleTargetPos = (grappleThrowSpeed * grappleTime * myController.Controller.headTransform.forward) + myController.Controller.headTransform.position;

where grappleTargetPos is a vector3, grappleThrowSpeed = 25f and grappleTime = 1f, always equal JUST the position of that head transform?

#

oh

#

wait

#

ok ignore me sorry

#

I have two similarly named variables, grappleTime and grappleThrowTime. i meant to use grappleThrowTime

knotty sun
# fossil blaze

You are allowed to read the message yourself, I dont need to read it for you

fossil blaze
#

I take it this is obsolete in Unity 6.

knotty sun
#

yes, so use the alternative it tells you to use

fossil blaze
#

[SerializeField] private ManagerComputer managerComputer;

        private void Awake()
        {
            playerInput = new PlayerInput();
            itemHandler = GetComponent<ItemHandler>();
            carryHandler = GetComponent<CarryHandler>();
            managerComputer = GetComponent<ManagerComputer>();
        }
#

I did that and put the component

knotty sun
#

you need to remove the GetComponent if you are going to set a value in the inspector. Have you done ANY C# and Unity basic courses?

simple saffron
#

if you're brand new to unity scripting, i'd strongly recommend code monkey. He does a lot of in depth tutorials and explains his methods too, rather than just spoonfeeding you code without "just" telling you what to do

simple saffron
#

GetComponent is only needed if you are not manually assigning a reference

simple saffron
#

are you dragging computer manager into that box in edit mode

fossil blaze
#

Now it works, but I don't understand how to limit the button pressing if the raycast doesn't hit the object.

#

because I can press that button anytime I want.

#

private void HandleRaycast()
        {
            if (Physics.Raycast(mainCamera.transform.position, mainCamera.transform.forward, out hitInfo, raycastRange, computerLayerMask))
            {
                if (hitInfo.collider.gameObject == gameObject)
                {
                    computerUseUI.SetActive(true);
                    EnableOutline();
                }
                else
                {
                    DisableOutline();
                    computerUseUI.SetActive(false);
                }
            }
            else
            {
                DisableOutline();
                computerUseUI.SetActive(false);
            }
        }
#

if (hitInfo.collider.gameObject == gameObject)
                {
                    computerUseUI.SetActive(true);
                    EnableOutline();
                }
simple saffron
#

i dont really understand what you mean

fossil blaze
#

here's how to make the button permission?

#

private void UseComputer(InputAction.CallbackContext context)
        {
            Debug.Log("Interacting with computer...");
            managerComputer?.UseComputer();
        }

simple saffron
#

what does UseComputer do

#

does it do call anything at all?

fossil blaze
#

Yeah, I switch the camera that looks at the computer screen.

simple saffron
#

okay

fossil blaze
#

public void UseComputer()
        {
            Debug.Log("Switching to computer camera");
            mainCamera.SetActive(false);
            computerCamera.SetActive(true);
            isUsingComputer = true;

            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;

            DisableOutline();
        }


simple saffron
#

then you need to figure out a way for UseComputer() to know whether or not HandleRaycast hits anything

#

it doesn't just know

fossil blaze
#

You mean add raycast to it, too?

simple saffron
#

if that's what you want to do

#

it looks like you're not setting anything or doing anything at all other than, presumably, activating an outline

fossil blaze
#

HandleRaycast() and you can't do that in this method?

simple saffron
#

HandleRaycast doesn't return anything

#

it doesn't set anything

#

it doesn't DO anything other than enable or disable the ui and outline

#

if you tell someone to go buy something
they go buy it
but they never come back, never text you

#

how do you know they bought it?

#

in this example

  • calling the method is asking your friend to buy you something
  • the code executing is them going to buy it
  • setting/returning something to say "you can interact with the computer" would be your friend bringing that thing back, or texting you to say they got it
fossil blaze
#

You're confusing me, I'm still a beginner.

simple saffron
#

you aren't setting anything to say that you can interact with the fcomputer

#

i've said it multiple times

#

im not feeding you the answer

#

but here's a helpful hint
boolean

#

do with that what you will

fossil blaze
#

it all worked out.

hollow hound
#

I want to do some logic when the particle system stops. I can't use OnParticleSystemStopped because I want to control its behaviour from the script that are not connected to the same GO.
Ideally I want something like

      foreach (var system in _particleSystems)
      {
        var main = system.main;
        main.onStop += HandleStop;
      }

And I don't want to go to every particle syste and add a script to its GO with OnParticleSystemStopped which will fire onStop.
Is there an adequate non-kludgy solution for this?

swift falcon
unkempt meadow
#

I have a problem which I'm not sure how to go about fixing.

I have an IK chain constrain set up to place my hands onto the environment with all kinds of logic and it works fine except in one instance:

I have tight tunnels which the player must crawl through. Normally I have a point parented to the player just offset by some amount on the Z to shoot raycasts (down first) to figure out where to place the hands

#

intention is to make it seem like the player is grabbing the terrain floor and pulling himself forward

#

but in these tight tunnels it doesn't work due to a couple of reasons. First if the player rotates toward the floor, the point raycast point goes beyond the floor or if he is close to a wall, it goes beyond that too

#

I can have a sharp turn where the point is beyond the tunnel mesh on the turn, so the hand clips through the wall

#

best I can do functionally is to shoot a raycast forward from the camera but it looks stupid if I'm looking down, for example, and the player just grabs the floor point instead of reaching forward

#

I thought of all kinds of solution but each of them have some kind of problem

#

I thought of even baking a navmesh in the tunnel and making a tiny navmesh agent run ahead of the player, up to a certain distance, and that navmesh agent would be the point of raycast so I could always keep it ahead in the traversable section

#

it's a silly solution but it would work were it not for the fact that I have intersections and I can turn around to go the opposite direction, so how would the agent know where to go

#

sorry for the long post, I'm just stuck here and want to hear ideas on what kind of logic might solve this

heady iris
#

I was playing with a vaguely similar problem when prototyping a parkour game. Figuring out where to put your hands can get tricky.

heady iris
#

It sounds like it should match the direction you're trying to move in

unkempt meadow
#

but unfortunately that won't work either

#

or at least not perfectly

#

what if I reach a sharp turn and I'm just continuing to a wall in front of me

#

I'd rather have the hands grab left/right in the direction of the turn

#

I did think of that

heady iris
#

Is this "on rails", where holding forward automatically makes you follow the turn?

unkempt meadow
#

no

heady iris
#

or should the player just start bumping into the wall until they turn their head?

unkempt meadow
#

I actually made it freeform movement

#

just simple controller move moving

heady iris
#

You need to find the most reasonable position given the current obstacles and the intended direction of movement

unkempt meadow
#

yes

heady iris
#

I'd consider starting with a raycast exactly in the direction of movement to find the "origin point", then another raycast straight down to find a ground patch to grab

unkempt meadow
#

that's what I'm stuuck on

heady iris
#

If this raycast doesn't make it far enough, then you need to try less optimal positions

unkempt meadow
#

well what if I'm looking down?

heady iris
#

you still move forwards when looking down, right?

unkempt meadow
#

ah direction of movement, yes

#

yes yes

heady iris
#

yeah, use the same logic there

#

You might be able to come up with a "score" for a hand position

unkempt meadow
#

I kind of do that already

heady iris
#

the score goes down if it's too far from the ideal hand position (which is what you'd get if you have no obstacles in the way)

unkempt meadow
#

well not quite

#

but I do a short raycast down, if it doesn't reach, then raycast right (for right arm) and left for left arm

heady iris
#

You can search until you get a high enough score (with your standards gradually slipping to guarantee you find something)

unkempt meadow
#

it's not quite same but

heady iris
unkempt meadow
#

I am also taking the move vector into considerations anyway

#

because

#

I forgot to mention

north hatch
#

Does anyone know how to make vhs effect or have a tutorial that i can watch?

sterile reef
#

question, with unity 6 when adding a new script to a game object, the default language is c#, how would i change this?

unkempt meadow
#

because when I'm moving backward, I don't want my hand to be too far in front because that wouldn't make sense in sense of pushing forces

#

so when I'm moving backward, I'm raycasting from a position closer to the player

sterile reef
#

c# is garbage

#

imo

#

no offense to you guys

spare dome
#

Unity uses C# as its scripting language

#

afaik you cannot change that

unkempt meadow
unkempt meadow
heady iris
sterile reef
#

brah

heady iris
#

mysterious

spare dome
fleet basin
#

But why is it garbage? Curious what your thoughts are , what you would rather see?

sterile reef
#

c plus plus

#

is a blocked word in this discord?

#

๐Ÿ˜‚

heady iris
#

probably because the server tends to filter very short responses

#

c++ by itself is exactly one letter

sterile reef
#

lets try this c++

#

ah

#

ur right

fleet basin
#

๐Ÿ˜‚

spare dome
#

But anyway, unity does not support any other scripting language other than C#

sterile reef
#

thats unfortunate

#

goodbye unity ๐Ÿ™‚

spare dome
#

It works for me

fleet basin
#

Im unreal dev i just saw the Reddit posts about fog power tripping and wanted to see,

spare dome
#

I see no issue with it

languid hound
#

No language except JavaScript is objectively bad since they all server different purposes

sterile reef
#

c# reminds me too much of java ๐Ÿคฎ

languid hound
fleet basin
#

C# is fine for general oop classes etc imo

heady iris
#

it's the much cooler Java

languid hound
#

Except the fact that Java literally hacks itself first thing to look more OOP

sterile reef
unkempt meadow
#

@heady iris ah yes I remembered the problem, of course.

It's a cave diving game so holding W while looking down won't move me forward, depending on the angle

#

That was the problem

#

Point being, I move in 3d

#

I might just have to a use a simple controller in these tight sections

#

Is that the solutipn?

languid hound
#

Are you on about looking 90 degrees up or down causing you to not move?

#

A lot of games have a "compass" that tracks the camera's y rotation and they use that for move directions instead if that's your issue

heady iris
#

I wonder how you should handle that

#

beyond just clamping the X rotation to like

#

-89 ... 89

unkempt meadow
#

Yeah yeah

sterile reef
unkempt meadow
#

I was thinking along those lines

#

It's a bit complicated

sterile reef
#

and optimizations

unkempt meadow
#

My brain hurts

heady iris
#

as a core language feature

unkempt meadow
#

I came up with an entirely riduculous solution that almkst works but doesn't

spare dome
#

I have zero clue why

heady iris
# heady iris -89 ... 89

I guess that, if movement fails, you could try rotating the movement vector around your local X axis

sterile reef
#

also c# was built by microsoft to resemble java and runs as managed language where .net framework helps manage memory and other inefficient tasks

heady iris
#

especially if you're allowed to go completely upside-down

#

(rather than your up-and-down aiming being clamped to [-90..90]

unkempt meadow
languid hound
#

I don't entirely understand your solution then because I had a similar issue and that fixed it

#

Not solution sorry I mean issue

unkempt meadow
#

Well did you read the problem from the beginning?

languid hound
#

Yeah that's why I suggested the fix I use

#

Oh wait

#

You mean the start start

#

I don't think I was even here when you first asked. My bad

unkempt meadow
#

as opposed to 90, where I wouldn't move forward?

unkempt meadow
languid hound
#

The compass will never look up or down and so it can only reach forward

#

Ah

#

You already tried something similar

unkempt meadow
#

I mean, I guess that would ultimately achieve the same thing as Fen's suggestion

#

i.e. the compass Z would be the same as the movement direction of the player

#

although now that I think of it, I think Fen's solution wouldn't work because, as I said, it's a cave diving game so I'm not sticking to the floor.

There could be a case where I'm a bit up from the ground and my movement direction would still be down if the I get the movement direction at that moment

chrome trail
#

As you can see from the GIF, the goal is to have it so that the script displays a sort of movement radius around the player as a mesh then convert that into a decal whenever the cursor hovers over the character (Conversely the mesh is meant to be disposed of whenever the cursor leaves the character bounds). While the mesh is properly displayed the first time the mouse hovers over the character, every subsequent time I hover over the character the mesh doesn't appear and I don't know why.

https://cdn.discordapp.com/attachments/493511448639832085/1320140016621719653/Blink.gif?ex=676883b2&is=67673232&hm=4fcdb3e10b9dcae318d1decce2226586a105944c57d86489745df8611433f4e3&

hollow hound
#

I want to do some logic when the particle system stops. I can't use OnParticleSystemStopped because I want to control its behaviour from the script that are not connected to the same GO.
Ideally I want something like ```cs
foreach (var system in _particleSystems)
{
var main = system.main;
main.onStop += HandleStop;
}

Is there an adequate non-kludgy solution for this?
fickle crown
#

Hi, a quick question, how do I move settings from one lobby (let's say lobby scene), to another scene (let's say gameplay scene) ?

heady iris
#

If you don't want to manually attach it to each object with a particle system, you could write a method that gets it if it exists, and otherwise attaches it and sets it up if it doesn't

#

so you'll wind up doing

#
particleSystem.GetOrCreateNotifier().OnStop += whatever;
#

it could be an extension method!

#
public static class ParticleSystemExtensions {
  public static ParticleNotifier GetOrCreateNotifier(this ParticleSystem ps) {
    if (ps.TryGetComponent(out ParticleNotifier notifier)) {
       return notifier;
    }
    
    notifier = ps.gameObject.AddComponent<ParticleNotifier>();
    // maybe do some setup here?
    return notifier;
  }
}
#

Like so

heady iris
#

It is appropriate if there's only one ever set of settings active at a time

halcyon swallow
#

rigidbody.drag no longer seems to exist
is rigidbody.lineardamping the same thing?

heady iris
#

Yes.

halcyon swallow
#

why the re name

fickle crown
heady iris
#

It's more consistent with how angular damping and velocity are named, I guess

#

I believe "Damping" is also more accurate of a name than "Drag". It's not accurate air drag

#

It's just a force that's directly proportional to the current speed

halcyon swallow
#

no that is drag
i guess damping just sounds more scientific because theres no actual air simulation

heady iris
#

air drag is proportional to the square of your speed

#

(or worse!)

mighty juniper
#

for a [SerializeField]'d float in a script, is there any way to force it to be positive or zero, without setting an upper limit?

heady iris
#

You can constrain its value in OnValidate

#

(the actual intended use of OnValidate, for once!)

#

I don't think there's a handy attribute you can use, though

#

(i bet NaughtyAttributes has one, though)

mighty juniper
mighty juniper
mighty juniper
#

oh i didnt even realise that existed by default haha, thanks

cold parrot
#

Naughty is a good to have regardless

tranquil rover
#

I want to log an error when an object is destroyed prematurely, but not during scene changes which call OnDestroy. Only when its destroyed via inspector or Destroy(gameobject). Is there another callback I can use or way I can check if the scene is currently changing?

cosmic rain
raven bobcat
#

I have a game idea in my mind, but don't know how to achieve that:

I want to make a game that allow you to craft a gun. Each gun contain 3 parts, scope, barrel, and body. After player put all three part together in the crafting table, it become a gun(one object) that allow you to store in the inventory.

I want to code a inventory system that allow you to store the gun and other parts. What are some possble approaches I could try?

raven bobcat
# rigid island ScriptableObjects

I look up some scriptable object tutorials on YouTube, but the question is how do i combine 3 scriptable objects(scope, barrel, body) into one when crafting the gun?

rigid island
#

you need like 4 SO fields
scope, barrel, body
output (this can also just be a prefab depending how you plan on making your guns)

rain minnow
#

honestly, think of it like crafting a recipe. you need 3 ingredients (gun parts) to make the recipe (gun) . . .

raven bobcat
#

But the gun isn't really a recipe, the stat of the gun is just all the part's stat added together

rain minnow
#

yeah, the last partโ€”the gunโ€”can be created a few different ways . . .

rigid island
#

scope barrel body

raven bobcat
#

Hum...OK, I think I have an idea. THX

rain minnow
#

you'd have a gun script though. that can store a list of the gun parts (or separate fields for each). you can place the stats on the same script and cycle through the list to add all the stats from the parts. a duplicate stat would add to the current value of the same stat . . .

raven bobcat
#

Wait, I though you cannot create a scriptable object in run time

rigid island
#

you can but why do you want to create them at runtime

rain minnow
rigid island
#

if the parts have to have stats you need to make fields for those specific

#

eg
Scope
float zoomAmount;
etc.

raven bobcat
#

I think I got the idea now thanks

#

Let me try it first and see if I need to come back latertryitandsee

#

Thx

halcyon swallow
#

this code makes a ray from the objects origin, down a few meters
any clues as to why the ray is consistently several meters behind and diagonal from the actual object?

#

never mind

cosmic rain
halcyon swallow
#

yeah
somehow the children of the object all had their transform position far away
despite being visually on the parent game object
no idea how this happened or why it doesnt show them in their accurate locations but yeah, fixed

light fulcrum
#

https://paste.ofcode.org/zY2kRVxPx7UcZ3r8ZXvqZS

Local idiot returns with question

So I have this script that activates my canvas with my dialogue box and text, replacing the sample text with what I enter in the inspector, which works! However, its also supposed to split the text up when it reaches 250 characters so the player can cycle through longer dialogue, but this part doesnt work. It just shows the first 250 characters and pressing E doesnt cycle OR close the dialogue box; youre just kind of stuck. Any idea where its going wrong?

Edit: ALSO, sometimes (ONLY sometimes), certain objects' dialogue wont pop up once you leave and reenter a scene

soft shard
# light fulcrum https://paste.ofcode.org/zY2kRVxPx7UcZ3r8ZXvqZS Local idiot returns with questi...

TextMeshPro actually has a mode for this you can setup from the inspector, its called "Page": https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/manual/TMPObjectUIText.html#wrapping-and-overflow - you can then set an index to represent which "page" to display - if youd want to try to fix some of the issues you mentioned in your code, maybe you can make your private variables public so you can see what value they are compared to what you expect them to be, you could also add some Debug logs to make sure the correct functions and block of code are executing when expected

light fulcrum
# soft shard TextMeshPro actually has a mode for this you can setup from the inspector, its c...

Well Page DOES seem to be what I want; ive not been able to figure out how to hook that up to my dialogue script tho. What's been happening is that, say I have 10 lines of text and only 4 fit on screen at once. It will display only the 1st 4 lines and then the player can't do anything (cant cycle through pages or close dialogue) until all 10 lines are finished printing in the inspector (after which we can only close the dialogue box, not cycle), and we're stuck on page 1 thonk

gonna keep trying, i think im just stupid

whole sorrel
#

I have a question

I was trying to understand how async / await works and there's something I really don't get. Quoting this article:

To use async/await, you first need to declare your method as async. This tells the compiler that the method can return an async Task object. You can then use the await keyword to wait for an asynchronous operation to complete.

using System.Threading.Tasks;
using UnityEngine;

public class AsyncExample : MonoBehaviour
{
    async void Start()
    {
        Debug.Log("Start of the method");

        await SomeAsyncOperation();

        Debug.Log("After the async operation");
    }

    async Task SomeAsyncOperation()
    {
        await Task.Delay(2000); // Simulating a time-consuming operation
    }
}

If the goal was from the beginning to not wait for the task to finish but rather do other stuff while it's running on a secondary thread, why would I await?

mellow sigil
#

You can still do that while that part of the code awaits for the task

whole sorrel
#

If I wanted to save and load data asynchronously, does something like this make sense?

    public async static void SaveEventFlags(EventFlags flags)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        await Task.Run(() =>
        {
            using (FileStream stream = new FileStream(savePath, FileMode.Create))
            {
                EventFlags data = new EventFlags(GameManager.Instance.EventFlags);
                formatter.Serialize(stream, data);
            }
        });
    }

    public async static Task<EventFlags> LoadEventFlags()
    {
        EventFlags data = null;

        await Task.Run(() =>
        {
            if (File.Exists(savePath))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                using (FileStream stream = new FileStream(savePath, FileMode.Open))
                {
                    data = formatter.Deserialize(stream) as EventFlags;
                }
            }
        });

        if(data == null) 
            Debug.LogError("Save file not found in " + savePath);

        return data;
    }
thin aurora
#

IO operations are not required to always be async. Often introducing a Task pattern is a waste of time, hard to support and generally won't solve anything in Game/UI design

#

As for your code, Don't use BinaryFormatter. It's old, shitty, and deprecated. This is probably not the case in Unity, but newer .NET versions don't even have it anymore.

fathom quartz
#

there is some problem with unity

thin aurora
#

Instead, either use a StreamReader/StreamWriter or use Newtonsoft for reading/writing your data reliably

fathom quartz
#

when i put dontdestroyonload script on environment object the object is dontdestroyonload

#

but when i put that script on the other object that object becomes dontdestroyonload however environment object no longer becomes dontdestroyonload

thin aurora
tawny elkBOT
fathom quartz
#

public class DontDestroyOnLoad : MonoBehaviour
{
    GameObject EnvironmentScript;
    private Code code;
    public static DontDestroyOnLoad Instance { get; private set; }
    private void Awake()
    {
        if ((Instance != null) && (Instance != this))
        {
            Destroy(this);
        }
        else 
        {
            // Delay destruction by one frame to avoid timing issues
            Instance = this;
            DontDestroyOnLoad(gameObject);
            EnvironmentScript = GameObject.Find("EnvironmentScript");
            code = EnvironmentScript.GetComponent<Code>();
            code.Register(gameObject);
        }
    }
 
}
dusk apex
fathom quartz
#

ignore the comment

dusk apex
#

Assuming it's a Singleton

fathom quartz
#

So I need to make different script for other object?

dusk apex
#

You might want to consider informing folks what exactly are you trying to do.

sudden lantern
#

Hey everyone. When I restore the camera from a pan I lerp its position from the last to the current. The restore state is inherited from the "free" camera state, so I just override the SetPosition function and get the desired position. The problem is that when the camera is โ€œfar awayโ€ from Sonic, its positioning around an unknown center, until it's near the current pos. At first I thought it had something to do with distance, which is pretty obvious in this situation, but apparently not. I also tried to lerp it, but no help. You can see what I'm talking about in the end of the video, when I rotate the camera quickly with my mouse

protected override void SetPosition(Vector3 targetPosition)
{
    Vector3 center = _actor.transform.position;
    Vector3 diff = targetPosition - center;
    _stateMachine.position = Vector3.Lerp(_lastData.position, diff, _stateMachine.interpolatedBlendFactor);
    _stateMachine.position += center;

    Debug.DrawRay(targetPosition, Vector3.up, Color.cyan);
}
dusk apex
#

If you're just trying to make every object a global object, it's a very bad idea.

fathom quartz
#

I just needed to make 2 object global one which is counting score and oen which is stroring important details from objects

#

i fixed it by creating 2 scripts witrh same code

#

If it works... it works ig

#

though I wonder how would someone make every object a global object...

whole sorrel
dusk apex
sudden lantern
thin aurora
# whole sorrel so the thing with BinaryFormatter is that it would take my class and serialize i...

Newtonsoft does the same but rather it serializes it into JSON which is the standard for object serialization. The only drawback is that it's in a human-readable state, but even then I would suggest you serialize with JSON and then use StreamWriter to write the JSON to the file stream you have.

Implements a TextWriter for writing characters to a stream in a particular encoding.

whole sorrel
#

thanks

thin aurora
#

And then reading the data is the same, but in the reverse. Newtonsoft can also deserialize into a new class instance.

#

With this you also don't need [Serializable] and all that and Newtonsoft serialization supports many more classes, including Dictionaries

whole sorrel
#

Is it included in Unity or do I need to install it myself?

thin aurora
#

Newtonsoft is a package

whole sorrel
#

I think it needs to be installed, right?

thin aurora
#

Yep

#

And once Unity updates its core to the newest .NET versions, you can easily migrate to the natively available System.Text.Json and get rid of Newtonsoft

#

BTW you don't need StreamWriter to write into a file stream, but it's a very convenient util since you otherwise work with plain bytes

whole sorrel
#

Actually since we're already here. How am I supposed to install it? It's not in the default unity registry, I suppose I need to add a registry but I can't find which one

#

I'm new to this so sorry if I kind of suck

#

(New to unity not programming)

thin aurora
#

Unity has a package manager where it should be available

dusk apex
# whole sorrel so the thing with BinaryFormatter is that it would take my class and serialize i...

You're either going to be serializing to some sort of text format or binary. Here's a dev blog from Microsoft about migrating (linked specifically to the migration section)
https://devblogs.microsoft.com/dotnet/binaryformatter-removed-from-dotnet-9/#migrate-away

Starting with .NET 9, we no longer include an implementation of BinaryFormatter in the runtime. This post covers what options you have to move forward.

whole sorrel
thin aurora
#

Migration specifies the use of System.Text.Json instead, so it kind of comes full circle anyway

whole sorrel
thin aurora
whole sorrel
#

it would appear in the second image

thin aurora
#

Oh, right

whole sorrel
#

Maybe it's because I'm using the latest LTS?

#

2022.3

thin aurora
#

Can you use System.Text.Json perhaps?

dusk apex
thin aurora
#

Try adding using System.Text.Json to the top of your file

thin aurora
#

Yeah, STJ isn't supported dont he .NET Standard versions which is what Unity supports. It was worth a shot

#

Weird, it should definitely be here. Otherwise you might have to manually add it

sudden lantern
whole sorrel
thin aurora
#

This one also supports .NET Standard which is what Unity uses

whole sorrel
thin aurora
#

See if you can implement it

dusk apex
# sudden lantern it didn't help. And I need an easing

Unsure of how to respond to "it didn't help", didn't work or whatnot.
As for your second sentence..
What I would personally do would be to use lerp correctly with the third argument as a function that would take the t value (an animation curve would allow for some variable customization from the Editor Inspector).

sudden lantern
sudden lantern
dusk apex
#

Good luck then. Best log your destination or current location and see why either are not what you're expecting it to be - assuming one or the other is the issue with the camera not moving to the wanted location.

whole sorrel
#

I'll try but the code looks ok

#
public static class SaveSystem
{
    private static string savePath = Application.persistentDataPath + "/eventFlags.json";

    public async static Task SaveEventFlags(EventFlags flags)
    {
        await Task.Run(() =>
        {
            using (StreamWriter sw = new StreamWriter(savePath))
            {
                string output = JsonConvert.SerializeObject(flags);
                sw.Write(output);
            }
        });
    }

    public async static Task<EventFlags> LoadEventFlags()
    {
        EventFlags data = null;

        await Task.Run(() =>
        {
            if (File.Exists(savePath))
            {
                
                using (StreamReader sr = new StreamReader(savePath))
                {
                    data = JsonConvert.DeserializeObject<EventFlags>(sr.ReadToEnd());
                }
            }
        });

        if(data == null) 
            Debug.LogError("Save file not found in " + savePath);

        return data;
    }
}
#

I could probably remove the async on load since it's just text

thin aurora
#

These have an async variant if you want proper async code

#

Then your method can be async void and you can get rid of Task.Run since awaiting these methods makes it asynchronous

whole sorrel
#

without using StreamReader / StreamWriter, right?

thin aurora
#

Yes

whole sorrel
#

oh nice

#

thanks

thin aurora
#

These methods essentially do what you do

whole sorrel
#

Does this create the file if it doesn't exist?

#

I suppose so since it should be w+

thin aurora
#

It does

whole sorrel
#

Nice thanks

#

So in general is it best practice to let the gamemanager handle when to save the game?

#

Because my first thought was to have some planes that when triggered would save the game, but then it's not the gamemanager triggering the save

thin aurora
#

I would look into having a singleton SaveManager than handles purely the saving. The idea of a GameManager is broad and can be anything, and you should make managers for each purpose.

whole sorrel
#

About singletons: do they exist without being attached to any gameobject? Or do I still need to attach them to something? And if so, what happens when I change the scene?

Like if I have my gamemanager as singleton and then have to change the scene, will the game manager be reset?

dusk apex
#

You're only ever needing them to be attached to stuff if they're Unity components

whole sorrel
#

MonoBehaviours?

#
public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public EventFlags eventFlags;
    public GameObject savingPlane;
    public FirstPersonController player;

    private void Awake()
    {
        Instance = this;
    }

    // Start is called before the first frame update
    async void Start()
    {
        // Loads up all the event flags
        eventFlags = new EventFlags(await SaveSystem.LoadEventFlags());
    }

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

    }

    // Save the game directly via GameManager
    private async Task SaveGame()
    {
        await SaveSystem.SaveEventFlags(eventFlags);
    }
}

Like this thing here (very barebones) I know

Will this be deleted when I change scene?

thin aurora
#

But the singleton pattern is not limited to monobehaviours. It can also be on a class in general

thin aurora
#

The correct approach is also removing the instance

#

Alternatively, use DontDestroyOnLoad or a transitive scene where the monobehaviour is retained

whole sorrel
#

And with DontDestroyOnLoad the GameManager that will be in the next scene will basically retain the same address?

whole sorrel
#

Oh that's neat

dusk apex
#

Having a script with a ddol statement will prevent the object from being destroyed but it isn't a Singleton.

#

Instance will only be referring to that one object though and the rest would simply be not-destroyed upon loading a new scene or whatnot but will likely be lost forever - unless you're using other means to find them again. The reason why you're needing a unique script for each is because each script is meant for one manager only with respect to the name of the pattern Singleton

#

The inheritance/interface pattern will work for reducing lines of code and reusing the pattern as you're still inheriting/interfacing with a unique class.

whole sorrel
#

Does it make sense to have systems communicate via signaling? Like Game Manager and Save Manager

west lotus
#

What does signaling mean ?

#

Events ?

thin aurora
#

Maybe you want something like a mediator?

#

Whatever the case, you might be interested in just trying basic events first

gleaming orbit
#

hii my fps went from 500 to 100 after making this script (its a gun equipt system so its very important) does anyone know how i can improve my performance?

gray mural
#

In my 2D game, I have the ground tilemap and individual boxes, which should be affected by gravity.
The boxes can only fall when the player moves, which is 10 times per second at most.
Unity's Rigidbody 2D doesn't seem reliable, since each box should exist perfectly on its integer position, but a y offset of maybe -0.1 - 0.1 is visible.

I thought I could add my own gravity script to each box, which waits for the event on player move and shoots 2 raycasts to the bottom.
The 1st one gets the first found ground block's position on the ground layer, and the 2nd one calculated the amount of the other boxes, which are also affected by the gravity, in-between. Then, for each box, the gravity is applied to the found ground block's position plus the number of another boxes between them.

This approach is pretty reliable, but I am worried about about the performance when the amount of boxes equals to e.g. 1000 or more, and 2000 raycasts are shot every player move. Of course, the screen is only big enough to contain 100 boxes at most, but the scenario is very possible if another boxes exist outside of the player's current view.
I would appreciate any of your ideas.

dusk apex
gleaming orbit
thin aurora
#

Your script, apart from not doing anything heavy, doesn't contain features that are invoked each frame. Instead it does it on a conditional basis, and therefore would at best cause a spike in frame dropping

#

I suggest you fully verify this script actually is the cause by disabling the component on the gamebehaviours that use it. If it truly fixes the issue then I would grab the Unity profiler

zealous lagoon
#

Hello, I'm trying to add Lua to my game, what's the simplest way to introduce a wait() function into Lua, so it can pause Lua code execution for the specified time? E.g. wait(2) -> wait 2 seconds

I'm using MoonSharp, any answers are appreciated ๐Ÿ‘

vestal arch
#

not sure how lua interacts with unity/c#, but with coroutines you could use WaitForSeconds or WaitForSecondsRealTime depending on which makes sense

hexed pecan
# gray mural In my 2D game, I have the ground tilemap and individual boxes, which should be a...

I would start by implementing the raycasts and then stress testing it with those 1000+ boxes and seeing how it performs.

If the raycasts are too expensive, one option is to use 3D colliders and RaycastCommand. It allows you to cast a lot of rays in a job. There is no 2D equivalent for this so you'd need to convert your project to use 3D physics (colliders, rigidbodies).

Another option is to leverage the fact that your boxes don't move horizontally. You could keep each column of boxes in its own array and use some algorithm to check only the boxes below the one you are currently processing.

#

In the last option, you'd ideally process each column of boxes from bottom to top

gray mural
#

And I know this is an important factor that I, for some reason, have left out in the initial message

#

When the snake moves, always by 1 block, its last tile will always be removed (and a new tile added), so it's only a single column that is affected, which shouldn't be too bad.

#

I already have an, in my opinion, efficient method to update the snake's gravity, so when it's applied, all blocks, which are currently on the snake, should also be affected by the same number of cells

gleaming orbit
#

does anyone know how i can make this not run every frame but like every qauter of a second?

knotty sun
#

Look at your if statement and think about what it actually says not what you think it says

thin aurora
#

I'd say use a timestamp

placid summit
#

I cant find much info on editor tools - I want to create an editor to modify a component when selected so I guess I use the EditorTool class

hexed pecan
#

I guess EditorTool can be used if it is for the sceneview

placid summit
sullen drift
#

hello guys, I have question. Do you guys know why when I build unity webgl, it wont produce build files with .unityweb type?

#

but just regular .js?

knotty sun
deep stirrup
#

Is there a way to unpress (or should I say release?) UI button after you click on it? It stays pressed until you click it the second time, and I want to change it

deep stirrup
#

oh, okay, sorry ๐Ÿ˜…

sullen drift
knotty sun
sullen drift
#

I followed this, but it didnt produce the same output

#

this is for unity 6

fathom quartz
#

this isnt working

#

Its going in another level so i cant use serializefield

#

it keeps saying the dammit error object instance not set to an isntance of an object

knotty sun
#

So break the statement down, see which is failing the Find or the GetComponent

sleek bough
delicate granite
#

hi, I have an issue where the player camera updates for the host when a client joins.
it sets the camera in the start function when the script starts.


 if (gameObject != null)
        {
            // Find the camera that is a child of the player
            playerCamera = gameObject.GetComponentInChildren<Camera>();

            if (playerCamera != null)
            {
                Debug.Log("Player camera assigned successfully!");
            }
            else
            {
                Debug.LogWarning("No camera found as a child of the player!");
            }
        }
        else
        {
            Debug.LogError("Player GameObject is not assigned!");
        }

this is the script that sets the player camera. The player is instantiated by the net script as a gameobject but the camera keeps changing

#

i didnt know if this went here or in networking but the issue is about coding part

heady iris
#

sounds like everyone's running that function, then

#

Only the client should be finding the camera, presumably

delicate granite
#

yeah, but how do i do this?

#

sorry if i sound rude, i've been trying to fix this for a while and i'm tired of it

#

i don't mean to come across as rude

heady iris
#

I'd need to see the context this code is running in -- how does that method get executed?

#

also, what networking system are you using?

#

Netcode for GameObjects?

delicate granite
#

this happens in the start function

delicate granite
heady iris
#

Start will run for every single user when they see that component come into existence

#

Is this part of a NetworkBehaviour?

delicate granite
#

uhh i'm not sure. i just have this run in the start function

#

it's in the playermovement script

heady iris
#

Show the entire script. !code

tawny elkBOT
delicate granite
#
public class PlayerNetwork : NetworkBehaviour
{
  

    public float speed = 7.5f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    public Camera playerCamera;
    public float lookSpeed = 2.0f;
    public float lookXLimit = 45.0f;

    CharacterController characterController;
    [HideInInspector]
    public Vector3 moveDirection = Vector3.zero;
    Vector2 rotation = Vector2.zero;

    [HideInInspector]
    public bool canMove = true;


    void Start()
    {
        characterController = GetComponent<CharacterController>();

        if (gameObject != null)
        {
            // Find the camera that is a child of the player
            playerCamera = gameObject.GetComponentInChildren<Camera>();

            if (playerCamera != null)
            {
                Debug.Log("Player camera assigned successfully!");
            }
            else
            {
                Debug.LogWarning("No camera found as a child of the player!");
            }
        }
        else
        {
            Debug.LogError("Player GameObject is not assigned!");
        }

        rotation.y = transform.eulerAngles.y;
        //Cursor.lockState = CursorLockMode.Locked;
        //Cursor.visible = false;
    }

    void Update()
    {
        if (!IsOwner) return;
        if (characterController.isGrounded)
        {
            // We are grounded, so recalculate move direction based on axes
            Vector3 forward = transform.TransformDirection(Vector3.forward);
            Vector3 right = transform.TransformDirection(Vector3.right);
            float curSpeedX = canMove ? speed * Input.GetAxis("Vertical") : 0;
            float curSpeedY = canMove ? speed * Input.GetAxis("Horizontal") : 0;
            moveDirection = (forward * curSpeedX) + (right * curSpeedY);

            if (Input.GetButton("Jump") && canMove)
            {
                moveDirection.y = jumpSpeed;
            }
        }

        // Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
        // when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
        // as an acceleration (ms^-2)
        moveDirection.y -= gravity * Time.deltaTime;

        // Move the controller
        characterController.Move(moveDirection * Time.deltaTime);

        // Player and Camera rotation
        if (canMove)
        {
            rotation.y += Input.GetAxis("Mouse X") * lookSpeed;
            rotation.x += -Input.GetAxis("Mouse Y") * lookSpeed;
            rotation.x = Mathf.Clamp(rotation.x, -lookXLimit, lookXLimit);
            playerCamera.transform.localRotation = Quaternion.Euler(rotation.x, 0, 0);
            transform.eulerAngles = new Vector2(0, rotation.y);
        }
    }
    

    // Stuff only the server can access (and host)
    /*
    [ServerRpc]
    private void TestServerRpc()
    {

    }
    */
}
delicate granite
#

oh okay thanks

#

do i forward it to networking hten?

heady iris
#

please use a paste site for large blocks of code

delicate granite
heady iris
delicate granite
#

okay

onyx cypress
leaden ice
onyx cypress
#

oj

#

oh

leaden ice
#

At most, it prints a log

onyx cypress
leaden ice
leaden ice
#

The code just says:
"each frame, if I press the button, and the door is not open, open the door"

#

Nothing about locations of objects

#

nothing about the player looking anywhere

#

the code does what you wrote it to do

#

nothing more, nothing less.

onyx cypress
#

oph ok thx

whole sorrel
#

It used to be SetBool but now it's gone in the new system

vestal arch
leaden ice
#

Yeah you need to look at Animator

#

AnimatorController is an editor only thing

#

and both of them have been around forever, neither is "new"

whole sorrel
#

nvm I'm stupid

#

I need to use animator

#

yeah

#

thanks

zealous lagoon
#

Hello, I'm trying to add Lua to my game, what's the simplest way to introduce a wait() function into Lua, so it can pause Lua code execution for the specified time? E.g. wait(2) -> wait 2 seconds

I'm using MoonSharp, any answers are appreciated ๐Ÿ‘

Some guy replied to use coroutines, but I have no idea how. Exposing a coroutine and running it does not make it wait for the coroutine to finish.

dusk apex
somber nacelle
dusk apex
zealous lagoon
vestal arch
zealous lagoon
small schooner
#

use async then or better use UniTask

zealous lagoon
small schooner
#

what is Lua

rigid island
#

lol

vestal arch
#

lmao, even

rigid island
small schooner
#

so your question is about C# not unity, in this case google "asynchronous programming c#"

somber nacelle
vestal arch
small schooner
#

well I dont know what is lua and why do u use it ๐Ÿ™‚ but you can just write something like float triggerTime = Time.time + delay; then if(Time.time>triggerTime)DoSomething();

swift falcon
#

What is the best word to name things that doesnt have implementation? my library provided a sealed class that doesnt have implementation where the user must implement it on their own by providing delegate to it. I thought of the name "abstractmodel" but i dont think its a good name because the class is not abstract. I thought of naming it just as "model" but i also dont think it is accurate because it doesnt have implementation.

small schooner
#

Abstract

swift falcon
#

But the class isnt abstract

#

None of them is

wicked scroll
#

'Base' is common

small schooner
#

okay I didnt read to the end, just answered the first sentense ๐Ÿ™‚

swift falcon
wicked scroll
small schooner
#

why do you need to call it if you can create just abstract class and use its naming convensions

wicked scroll
#

or an interface

swift falcon
#

using inheritance for implementation is not a good idea, i uses delegate to allow user to implement it on their own

#

Hmm maybe i should go with base, thanks

wicked scroll
#

sounds like it should be an interface

swift falcon
wicked scroll
#

good news! you can use multiple interfaces

#

but that directly contradicts what you've been saying, so now I don't know what you want

vestal arch
#

i mean that sounds like an abstract class

#

but that would be using inheritance so idrk what to say to that

small schooner
#

you can use only interfaces without abstract calases it is also fine and some people say it is better way to code but if you want use abstract class you can name like this "Shape and then Polygon and then RegularPolygon so on."(I found this answer on stackoverflow for me looks good)

vestal arch
#

yeah that's definitely not applicable here

swift falcon
#

I think of using abstract and interface but then user can provide their own class which inherit the abstract/interface and that is bad, i dont want that

vestal arch
#

do you have a solid reason to avoid inheritance though?

small schooner
#

if you use Interfaces call it just IEnumerator IEnumerable etc.

zealous lagoon
swift falcon
knotty sun
swift falcon
vestal arch
wicked scroll
vestal arch
wicked scroll
#

and 'because I read that I should on SO' isn't a great reason to do that

small schooner
#

@zealous lagoon If you assign triggerTime value at Start() method for example it wont give you a loop

#

and in DoSomething() you can reasign the triggerTime

vestal arch
#

well no that's not how scoping works

swift falcon
#

Hmm maybe i need to rethink if i should use abstract and interface, txn everyone

wicked scroll
#

sounds like what you really should do is just write the code to make the thing work and then think about how to abstract it, since you aren't sure what needs your abstraction has right now

zealous lagoon
#

Hello, would like to state I managed to get it working, by running the script in an IEnumerator you get access to WaitForSeconds, then simply use:
coroutine.yield(x) inside the script and catch it in the IEnumerator and wait

swift falcon
vestal arch
#

well you're defining it as "unimplemented" so that points to "abstract class"

#

what if you just consider it as taking a callback, or something like that? that detaches your idea from inheritance

swift falcon
vestal arch
#

yeah but you're still calling it "unimplemented"

wicked scroll
#

your users have access to your code?

swift falcon
#

No, it is planned to be published as dll

small schooner
vestal arch
#

if it's a delegate, that's not "unimplemented", that's a callback

vestal arch
#

the argument is usually inheritance vs composition, but i guess this is.. a secret, third option

#

well, callbacks.

swift falcon
#

hmm maybe i should go with abstract class then, i need to google again if this is good idea or not

wicked scroll
#

it's stll composition, it's just at the function level rather than the object level

#

this pattern is very common, especially in langauges like JS that are more functional

vestal arch
#

actually is it thonk

somber nacelle
vestal arch
#

really having a "i don't need answers, i need sleep" moment here

swift falcon
wicked scroll
dusk apex
small schooner
#

Yes you actually right. I mean do not use classes inheritance only interfaces inheritance

upper totem
#

Does anyone know a good YouTube channel for learning active ragdolls in unity

somber nacelle
vestal arch
vestal arch
# somber nacelle interfaces are not inheritance

in java and ts, interfaces are considered an aspect of inheritance thonk
but those kind of have exceptions in their interfaces
are interfaces in c# not considered aspects of inheritance, because they're purely declarations or something?

wicked scroll
#

I mean, it's semantics but an interface does not traditionally 'inherit' anything, since there is no 'base' and no 'child'

small schooner
#

interface is simulation of multiple parents behaviour

wicked scroll
#

though now that interfaces can have default implementations, that gets muddied

vestal arch
vestal arch
#

yeah this is kind of what i was referring to with java's exception in interfaces

swift falcon
vestal arch
#

multiple inheritance with a different name lol

wicked scroll
vestal arch
dusk apex
wicked scroll
#

an interface is a contract

somber nacelle
vestal arch
wicked scroll
#

er sorry, an abstract

#

an interface (traditionally) does not have any 'pieces' to pass down

#

it describes a contract which you can adhere to

vestal arch
#

that "traditionally" is pulling a lot of weight lmao

#

by "pieces" you mean like, implementations/fields, right?

wicked scroll
#

and you can then tell your program that you adhere to that contract, but there is on inheritance

#

yep

vestal arch
#

i see what you mean

wicked scroll
#

i mean, with default implementations you can argue either way

#

but that's the logic

vestal arch
#

im not old enough to have experienced the "traditional" form of interfaces so i don't think it's really set in my mind lol
i get the logic though

#

interfaces/abstract classes/concrete classes just seem like a spectrum to me and which you use is more about what you want it to be than what they actually are or can do

small schooner
#

well using Parent classes and abstract classes is making code little be harder for debuging but if you know how shadowing and overriding works it is not much harder with interfaces you have more freedom and simpler code to debug

wicked scroll
#

inheritance necessarily forms a hierarchy, which interfaces don't

#

that hierarchy is why they are valuable in specific cases, but also why they are mostly not a good default (few things fit into clear, consistent hierarchies for any length of time)

halcyon swallow
#

why does unity run this code when im not pressing space

steady bobcat
#

missing a ), did that even compile?

small schooner
#

GetKeyDown

somber nacelle
halcyon swallow
#

thats not the whole code
i only screenshotted the important part

somber nacelle
vestal arch
small schooner
#

not GetKey use GetKeyDown

knotty sun
wicked scroll
halcyon swallow
#

it says warning: possible empty statement

steady bobcat
#

the ; ended the if early so the other code just runs always

knotty sun
#

since when do if statements get terminated with ; ?

halcyon swallow
#

aw fuck

#

im so silly!

wicked scroll
vestal arch
wicked scroll
vestal arch
swift falcon
wicked scroll
#

well sure, because all objects are children of object, no interfaces here?

#

I guess I'm not sure what you're saying

steady bobcat
#

๐Ÿ˜†

somber nacelle
halcyon swallow
#

im suprised it lets you put if(); and doesnt immedialy tell you off

knotty sun
vestal arch
wicked scroll
#

it's not though

#

the interface isn't 'anything'

vestal arch
#

the variable typed as an interface

wicked scroll
#

it's a contract that other things can fulfill

vestal arch
#

yeah yeah

steady bobcat
knotty sun
#

guys, this is hardly a Unity discussion

small schooner
#

it is code general discussion so discuss C# is okay I think

wicked scroll
dusk apex
spare dome
somber nacelle
# vestal arch yes this is my argument

implementing an interface is still not inheritance though. interfaces inherit System.Object because everything in C# does. You implement the members that an interface declares, you are not inheriting behavior from it

rapid gale
#

Hello, i'm new to unity. How do i set lang version and .net version? IntelliSense complains that i cant use with keyword

knotty sun
vestal arch
knotty sun
small schooner
somber nacelle
rapid gale
rapid gale
#

๐Ÿซ  gotcha

swift falcon
steady bobcat
#

wut even if you did that it wont magically work

dusk apex
small schooner
#

and interfaces create in c# for simulate multiple inheritance what is not quite far from what I said before

knotty sun
rapid gale
#

well, thanks for answer

swift falcon
somber nacelle
# rapid gale ๐Ÿ˜จ So there is no way to use new features C# devs made?

unity is in the process of upgrading the engine to use the core clr instead of mono (which is what they've been using for years), the engine is currently stuck with (most of) c# 9 as the latest language version supported. there are technically ways to get it to support more recent language features, but only features that do not rely on newer .net versions and are just syntax sugar. the upgrade to coreCLR is currently expected in Unity 7 which should have an alpha version probably late next year

knotty sun
steady bobcat
#

haha soo many replies

vestal arch
# somber nacelle then surely the matter is settled and you admit that interfaces are not inherita...

"admit" wtf waitWhat
im trying to reconcile my mindset vs what they can do within the langauge vs how they're treated semantically/in terminology

because to me,
a) declarations are inherited, both through classes and interfaces
b) interfaces do inherit fields and implementation in some languages' implementations of interfaces, though i recognize that this is not "traditional" interface behavior, as has been discussed already

i know how interfaces work lmao, you don't have to keep re-explaining them

knotty sun
# rapid gale good to know that

you can use different C# and .Net versions but you have to make projects outside of Unity and then copy the resulting dll's into your Unity project

elfin pulsar
#

every time i bake my Lighting it crash

rapid gale
steady bobcat
#

yea we all suffer