#archived-code-general
1 messages ยท Page 398 of 1
I'll see what I can figure out, that dark souls video is pretty helpful
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
is there a callback I can get for when a component is added to a gameobject?
what is colliderInstanceID? That's not.. a thing.
that's your own custom field
and presumably you never set it to anything except 0
is this not it?
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
is it safe to use a float as Dictionary key?
depends what you mean by "safe". It's usually not a good idea, no
but it's "safe", and makes sense in certain specific circumstances.
what are you trying to do?
I would guess that property only gets populated when using RaycastCommand, not normal raycast
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
it doesnt like that
Because hit isn't being populated anywhere
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
i see
yeah that's just an empty/default RaycastHit
nothing has written any data to it
if (Physics.Raycast(ray, out hit, 100))
For example
^^^ @leaden ice what do you suggest I do?
Why is the group ID a timestamp?
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.
yeah, foolsihly didnt cross my mind it would need to know about "hit" to put it in there
any ideas for why my transform is set at the Player object instead of the selected Capsule?
Use "Pivot" instead
oh thank you, i feel dumb now haha
"Center" mode just tries to guess the center of your object based on its renderer bounds and collider bounds
i must have accidentally changed it at some point
does disallow multiple component attribute count for inherited classes too?
Mate you need to learn to use the docs
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/DisallowMultipleComponent.html
They exist for a reason 
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?
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
I use F4 but never bothered to look up the difference of N, D, F etc.
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
unscaledTime is time since startup
ish
the latter is true time since startup, and changes during a frame
generally not desirable
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
what happens if you click on it instead?
wonky lol but it has happened to me before though
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
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)?
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
I'll sync up the versions with a windows machine and see if it does the same thing
I suggest taking a look at Rider, it became free for noncommercial use recently
I doubt it though as I'm sure more peeps would have noticed and reported it
And when you start it up first time you can easily import settings and hotkeys from VSCode
yeah, I saw Rider went free. I have it installed but not tried it out yet
Very painless transition
good to hear. Other devs I know use it and love it
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
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
Yeah same, that made me stick to VSC for a while longer
it's become my all purpose text editor so it's hard to move ๐
I used vsc for years but instantly rider feels like home already
And so many little QOL changes that just make me smile
I'm sure they wouldn't be misspelling code completions ๐ฅ
thanks for the reminder to check it out
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
I'm not even sure what you're asking tbh..
this just looks over convoluted, how complex is this FSM supposed to be ? why is singleton and not dependency injected
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
๐ญ
wdym dependency injection?
you mean why did I not have a variable to store the link to the main class within the state machine state?
How to check if Iโm using a simulator in the editor
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
If it's coming out of the pool, then you put it into the pool somewhere. Log the objects you insert into the pool.
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?
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
Ahh I see it now
Thanks for the info
bumps
Do you understand the usecase of a singleton and is there a reason it is one?
I feel like context is missing yeah
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.
yeah it's sheer fact of typing instance every time makes me feel like I am doing something wrong
I am making 2 FSMs one of which is about the UI in main menu, and the other one is managing the whole gamestate
I am seeing them being singletons reasonable
Anyway, if they were not singletons, would that somehow help to making FSM more handy?
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
Then perhaps you're using it more than it needs to be used.
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?
From a quick look at this code snippet, it seems like you're abusing references. You shouldn't be chaining that many reference accesses that often. Instead implement intermediate methods, or use events. Passsing delegates is fine as well.
It could be reasonable. It could be unreasonable. It's hard to tell without seeing actual examples.
Yeah this is all very vague to me
"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
The names that you use also make it vey confusing. For example, what's Inputer? And why is there inputs inside the inputter instance? If Inputer is an input manager, should it not have properties directly in it?
What class is that code from anyway? Maybe if you provide a bit more context, we could provide better advice.
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
I just ducttaped my input manager of a kind, in a bad way I guess
on rethinking I should ve just made static fields there
Mmm... Static fields is usually a bad idea.
I mean, less dots?
I don't know your whole game context, but it seems like you're basically managing the whole game lifecycle via the same statemachine.
If your game is not too big or complex, that's actually fine.
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.
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
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.
(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?
I have an odd feeling that making more even non-value variables like classes to store a reference to already existing class is in a way non-optimal
so I have icky feelings about both ways
does that feeling wrong?
I do almost exactly that and it works well, no idea if that is the best way tho
Optimal in what way? Performance? Memory?
A reference is just 8 bytes of memory. You can calculate yourself how much more memory your app would consume. And in terms of performance, big chains of references are probably slower(though probably negligible difference).
Always think of code readability and ease of extension and debugging first. Performance issues can be solved later.
Hardcoding is always an option. Otherwise state machines are the way to go.
As for what you have in mind, it's hard to say without seeing actual implementation, or at least some pseudo code, block schemes representing the logic.
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.
oh I made something working
That being said, it's fine to ask about things that you're worried about. I hope the conversation gave you some insights.
I already released one shitty game and now trying to do stuff more properly
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?
I would probably just use an AnimationCurve and a script for that
but it's up to you.
Both approaches are fine. Animations might have a little more overhead, but other than that it's a preference thing.
thank you!
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();
Where am I supposed to save this file if I wanted to use "Something" namespace?
the file location has no impact on the namespace
but vscode shows that ... thing. I assume this is because I'm doing something wrong even though it will compile just fine.
I want to know the standard or recommended way to do it.
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
(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.
I already named the folder where the thing is saved with the same name as the namespace. But it still doesn't like it.
Where should I put that file if I want to do it according to the convention? I want to keep the namespace "Something"
you can right click the warning to supress it
I finally bit the bullet and rearranged my entire project to conform to this
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.
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
something that could be a problem is if you put your .cs files inside a "scripts" folder, then the namespaces for files in there will always start with scripts
or maybe it'll do assets/scripts
Yeah I don't do the "organize by file type" like Scripts/Textures/AudioClips/whatever, I find that to be largely pointless.
I organize by type for things that don't have much of an identity
Yeah, ive never been a fan of having a folder per file type
all assets for a characater go in a folder for that character, since they cleraly belong together
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
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
"source" or "src" makes far more sense over "scripts"
is there any way to take control of detail distance of particular detail instance of terrain using script or something?
camTarget.position = transform.forward.normalized * -1 * camDistance;
This doesn't make sense. It doesn't include the position of another object
Perhaps you meant to set localPosition!
That would set your position relative to your parent
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
Note that you won't want transform.forward in that case
since that's a world-space direction
You'd just do Vector3.back.
woah, thank you! that's a lot simpler than what i was trying haha
works perfectly now, thanks :D
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.
The reason I believe it's an initialization issue is due to how Unity auto-initializes referenced objects when viewed in the inspector, however when the "Chest" GameObject is being placed (initialized), I am initializing the storage component directly. (Which means the menu cannot be opened prior to this occurring).
but what if menu, menu.storage and/or menu.storage.items are null?
and you could be trying to call GetItem on a null
There are like 5 things you're dereferencing there that could cause that issue..
Yeah, I'll try to ensure I've checked everything again. But I am nearly certain everything is initialized and correctly set.
nearly certain means you are assuming, dont
nearly certain doesn't count!
"close" only counts in horseshoes and hand grenades (:
I mean nearly certain to the point where a mouse would have had to flipped the required bits on my motherboard to manually change it, but you never know ahah.
Just adding a log to everything in the tree of functions to check for nulls
the chances are greater for that than that the runtime is wrong
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 (:
Unity will sometimes open the wrong file when you double click on an error.
I think it's trying to guess what is "your code" and what is "library code"
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");
}
77:
if (menu.storage.items[slotNumber].GetItem() == null) // ERROR
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.
GetItem():
public ItemClass GetItem() { if (item != null) { return item; } else { return null; } }
^ Current:
public ItemClass GetItem() { return item }
^ tried
Show the complete console
notably, show that all of those log messages did not get printed
There is a LOT of irrelevant debugging logs, but I'll explain anything on it. One sec.
Is there a way to copy the entire console?
Just show a reasonable number of messages before the error.
Also ensure that Collapse is disabled.
Alright, sec.
(and that you aren't hiding any of the log categories)
e.g. this hides informational log entries
there is your answer right in front of your nose
Yes, but why is that null.
Only when I click in the inspector does it populate is the assumption
hey
Debug.Log("Debugging Place/Swap, GetItem: " + menu.storage.items[slotNumber]);
This doesn't confirm that menu.storage.items[slotNumber] is non-null). It will not cause an error if it's null.
I believe you'll get an empty string.
So you'd just see "Debugging Place/Swap, GetItem: "
I was under the impression you'd checked the log message!
I see I'm sorry for the confusion there, but I am still confused as to how/why that is null which is what I explained initially.
If you're relying on Unity to populate serialized fields with "sane defaults", this won't happen for a newly created component
e.g. creating an empty list to put in a List<int> field
viewing it in the inspector would cause this
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?
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
20 Empty "SlotData" containers is the hope.
(what if SlotData has no default constructor?)
You need to actually put things in the array
public SlotData()
{
item = null;
quantity = 0;
}
wont happen unless you do it explicitly
i am just providing an example of why this doesn't happen
Hi everyone! How can I make the button trigger only in this case?
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
new SlotData[20] is 20 nulls which MAY contain a SlotData
because the push I'm doing right now could go either way.
The intended result is creating 20 Empty "SlotData" with a default of "item == null", "Quantity == 0"
Check the phase of the context
context.performed , specifically
Then you need to fill the array with instances of SlotData.
So for over the array and fill it
so I click the left mouse button and it works! Even though I'm not looking at the monitor
Oh, I see
I thought you meant it was triggering both when you pushed and released the button
I want it to be able to work if I look at the monitor and the raycast hits it.
but why would this not construct properly by creating 20 default instances?
Sounds like you need to have UseComputer check something before doing anything
Because it doesn't.
Why doesn't int x; have a default value of 10?
because that's the way arrays work in C#. If SlotData was a struct rather than a class it would do as you expected
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
No, it works if I press it! But I want it to trigger if only the rakast hits the object I want it to hit.
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?
You are creating an array that can hold 20 SlotData objects
Why would this create 20 SlotData objects?
I also don't understand why the camera doesn't change when you press it?
it doesn't even display logs.
then the method is not being called
about what, how do I know?
I see, there's the discrepancy. I had assumed this meant add 20 instances of slotdata to the empty SlotData array.
This is conceptually identical to expecting this to work:
SlotData foo;
foo.quantity = 123;
(different kind of error, same premise)
May I then ask what is the point in ever setting the "Quantity" Of an array of a type?
change SlotData from class to struct, job done, will work as you expect
i would suggest reading the docs
(of course, now any code that expects reference-type behavior will either malfunction or start erroring)
such as...
foreach (var item in items)
item.quantity = 100; // error
SlotData item = items[0];
item.quanity = 100; // items[0].quantity is still zero
as OP doesn't seem to know the difference between value and reference types I doubt that will be a problem
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);
That looks reasonable, yes.
I was hoping there would be a way to by default add "default" values but I guess it really doesn't matter either way.
I guess that's true haha.
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
how do you do it?
what call a method?
I need to be able to use it here if it's successful.
and also for some reason it doesn't work even logs.
So, managerComputer is null. Why?
where?
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 ?
I use it on the manager's computer
where in the code you just posted?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
#archived-code-general message
You even highlighted the code!
can I post the code here?
why would you need to. You already did albeit it badly
so in the line of code you highlighted what does the ? mean
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
ok, so as I said. managerComputer is null
private void UseComputer(InputAction.CallbackContext context)
{
Debug.Log("Interacting with computer...");
managerComputer.UseComputer();
}
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.
and by adding the ? you added a non fail null check
I don't understand you
explain to me what this line of code does
managerComputer?.UseComputer();
finds this method in the managerComputer script to use it on the mouse key
no
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();
}```
this
managerComputer?.UseComputer();
is the same as
if (managerComputer != null) managerComputer.UseComputer();
and as managerComputer IS null the method is never being called
How do I then call this method when I click?
find out WHY managerComputer is null and fix it
I haven't figured it out and I haven't found a solution
ok, so where do you declare managerComputer
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>();
}
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?
No, this script is attached to the object I'm looking at, and PlayerInputHandler hangs on the player.
so why would you expect the GetComponent to work?
I understand then it is necessary to make a public variable to get this component? Or is there any other way?
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)
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
You are allowed to read the message yourself, I dont need to read it for you
I take it this is obsolete in Unity 6.
yes, so use the alternative it tells you to use
[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
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?
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
yes
GetComponent is only needed if you are not manually assigning a reference
then what should I use?
are you dragging computer manager into that box in edit mode
ty bro
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();
}
i dont really understand what you mean
here's how to make the button permission?
private void UseComputer(InputAction.CallbackContext context)
{
Debug.Log("Interacting with computer...");
managerComputer?.UseComputer();
}
Yeah, I switch the camera that looks at the computer screen.
okay
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();
}
then you need to figure out a way for UseComputer() to know whether or not HandleRaycast hits anything
it doesn't just know
You mean add raycast to it, too?
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
HandleRaycast() and you can't do that in this method?
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
You're confusing me, I'm still a beginner.
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
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?
Thats a great explanation made me undersand it too while just browsing dc out of boredom, thx alot
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
I was playing with a vaguely similar problem when prototyping a parkour game. Figuring out where to put your hands can get tricky.
You need to get a consistent "forwards" direction first. The camera forward vector is a bad choice, since you could be looking straight down
It sounds like it should match the direction you're trying to move in
yes yes, you're getting the problem at least ๐
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
Is this "on rails", where holding forward automatically makes you follow the turn?
no
or should the player just start bumping into the wall until they turn their head?
You need to find the most reasonable position given the current obstacles and the intended direction of movement
yes
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
that's what I'm stuuck on
If this raycast doesn't make it far enough, then you need to try less optimal positions
well what if I'm looking down?
you still move forwards when looking down, right?
yeah, use the same logic there
You might be able to come up with a "score" for a hand position
I kind of do that already
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)
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
You can search until you get a high enough score (with your standards gradually slipping to guarantee you find something)
it's not quite same but
yep -- see if you can come up with many variations like that
I am also taking the move vector into considerations anyway
because
I forgot to mention
Does anyone know how to make vhs effect or have a tutorial that i can watch?
question, with unity 6 when adding a new script to a game object, the default language is c#, how would i change this?
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
you don't
i thought unity supported other languages?
c# is garbage
imo
no offense to you guys
I think I did think of that though, let me try to remember if I found a fault there
then you havge to change to unreal
in the ancient past, it supported Javascript and "BooScript"
brah
mysterious
even worse
But why is it garbage? Curious what your thoughts are , what you would rather see?
probably because the server tends to filter very short responses
c++ by itself is exactly one letter
๐
But anyway, unity does not support any other scripting language other than C#
It works for me
Im unreal dev i just saw the Reddit posts about fog power tripping and wanted to see,
I see no issue with it
No language except JavaScript is objectively bad since they all server different purposes
c# reminds me too much of java ๐คฎ
What's wrong with JAVA???
C# is fine for general oop classes etc imo
Except the fact that Java literally hacks itself first thing to look more OOP
Swing is ugly
Oracle
Everything has to be in a class
@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?
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
I wonder how you should handle that
beyond just clamping the X rotation to like
-89 ... 89
Yeah yeah
c++ is lower level and gives more control over performance
and optimizations
My brain hurts
it also lets you blow your entire leg off
as a core language feature
he left
I came up with an entirely riduculous solution that almkst works but doesn't
I have zero clue why
I guess that, if movement fails, you could try rotating the movement vector around your local X axis
also c# was built by microsoft to resemble java and runs as managed language where .net framework helps manage memory and other inefficient tasks
especially if you're allowed to go completely upside-down
(rather than your up-and-down aiming being clamped to [-90..90]
Bump as a solution
that won't work
I don't entirely understand your solution then because I had a similar issue and that fixed it
Not solution sorry I mean issue
Well did you read the problem from the beginning?
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
Point being, if I am rotated 89 degrees downward and hold W, I should still move forward?
as opposed to 90, where I wouldn't move forward?
yeah I made just a giant block of text lol
@languid hound #archived-code-general message
I think with this solution you could still mix the compass
The compass will never look up or down and so it can only reach forward
Ah
You already tried something similar
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
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.
This is the code
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?
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) ?
I'd make a component whose sole job is to report when a particle system stops
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
the most crude way to do this is to just stuff the settings in a static field
It is appropriate if there's only one ever set of settings active at a time
rigidbody.drag no longer seems to exist
is rigidbody.lineardamping the same thing?
Yes.
why the re name
I did it using a singleton (GameSettingsSingleton), which has DDOL enabled
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
no that is drag
i guess damping just sounds more scientific because theres no actual air simulation
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?
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)
cheers
ooh this seems really useful, and has the attribute i need
[Min(0)]
oh i didnt even realise that existed by default haha, thanks
Naughty is a good to have regardless
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?
You might be able to check via the SceneManager. Can't say for sure. You'll need to check it's API
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?
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?
you create "recipes"
check if all 3 match a recipe , if so the output is a gun
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)
honestly, think of it like crafting a recipe. you need 3 ingredients (gun parts) to make the recipe (gun) . . .
But the gun isn't really a recipe, the stat of the gun is just all the part's stat added together
yeah, the last partโthe gunโcan be created a few different ways . . .
the gun is made FROM a recipe
scope barrel body
Hum...OK, I think I have an idea. THX
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 . . .
Wait, I though you cannot create a scriptable object in run time
you can but why do you want to create them at runtime
you can, but it's not recommended. instead of creating an SO, you'd instantiate the prefabs for each gun part as children to an empty GameObject parent. that parent GameObject would have the actual Gun script (or whatever you call it) with a reference to SO gun part . . .
if the parts have to have stats you need to make fields for those specific
eg
Scope
float zoomAmount;
etc.
I think I got the idea now thanks
Let me try it first and see if I need to come back later
Thx
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
The debug ray does not reflect your actual ray. It has a different origin point for starters.
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
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
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
thank you! :D
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 
gonna keep trying, i think im just stupid
bump
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?
You can still do that while that part of the code awaits for the task
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;
}
Is there a reason why you must make it async in general?
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.
there is some problem with unity
Instead, either use a StreamReader/StreamWriter or use Newtonsoft for reading/writing your data reliably
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
It's highly unlikely this is Unity's faulth. If you want to be helped you need to share the relevant !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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);
}
}
}
Ideally, only one of the two objects with said component can exist in the scene.
ignore the comment
Assuming it's a Singleton
So I need to make different script for other object?
You might want to consider informing folks what exactly are you trying to do.
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);
}
If you're just trying to make every object a global object, it's a very bad idea.
I fixed it
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...
so the thing with BinaryFormatter is that it would take my class and serialize it into binary. Is there any code example / library that allows to do this easily?
Not entirely certain but this looks like it's implementing lerp incorrectly (final location is always changing - second argument). Maybe use Vector 3 Move Towards instead of your just wanting one value to go towards another?
I need to restore the camera within a certain period of time
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.
thanks
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
Is it included in Unity or do I need to install it myself?
Newtonsoft is a package
I think it needs to be installed, right?
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
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)
Unity has a package manager where it should be available
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
I'm just starting luckily, so I don't need to migrate phew
Migration specifies the use of System.Text.Json instead, so it kind of comes full circle anyway
That's what I'm saying, it's not in the unity package manager
Try JSON.NET maybe
it would appear in the second image
Oh, right
Can you use System.Text.Json perhaps?
Smooth damp would interpolate relative to time. You may want to check that out.
Try adding using System.Text.Json to the top of your file
only regex
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
it didn't help. And I need an easing
Ok I managed to add it:
https://github.com/applejag/Newtonsoft.Json-for-Unity/wiki/Install-official-via-UPM
You technically don't need to install 3rd party packages. This one also exists: https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.0/manual/index.html
This one also supports .NET Standard which is what Unity uses
Yeah I installed "com.unity.nuget.newtonsoft-json"
Yep, that's the one
See if you can implement it
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).
I already have an easing for lerp
and I described the problem here
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.
I think I did that
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
LGTM. Note you can also use File.WriteAllText and File.ReadAllText to just read/write the JSON directly from the file
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
without using StreamReader / StreamWriter, right?
Yes
It does
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
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.
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?
You're only ever needing them to be attached to stuff if they're Unity components
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?
If your singleton inherits from a Monobehaviour it must be attached
But the singleton pattern is not limited to monobehaviours. It can also be on a class in general
If your static instance is not null it continues to exist, but it will be considered deleted
The correct approach is also removing the instance
Alternatively, use DontDestroyOnLoad or a transitive scene where the monobehaviour is retained
And with DontDestroyOnLoad the GameManager that will be in the next scene will basically retain the same address?
Oh that's neat
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.
Does it make sense to have systems communicate via signaling? Like Game Manager and Save Manager
Maybe you want something like a mediator?
Whatever the case, you might be interested in just trying basic events first
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?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
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.
Without looking at the code, my suggestion would be to use the profiler. Anything else would be guessing.
thanks ill watch a tutorial on it
It's impossible that this script does this
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
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 ๐
not sure how lua interacts with unity/c#, but with coroutines you could use WaitForSeconds or WaitForSecondsRealTime depending on which makes sense
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
Since the player is a snake with the specific length, which can be changed during the length, I also think it would be good to keep track only of the boxes, which are currently on the snake, so those, which might be affected when the snake moves and they lose their standing point, and apply the gravity only to them.
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
ty i just realised i reset unity and its fine again
does anyone know how i can make this not run every frame but like every qauter of a second?
Look at your if statement and think about what it actually says not what you think it says
Use the modulo operator instead
Alternatively, save a timestamp on when to fire again. The docs for Time.time has an example: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Time-time.html
I'd say use a timestamp
thanks:)
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
A custom inspector or a separate window?
I guess EditorTool can be used if it is for the sceneview
Theres a dedicated channel for this btw #โ๏ธโeditor-extensions
yes is scene view related - oh ok thanks
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?
.unityweb has not been a thing for many years. now Unity produces (by default) .wasm.br (Brotli compressed) files
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
#๐ฒโui-ux or #๐งฐโui-toolkit whichever one you are using
oh, okay, sorry ๐
what if I insist on producing .unityweb, is there a way?
no, it is old, if you were using 2017 you could do it
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
So break the statement down, see which is failing the Find or the GetComponent
You can also pass references without resorting to costly find methods through https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Object.DontDestroyOnLoad.html objects or Scriptable Object assets.
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
sounds like everyone's running that function, then
Only the client should be finding the camera, presumably
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
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?
this happens in the start function
yeah netcode
Start will run for every single user when they see that component come into existence
Is this part of a NetworkBehaviour?
uhh i'm not sure. i just have this run in the start function
it's in the playermovement script
Show the entire script. !code
๐ Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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()
{
}
*/
}
should probably be in #archived-networking
please use a paste site for large blocks of code
oh sorry
put it on one (use paste.ofcode; gdl.space broke) and post that in #archived-networking
okay
i want it to open only hen the plaeyr looks at dylan but now it just only works whenm i look anywhere from any distance
https://hastebin.skyra.pw/upusewoheq.pgsql
The entire cs CheckForColliders(); function doesn't actually do anything
At most, it prints a log
wait do you know whats going o with my door scripot and why i can open it from anywhere
Like I said there's nothing in the code that would prevent that
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.
oph ok thx
How can I change a parameter of an animatorcontroller using the new Animator system?
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Animations.AnimatorController.html
It used to be SetBool but now it's gone in the new system
wdym by "new animator system"?
if you're looking for SetBool you're in the wrong class https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Animator.SetBool.html
Yeah you need to look at Animator
AnimatorController is an editor only thing
and both of them have been around forever, neither is "new"
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.
You might want to ask this in a Lua discord server as this server is mainly C# Unity
perhaps they meant coroutines in lua
https://www.moonsharp.org/coroutines.html
Especially as the question you're asking pertains specifically to Lua.
but that has like no WaitForSeconds though, no?
it was me, i did not mean that
i was clueless
No, preferrably the wait thing is handled in C#
use async then or better use UniTask
but how to make that interact with the Lua interpreter?
what is Lua
lol
lmao, even
so your question is about C# not unity, in this case google "asynchronous programming c#"
moonsharp has its own discord server you can ask for help with it in
not really, i think you're misunderstanding the question
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();
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.
Abstract
'Base' is common
okay I didnt read to the end, just answered the first sentense ๐
Base might be a good idea, but usually base class already have implementation while mine doesnt have one though
sounds like it should be abstract then
why do you need to call it if you can create just abstract class and use its naming convensions
or an interface
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
sounds like it should be an interface
Only part of the class dont have implementation
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
i mean that sounds like an abstract class
but that would be using inheritance so idrk what to say to that
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)
yeah that's definitely not applicable here
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
do you have a solid reason to avoid inheritance though?
if you use Interfaces call it just IEnumerator IEnumerable etc.
Lua is an interpeted language and allows you to script stuff without needing to write C# code. It's quite popular for modding, especially on steam. Anyway the if thing, should it be in an infinite loop or something? Wont that make the process get stuck?
I read one stackoverflow comment from someone with very high reputation that implementation through inheritance is not a good idea
only if you allow it, seal the things you dont want inherited
I cant seal abstract and interface, i hope i could
that's not a very good reason
yeah because that doesn't make sense lol
You definitely can write things more functionally and compose behaviors that way, but then I don't know why you'd be trying to follow OOP naming and conventions
read through the comment's reasons for that claim
consider if they're applicable to your situation
don't just take the conclusion as gospel
and 'because I read that I should on SO' isn't a great reason to do that
@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
well no that's not how scoping works
Hmm maybe i need to rethink if i should use abstract and interface, txn everyone
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
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
I already know, part of the class must not be defined by user while the other part doesnt have implementation and must be implemented by user
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
Thats what im already doing, using delegate
yeah but you're still calling it "unimplemented"
your users have access to your code?
No, it is planned to be published as dll
Inheritance is okay but you can do same thing without inheritance just with interfaces, I didn't create inheritance in my last job at all because we used just interfaces, but for me it doesent matter what to use
if it's a delegate, that's not "unimplemented", that's a callback
without inheritance
with interfaces
that's inheritance
the argument is usually inheritance vs composition, but i guess this is.. a secret, third option
well, callbacks.
hmm maybe i should go with abstract class then, i need to google again if this is good idea or not
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
it's in the opposite direction though, i'd consider this separate from the typical composition
actually is it 
interfaces are not inheritance
really having a "i don't need answers, i need sleep" moment here
It is. If your method accept interface as parameter, user can provide their own class which inherit the interface
I think that what you're doing is probably fine and you should forge ahead, not worrying so much about specific naming, until you understand what you're doing
They'd interface the interface? Not inherit the interface? 
Yes you actually right. I mean do not use classes inheritance only interfaces inheritance
Does anyone know a good YouTube channel for learning active ragdolls in unity
Relative to vocabulary
so you'll believe random stackoverflow answers about how inheritance = bad, but you won't believe actual information about how interfaces are not inheritance? maybe i should find a stackoverflow answer that explains it so that you understand it
they'd implement the interface, exposing that interface
in java and ts, interfaces are considered an aspect of inheritance 
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?
I mean, it's semantics but an interface does not traditionally 'inherit' anything, since there is no 'base' and no 'child'
interface is simulation of multiple parents behaviour
though now that interfaces can have default implementations, that gets muddied
that's not the main idea, no
oh, i thought c# interfaces didn't have that ๐งโโ๏ธ
yeah this is kind of what i was referring to with java's exception in interfaces
I dont see how interface is not inheritance. If there is a method A(InterfaceX input), user can inherit the interface and provide their own class to the method as input.
multiple inheritance with a different name lol
C# 8 and up, IIRC
nothing is being 'inherited' in this case
i mean, "interface" and "implementer" are just different terms for the same relation between "base" and "child", no?
abstract class implementations are still "base" and "child" (which i guess just muddies it even more lol)
It only promises that certain methods would be implemented. There isn't any certainty if the underlying types will share a base type.
an interface is a contract
that's implementing an interface. interfaces are a contract that a class will implement specific members. it has no impact on what those members actually do, just that they are implemented so other objects that refer to them by the interface know how to interact with them
i know about this, i think im stuck on the semantics of why it shouldn't be considered the same thing
no, with inheritance you have a Base which has 'pieces' that get 'passed down' to any inheritors
er sorry, an abstract
an interface (traditionally) does not have any 'pieces' to pass down
it describes a contract which you can adhere to
that "traditionally" is pulling a lot of weight lmao
by "pieces" you mean like, implementations/fields, right?
and you can then tell your program that you adhere to that contract, but there is on inheritance
yep
i see what you mean
i mean, with default implementations you can argue either way
but that's the logic
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
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
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)
why does unity run this code when im not pressing space
missing a ), did that even compile?
GetKeyDown
you're excluding important context, such as the remaining condition(s) of your if statement.
thats not the whole code
i only screenshotted the important part
pay attention to the warnings in your IDE
i don't see why not
interfaces kinda inherit Object/the root type anyways
when multiple interfaces exist, they can still be parents/childs of each other, in which case they "inherit" the declarations, no?
not GetKey use GetKeyDown
the ; at the end of your if is the problem
you can certainly do that, but you don't have to do that, whereas with classica inheritance you do
it says warning: possible empty statement
the ; ended the if early so the other code just runs always
since when do if statements get terminated with ; ?
I would argue that the interface is not inhertiting anything in this case. It doesn't know or care about the base object class
a single interface still falls as a child of Object anyways, same as a standalone class
every object is a child of object, it has nothing to do with interfaces
when a variable is typed as just an interface, Object members are still accessible
You have semicolon at the end of your if. The code block and the if block is separate. Your jumping debug log is not inside if statement because the if statement ended by the semicolon
well sure, because all objects are children of object, no interfaces here?
I guess I'm not sure what you're saying
๐
this is just because everything inherits System.Object. structs don't support inheritance at all, yet they still inherit System.Object
im suprised it lets you put if(); and doesnt immedialy tell you off
It did you just did not see it
it literally does
so an interface is "aware" that it's an object, is my argument
the variable typed as an interface
it's a contract that other things can fulfill
yeah yeah
having {} on its own is valid but it tried to warn you with the squiggles
guys, this is hardly a Unity discussion
yes it is
yes this is my argument
it is code general discussion so discuss C# is okay I think
I mean, it's a code discussion in the code channel when no other channels are busy so it seems fine to me
The semicolon only terminates the statement - disregards the body associated with the if-statement. Perfectly valid for while loops with no body and whatnot - though more often than not, found with code resulting in unwanted behavior if not explicit.
let the battle commence
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
Hello, i'm new to unity. How do i set lang version and .net version? IntelliSense complains that i cant use with keyword
well take it to a thread because you guys are flooding the channel
yes we've been through this one before
you don't they are built into Unity
yes thats my point it is actually implementation not inheritance
then surely the matter is settled and you admit that interfaces are not inheritance?
๐จ
So there is no way to use new features C# devs made?
๐ซ gotcha
It is hard to modify the csproj of unity project. If you do modify it, unity will likely regenerate it unless you do some very specific things. This is also why i complain that i cant set nullable to enable by default in the csproj.
wut even if you did that it wont magically work
The interface only defines the members though (this used to be true) whereas with inheritance, you may have more than just definitions.
and interfaces create in c# for simulate multiple inheritance what is not quite far from what I said before
no, it wont
why cant unity devs just make there selector of c# and .net version. I didn't think unity is like that
well, thanks for answer
You can select the .net version in player settings. You can only choose between .net standard and .net framework though
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
because it is not as simple to do so as it sounds
There is one but the .net version is kinda outdated and wont change untill it changes to .net core (from mono)
haha soo many replies
"admit" wtf 
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
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
every time i bake my Lighting it crash
It is .net framework 4.8 btw
not even .net 9
yea we all suffer