#archived-code-general
1 messages Β· Page 150 of 1
of wht
so either you have modified it and made a mistake, or just a big typo
just in case there are more problems, this is the link for all (i assume, i didnt watch the video myself) scripts from the video https://github.com/lchaumartin/SpiderProceduralAnimation/tree/FirstVideo/Scripts
erm
nothing works π
i tried some tutorial for this but everything i try fails
if i make the animation by keyframes in blender it will look horrific
how do i fix my camera view clipping into things
camera has a property for that
i think its called near clipping plane
set it to 0.01f
Camera.nearClipPlane
Select an object and click F once or twice if your editor camera is doing weird things
is there anyway to do something like this just in the program for visualization purposes? like it still is just top down. Is it possible in notepad or any other programs?
Are you asking how to make ASCII art?
no, its maps for a html platform game
You can certianly write a graphical program that lets you produce that text, sure
I'm just wondering if theres a way to like partition a block of text and shunt it into a popout window for visual purposes
Nah not that, like
Just in a coding software
to help with the coding process
I'm not sure I understand the workflow you're looking for tbh
I'll make a better photo to explain what I'm going for
It would probably be better to define that string in a separate file
and easier to pull it out to a separate window
have your code read it from the file
most code editors and fancy text editors will let you open two tabs into the same file though
I'm not sure what I'm looking at here.
Im trying to expose component variables in my script with EditorGUILayout.FloatField, but every time I re-enter the prefab the components reset, how do I fix this?
oh wait I see, it's wrapped on the screen
@inland dust I agree with @leaden ice, you should just have a separate editor, like a WYSIWYG editor with a font that gives clean spacing.
yeh, i need to learn more
Considering how much of a pain it is to edit text though to make levels
You could also create a system where you feed in a 64x64 image, and you associate each color to a character.
You would have to keep track of some sort of legend that says "brown is C"
I was planning maybe using two images for every world
where 1 is the visuals the other the interactables, like collision and objects and npcs
because you have to stack objects in a single space right?
thx
Kindof, only objects and NPCs would actually be visualized, collision based things would just be the data
Hmm, thanks yeh, I'll just give up on the text
and work with images
If you went one step farther, you could have some small sprites and a grid, and then use some of unity's tile tools too easily draw things, then export that as text
I'm not doing this in unity at all
Why are you asking in the Unity discord then π€
I've made some cool stuff in unity but I like understanding everything that goes into it
Cause you guys still helped?
I actually dropped the same question in a few code related servers im on
you guys answered first, and therefore the most helpful!
This server is for Unity specific coding questions, only.
well ok, I wont ask for help then?
the thing is unity coding is still applicable to almost all other code? its just logic
Sure, and questions that don't fall into the "almost all other", don't belong here. If you have a Unity specific question, you're free to ask.
Though, as you said, you're not using it. π€·ββοΈ
which thread is non unity code?
on any other server
Ah, okay goodbye forever everybody
didnt know the unity server was like this but okay...
why is this happening? I've already tried reimporting all assets
my visual studio is updated to the latest version
Does the error also appear in the Unity Console?
Hm, can you post the full error message?
wait mb again, the error is indirectly related
isnβt there a UI package that you have to import?
its a button error due to the UI not having a reference
no
Actually yes
Yeah UI is there by default
but it's in most projects by default
Where is this script? Is it inside a package or a folder that has an assembly definition?
did you put an assembly definition file in that folder
no
show the unity editor console window
but ive never had to do it before
no console msg
VS probably just desynced from Unity, it happens
i did that
nothing changed
i think wat caused it was me hitting ctrl + b
Unload the solution in VS, and reload it with all dependencies
so i built the .cs file independently of unity or sum
close vs, delete .vs open vs
how do i do that?
From the Solution Explorer tab, right click the project, Unload
Heya, anyone know how to make a method that gets called each time a new scene is loaded in a singleton script? Since stuff like OnEnable() won't work there
put it in Awake i think
View, Solution Explorer
It's closed it seems
SceneManager.sceneLoaded
- Listen to this event https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html
- Have a script in the new scene call a function on the singleton
ty all! β€οΈ (:
these are the options i get wen i right click the project
well i right clicked the solution..
Oh weird. Assembly-CSharp is the one
@orchid island did you do this - close vs, delete .vs open vs ?
One thing at a time
where do i find the .vs?
root project folder
ill try if this doesnt work
has to be the other way around
generally you first nuke .vs and then in 99% of cases the issue is resolved
Does anyone know how to fix the problem of "CreateEditor" having values not save when a prefab is exited and re-entered?
im trying to do a multiplayer game and read i need to set the variable "Default Is Networked" to true. I cant find it in project settings, can anyone help?
by "CreateEditor" you mean? show code
didnt work
im trying to create a layered inspector where I have an inspector for the "wheel" which is then brought to the "suspension" inspector. Problem is that when I change values through this, it resets the next time I enter the prefab im editing it in.
yes
yeah... i deleted it and reopened vs and nothing changed :/
then proceed to the previous branch
tried that too
Hmm, whats considered a clean pattern in a Dependency Injection setup to hook up your existing world GameObjects to your dependency tree
but for future always delete .vs when you have issues like intellisense stopping working, or files not recognized or namespaces or errors displayed that are not real
.vs is where vs cache is and it often gets corrupted
drag n drop
"Clean" is subjective π€·ββοΈ
this is curious case, if it was a serializedproperty you could manually
property.serializedObject.Update();
property.serializedObject.ApplyModifiedProperties();
Im thinking I might need to pass in all my GameObjects as variables via Editor on the "Root" of my DI tree, which should be a single monobehavior (and then everything else all the way down are POCOs)
and then I have some kind of "GameObjectManager" I register that handles holding a reference to my "scene" game objects
but i dont know how created editor (which you create on each gui call btw) behaves
what you can do to hack around this is to set the object dirty
So heres my issue, effectively speaking the GameObjects are all monobehaviors, so I dont think I can simply just Inject them, especially if later I want to also have more instances of them get made dynamically, as opposed to the ones that you start with in the scene
through EditorUtility.SetDirty()
this circumvents normal unity serialization mechanisms for inspector display but ensures that the data wont be lost
Like uh, lets say I have a Bat enemy, I might have a buncha BatEnemy prefabs dropped in preset spots in the scene they will always be.
But I might also have a VampireEnemy that has SpawnBat() to summon moar bats dynamically
When talking about references to obejcts created in code I'm not generally linking that concept with DI in my head. It's more for hooking up to existing stuff in the scene
you are serializing references at edit time, its not really DI
for dynamically loaded objects - you're basically going to end up with a collection at runtime to track them
but something like a "BatManager" which holds the list of bats could be injected
So lets say I have a BatManager in my DI chain, its job is to manage the bats. Creating em, deleting em, their AI, all that jazz. Its where all the bat logic goes.
Now I could dynamically generate all the bats with it at runtime, and then it'll of course have a ref to any bat it has generated itself ez
But what if I have like, 500 bats in "preset" places in the game that I already could have set and baked in
I presume the act of generating 500 bats from a prefab at runtime with a script is far more expensive than doing it via the scene editor and having all those prefabs already placed at compile time right?
the second one will effectively have done all that work already and "baked" em in right?
not really
most likely there is marginal difference
you probably get gains because unity will batch deserialization
but all the components on those objects will go through the same init calls
but for prebaked bats you can:
- Use
FindObjectsOfType<Bat>in the Awake for your BatManager - make a List<Bat> in your BatManager and drag n drop all the scene bats in.
It also means I gotta write all the code and stuff for placing those 500 bats, vs them being placed through the editor already
BatManager is a POCO, it has no Awake
it should be a MonoBehaviour
No it will be a POCO
call it from a MonoBehaviours Awake
what i assume most DI's and other architectures do is go through all the scene objects before they are initialized
doesn't matter
Only the very top level entry point will be a MonoBehavior and everything else can just be POCOs going down
have that top level thing call Initialize() on the POCOs
So yeah the List<Bat> was the second option I originally outlined
scene.GetRootGameObjects(), disable all roots, visit the hiearchy looking for what you are interested in
then restore the scene state
Effectively what I was describing was a SceneObjectManager service or whatever, who's job is to go snag all those existing objects in the scene at startup and manage the Refs to em
So it can be used to get all the bats, the player, all that jazz
aight, was mostly just sanity checking that its a decent way to approach it
type is not abstract?
not generic?
if its generic you have to construct generic type
where is the GoToState<DiggingState>
what subclasses it
Default constructor not found for type Characters.Core.States.DiggingState
so you are invoking that with a T that is DiggingState
anyway, this possibly just means that Character is null
possibly
ah
i remembered this one
let me check
no that was something else
what was it?
hmm, my next thing Im mulling over is at the core of my game I want to build all of the stuff that happens around "ticks" or "rounds", and I want a way to start off by firing off "okay everyone a new tick is starting, everyone do 1 tick of stuff", and then everyone does their 1 thing, which can take a variable amount of time, and then once everyone gives the thumbs up that their "thing" is complete, then the system queues up the next tick of stuff to do
simple example would be simply just movement, the player could click to queue up moving 3 squares, each 1 square of movement counts as 1 tick, so all the enemies will also move 1 square, possibly (some enemies may only move one square every 2 ticks, so they skip every other tick and give back an Okay asap every odd tick, doing nothing)
I definitely am thinking Coroutines are gonna be involved here, and some kind of callback to signify the given entity has completed its coroutine, and once everyone signs off, the next tick fires
is character a uobject?
a central "Tick manager"
public event Action<long> OnTick;
float TickDuration = 0.02f;
float timer;
void Update() {
timer += Time.deltaTime;
if (timer >= TickDuration) {
Tick();
}
}
void Tick() {
TickCount++;
OnTick?.Invoke(TickCount);
}```
nah ticks arent duration based, its action based
like "rounds" maybe is a better word
turns
yeh
then yeah a turn manager. Just keep a list of objects which need to act
and have them call back to the manager when they're done
at which point the manager removes them from the list/set
and when the set/list is empty you move on
yeah thats what Im thinking, Im thinking instead of events though, if you havent tried em yet, Pipes are super cool
works similiar to events but inherently Async
I dunno how I go about firing off a Task that doesnt block though, but still has a callback of some form I can monitor from Update
I have code for storing scripted objects so I can use the array as an ID
but right now its a class but I want it to be predefined and global (I think is the term?), so any script can access the lists data from any scene (even if I need to define everything myself like how minecraft does it, just without the registering stuff they use lol). I feel like I need to use a struct but im not sure how I would convert what I have.
the class based way I'm using right now is simple as its just for storing data
public class GameTileManager : MonoBehaviour
{
public List<GameTile> tiles;
public List<Stamp> stamps;
public List<GameTile> decoreTiles;
public List<FunctionTile> functionTiles;
}
help and direction would be amazing!
still new to this higher level coding even if it is basic stuff
look up "Unity Singleton"
ill ask phind about it, thanks!
is it safe to modify a class variable from inside of a fire and forget async void task, that future Update calls will keep checking in on?
hello I need some help, will wait till you finish your discussion
Is there a difference in overhead between declaring a function and using a lambda?
or is the difference purely that lambda functions can basically not be detached from events?
I think you are probably interested in UniTask
something like, uh
bool Busy = false;
void Update() {
if (Busy) return;
GetBusy();
}
async void GetBusy() {
Busy = true;
await Task.Delay(2000);
Busy = false;
}
Will Unity be cool with this?
it depends how the lambda is used. Generally lambdas are creating new instances all the time depending on variables
Hi, can anyone tell me which guide I can read to create my first tycoon game? Thank you π
sure but why bother with Update here?
current context is smt simple like this ```cs
public void AddToScene()
{
handle = Addressables.LoadAssetAsync<GameObject>(_reference);
handle.Completed += HandleOnCompleted;
}
private void HandleOnCompleted(AsyncOperationHandle<GameObject> obj)
{
Instantiate(obj.Result);
}
this is not using any Lambdas
it's kinda complex - but if your lambda needs to do any variable capture, it will create a new object (new delegate) every time you run AddToScene
so instead of await Task.Delay() its actually gonna fire off a Pub/Sub Pipe<ReadyEvent> or whatever that all of my other classes are listening in on, and itll delegate out "do this action" on the pipe which they read off of async, and then when they finish they fire back on the same pipe "Okay done" and once everyone has fired back "okay done" then it sets Busy back to false, which on the next Update tick will refire off the method if there's another "round" queued up
ah, like that
I do wonder, what happens if I call the AddToScene a second time? does it instantiate it immediately or does it work differently?
but why do you need Update for that? WHy not just fire the thing in GetBusy after the await
You should really look into UniTask
without UniTask Unity's async support is kinda pitiful
it's very half baked
So something like, uh
async void GetBusy() {
Busy = true;
var events = CalculateNextRound();
var writeTasks = events.Select(e => OutPipe.WriteAsync(e)).ToList()
await Task.WhenAll(writeTasks);
await foreach(var ready in InPipe.GetStuffAsyncIForgetTheMethodName()) {
}
Busy = false;
}
something vaguely like that
ah cause there might not be another round of actions queued up, at which point we hand back control to user input and the interface becomes re-enabled
instead of Busy = false just put this in a loop
yeah busy=false is just pseudocode
its more likely to be
while (queuedActions > 0)
``` or whatever
it has an exit case for once its chewed through all the queued up rounds of action to complete, at which point Update() will start handling other stuff like re-enabling the UI, and looking for user input events (which will re-queue up 1 to n more rounds of actions, which puts us back into re-firing off this task)
Hi I was reading up on task cancelling, Is this correct pattern to cancel a UniTask?
private CancellationTokenSource cts = new CancellationTokenSource();
private async UniTaskVoid LoadAndUseAa()
{
var go = await LoadAa(cts.Token);
// do something with go
}
private void CancalLoadAa()
{
cts.Cancel();
cts.Dispose();
}
private async UniTask<GameObject> LoadAa(CancellationToken ct)
{
var handle = Addressables.LoadAssetAsync<GameObject>("Something");
await handle.WithCancellation(ct);
Debug.Log("Loading done.");
return handle.Result;
}
Thank you π
@leaden ice so something like, this, ish
int queuedActions = 0;
void Update() {
if (queuedActions > 0) return;
if (noUserInput) return;
var actionQueue = GetQueuedActionsFromUI();
GetBusy(actionQueue);
}
async void Getbusy(DoTheThing[] actionQueue) {
queuedActions = actionQueue.Length;
while (queuedActions > 0) {
var events = CalculateNextRound();
var writeTasks = events.Select(e => OutPipe.WriteAsync(e)).ToList()
await Task.WhenAll(writeTasks);
await foreach(var ready in InPipe.GetStuffAsyncIForgetTheMethodName()) { ... }
queuedActions--;
}
}
Dudes, to doc TDD and GDD, do you use wiki in git for example or jira?
Where do you put it?
technical docs git, design googledocs
I honestly feel like there's still no need for Update:
- GetBusy can disale and enable the UI at the beginning/end
- All UI interactions will have callbacks which can call GetBusy
GetBusy should only be called in 1 place, largely speaking, at the root
nothing I said really contradicts that?
technical docs git, you mean git wiki?
I have suggested google docs for GDD. They say because it is just one doc and it can contain many pages maybe there are some problems in loading
Id have to mess with it but, I would want to do things other than GetBusy in the update method, it should be firing off many other things, or not firing them off, etc
like in my example its just calling GetBusy but in reality there may be dozens of other things that could be firing off instead of GetBusy
or I guess we can call it PerformCombatRounds() or whatever
like it wont be getting called during cutscenes and stuff, and outside of combat
I dont want PerformCombatRounds() to be running constantly 24/7 on the game, effectively, it should only spin up for combat and then spin down when the rounds conclude
if you do:
int x;
what is the value of x? You can't do:
x + 1;
So what is x? I thought it was 0 but it can also be infinite or negative infinte. Is it all 3 at the same time?
you can indeed do x+1 in C#, non nullable int will default to 0 on init :3
if you declare int? x though, that will default to null
Looking for some ideas on a code design problem - Im working on a FSM AI system that uses ScriptableObjects, my setup is essentially "AIAgent -> holds SO's for Idle, Chase, Attack -> agent performs logic/checks to change to Chase when player in sight, then Attack when in range", once in range/in attack state, it will periodically call an event to attack, and this is where im not sure the best next step - should I make a MeleeAttackSO and a RangedAttackSO, or create 2 extra scripts that subscribe for both types of combat (which would mean the agent would have specific state logic, which I dont really like), or is there another option I could look into? The reason im using SO's for the states instead of just classes, is so I can more easily modify what each "type" of AI should be, maybe one could patrol and chase but not attack, etc
Everything declared but not initialized takes value represented by the default keyword, including local and global variables.
Or do we have code samples to read on how to architect Task cancellation properly?
I think normal task system you need to do try catch and stuff and pass the token around into each of the Task method and polling token status in each of the Task (painful). Not sure how this works out w UniTask? For example even if I call cts.Cancel it seems that no exception is thrown?
it gave you error because the value was not initialized
class members are initialized for you
locals have to be initialized
also not x + 1 its x += 1
public void Foo()
{
SomeLargeStruct s;
bool condition = false;
if (condition)
{
s = new SomeLargeStruct();
s.x += 1;
}
else
{
}
}
if the condition here is false, s is never initialized, meaning its never allocated meaning you dont waste cycles
same thing will happen if you just move declaration into if but there are scenarios where its preferable to forward declare variables
Hey, does someone know how I could create a list of variables I can hide and show in the editor (like the screenshot) without using lists ?
Well lists and arrays are both serialized to the inspector, how else would you want to try and store that data without them?
Oh wait, these are not game objects/transforms, are they?
I mean, how could I create a list on the editor without using a list or arrays in my code, a list i can hide or show
Because I have a lot of serialized variables and I would like to know if its possible to make it more readable
Use the foldout attribute from here https://github.com/dbrizov/NaughtyAttributes
Or you know feel free to use other attributes from here to make your inspectors look better
That seems like a really useful git
yep, thanks i'll try it
Does anyone know why my script execution order wont go below the letter "N?"
I cant find ANY resources for why it wouldnt let me add a script to the list
like anywhere on Google, is there a bug or is there some reason i wouldnt be able to find a script in the list?
is it displaying as the namescpace?
It starts with PM_
but it cuts off right at "N"
can my script not be in a subfolder? i organize via Assets/MyFolder/Scripts/ScriptOrganizationName/TheScript.cs
SMH nevermind you can drag and drop the actual script from the folder into the list, so it doesnt matter
I guess this really isnt code but anyone know why remote 5 just isnt working randomly?
even when I close and reopen its just not working and in unity all the stuff is right
it was working like 10 minutes ago
When you plug in your device click this
Make sure it's on USB tethering
Sorry I should have mentioned Im using IOS
oh... I hav no idea then lmao
you might not have the package installed, or you may just need to regenerate project files
I've tried:
- deleting the .vs folder
- deleting all .sln and .csproj folders
- reimporting all assets
- regenerating project files
- unloading and reloading the project (with dependencies) from vs code
my vs code is also updated
Is this error in Unity too or only vsc
do you have the package installed
wats the package name?
the ui package
Unity UI iirc
this answer will tell you
i dont think it has anything to do with the package tbh, cuz i hav TMP installed and "using TMPro" is also not working
then it's just VSC
do you have the visual studio code editor package installed
and is it up to date
(also VSC is kinda terrible with Unity tbh)
\
wait fr? ive used it for years lol
u use mono?
it's by far the best - but it's not free unless you're a student
i am
would definitely use it then
what advantage does it have over vs?
- faster
- better search features
- better Unity integration (shows you all kinds of things like when fields have values assigned in inspectors, unityevent listenevers, etc.
- usages in the unity project
- fucking works all the time without any effort
"must only be used for non-commercial educational purposes" lmao... how they gonna know?
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Hi, let me know if this isn't an appropriate place to ask, but I've got a very strange problem here. It seems like Unity's random isn't working anymore for one specific project. Here's the line of code in question:
Debug.Log(Random.Range(0, System.Int32.MaxValue));
No matter how many times I call this, I always am getting the number 0. This line works fine for (at least one of) my teammates, and System.Random works fine:
// This works
System.Random systemRandom = new System.Random();
Debug.Log(systemRandom.Next(0, System.Int32.MaxValue));
This line also used to work just fine for me, but it seems to have stopped working today for some odd reason. It also worked when I made a blank project, but when I made the same script in an empty scene in my other project, it was still broken.
I've tried re-cloning the GitHub project, restarting my computer, and re-installing unity. No luck. Does anyone have any clue what could be going on here? Is there editor/project settings to do with Random somewhere that I don't know about? Has Unity just developed a grudge against my computer?
Are you calling https://docs.unity3d.com/ScriptReference/Random.InitState.html anywhere?
can you show the code?
No, but this has been working for a few months now and only broke today.
This is the entire class I tested in an empty scene:
public class UnityWhy : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log("system max value: " + System.Int32.MaxValue);
Debug.Log(UnityEngine.Random.Range(0, 5));
Debug.Log(UnityEngine.Random.Range(0, 5));
Debug.Log(UnityEngine.Random.Range(0, System.Int32.MaxValue));
Debug.Log(UnityEngine.Random.Range(0, System.Int32.MaxValue));
Debug.Log(UnityEngine.Random.Range(0, System.Int32.MaxValue));
Debug.Log("SYSTEM RANDOM");
System.Random stupid = new System.Random();
Debug.Log(stupid.Next(0, System.Int32.MaxValue));
Debug.Log(stupid.Next(0, System.Int32.MaxValue));
Debug.Log(stupid.Next(0, System.Int32.MaxValue));
}
}
and it prints 0 three times in a row?
Does the same thing occur with int.MaxValue? Just curious . . .
No, Debug.Log max value gives me 2147483647 as usual
rider actually solved my problem, ty
Interesting, are you calling Random.InitState anywhere?
No
Can you try calling it with any number before call Random.Range?
Hmm, interesting. Calling Random.InitState(0) did make it spit out some numbers that were not 0. But that brings up 3 questions:
- Why was it working before
- Why is it still working for someone else
- Why do I have to call it in the first place? I thought unity called that at some point itself
It might have somehow picked up some broken state and maybe you don't have domain reloads enabled or something?
I'm going to go and check to make sure we aren't loading random's state somewhere, thanks for the help
I have no answer to those questions but if it is for your local PC, Unity is likely using system clock or something to init state, so maybe problem with that
It seems that the culprit was this line:
Random.state = SaveManager.savedRandomState;
We have a save manager that saves a bunch of stuff, and it looks like someone added the random state to it. Now, why on earth it wasn't working for me, but it was working for other people, I have no idea. Also not sure why exactly we're saving the Random state in the first place. But anyway, thanks for the help!
it sounded better in my head
I just discovered PlayerPrefs
PlayerPrefs should be avoided like the plague
Can you not though
so basically I use the OnCollsionEnter/Exit function to help track fall damage for my player. Only problem is when the player moves from one ground object to another adjacent to it, the methods arent able to properly detect if the player has actually become off the ground
shown here ^
i tried putting the function in an Invoke() and waiting like 0.2 seconds later but that doesnt seem to change anything
track either:
- a set of colliders you're currently touching
- the number of colliders you're currently touching
yes i do
only when it becomes 0 have you stopped touching the gorund
and only when it goes from 0 - 1 did you start touching the ground
that will let your code distinguish
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.tag == "ground")
{
Collider[] colliders = Physics.OverlapSphere(gameObject.transform.position, gameObject.transform.localScale.x);
if (!(colliders.Any(c => c.gameObject.tag == "ground")))
{
Debug.Log("Is in air.");
isInAir = true;
}
else
{
Debug.Log("Still colliding with: " + string.Join(", ", colliders.Where(c => c.gameObject.tag == "ground").Select(o => o.name).ToArray()));
}
yOnExit = gameObject.transform.position.y;
}
}```'
ik about the redunant if condition i'll fix that later
what's with the OverlapSphere
This is my recommendation
i need to make sure the player isnt touch ANY ground objects though
I know
Again ^
use this
e.g.
OnEnter() {
numberOfColliders++;
}
OnExit() {
numberOfColliders--;
}```
when it's 0 you're touching nothing
when it's 1 or more you're touching something
that wouldnt do anything though because like the image above, the two objects enter and exit each other interchangeably
it would do everything
when you leave one object, you enter another so the object's never 0
OnEnter() {
numberOfColliders++;
if (numberOfColliders == 1) {
// Have just touched first object e.g. has just Landed
}
}
OnExit() {
numberOfColliders--;
if (numberOfColliders == 0) {
// Have just stopped touching last object e.g. has actually just come off the ground
}
}```
for example
im curious where u got this idea from, that an object is always touching something
if it was the logs from the previous code youve shown, that logic is flawed since you are using a OverlapSphere on the same frame you OnCollisionExit. Also it was kinda bloated with a lot of linq thats not needed
What praetor wrote is good, i already use the same logic in my game
i have a first person controller in which case that i want to flip the player's gravity for some puzzles, can anyone help?
flip the player's gravity upon pressing a certain key i should add
this is the test level
and this is the code for the player
[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
[Header("Movement Settings")]
public float movementSpeed = 5f;
public float jumpHeight = 2f;
public float gravity = -9.81f;
[Header("Look Settings")]
public float mouseSensitivity = 100f;
public Transform playerCamera; // Reference to the main camera
private CharacterController characterController;
private Vector3 playerVelocity;
private bool isGrounded;
private float xRotation = 0f;
private void Start()
{
characterController = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
}
private void Update()
{
HandleMovement();
HandleMouseLook();
}
private void HandleMovement()
{
// Calculate player movement
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 moveDirection = transform.right * moveHorizontal + transform.forward * moveVertical;
// Apply gravity
isGrounded = characterController.isGrounded;
if (isGrounded && playerVelocity.y < 0f)
{
playerVelocity.y = -2f;
}
// Handle jumping
if (isGrounded && Input.GetButtonDown("Jump"))
{
playerVelocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
// Check if the player controller detects the bottom of a GameObject
// and adjust gravity accordingly
if (isGrounded && IsUpsideDown())
{
gravity = 9.81f;
playerCamera.localRotation = Quaternion.Euler(180f, 0f, 0f); // Set camera upside down
}
else
{
gravity = -9.81f;
playerCamera.localRotation = Quaternion.Euler(0f, 0f, 0f); // Set camera upright
}
// Apply movement with gravity
playerVelocity.y += gravity * Time.deltaTime;
characterController.Move(moveDirection * movementSpeed * Time.deltaTime + playerVelocity * Time.deltaTime);
}
private void HandleMouseLook()
{
// Calculate mouse look rotation
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
// Rotate the player body horizontally
transform.Rotate(Vector3.up * mouseX);
// Rotate the camera vertically
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
// Apply camera rotation
playerCamera.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
private bool IsUpsideDown()
{
// Raycast downwards to check if the player controller detects the bottom of a GameObject
// Modify the raycast origin based on the player's current orientation
Vector3 raycastOrigin = isGrounded ? transform.position : transform.position + Vector3.up * 0.1f;
Ray ray = new Ray(raycastOrigin, -transform.up);
return Physics.Raycast(ray, 0.2f);
}
}```
why are you only flipping gravity while the player is grounded?
how would you suggest i fix it?
idk, it's kind of unclear what your flipping condition is actually supposed to be
well my goal is to have it so that if the player's gravity is flipped, the player object's gravity is reversed therefore sending the player object into the sky unless it collides with another object and walks like how it originally did prior to the gravity flip
Someone familiar with Netcode for GOs (specifically network animator) can help with a problem related to animator layers?
Iβve looked up quite a bit and canβt find anything (useful)
im trying to make the gravity manipulation be like this
https://www.youtube.com/watch?v=QmiNMI2dYCU
Gravity Cat Gameplay PC 60FPS [PC Gameplay Let's Play] Gravity Cat Walkthrough Playthrough
Platform: PC Steam
Genre: Platformer, Indie
Game Release Date: 14 Jul, 2016
Developer: Quiet River
Download Gravity Cat Steam Game: http://store.steampowered.com/app/491000/
Website: http://store.santaclaragames.com/games/8days/
Subscribe for more gamepla...
but in first person
(ping me if you have an answer, i'll be inactive because i hav to go to bed soon)
The perspective shouldnt matter in this case, since gravity is usually the same Y axis in both 2D and 3D, I could show you an example if youd like though the general idea would largely involve flipping the sign on your gravity on whatever your using to move your character, if its a rigidbody with its gravity, id suggest applying your own gravity instead, that way you can manipulate it - one way you can do this is have a bool track "isFlipped", and on input, or game trigger or however you want to "activate" it, call a function that flips the bool (someBool = !someBool), and use that bool to determine the sign of your y velocity, you can also use the bool to lerp the rotation if you also want the "flip upside down" in addition to the "fall upward" effect - as a side note just for organization, I would also suggest maybe putting that logic in its own script, and either initializing it in your player, or attaching it as another Mono script to your player, that way you can also easily decide to disable or debug its logic in isolation
You can serialize a list of type float, int, MonoBehaviour, etc... But why cant you serialize a list of type list of type float, int, MonoBehaviour, etc... ?
Because Unity says so
You can add wrapper [Serializable] type that holds list and serialize list of that type
is there a way to convert screen coords to scrollbar coords? i want to tween a card on a scrollbar to the center of the screen
One question.
I have implemented my own nav voxel agent. It is similar to NavMeshAgent unity with same functionalities.
I use it for my npcs. Now, I have added a new behaviour falling. Should it be in a separate class? right?
I mean controlling if that character is on the ground or not and updating it
such that you could...attach falling as a separate component and only have some of your npcs that fall?
i have a StartCoroutine(...) in an OnPointerClick event. why doesn't it work twice?
it seems to break the entire method call, because if I set the coroutine to start on right clicks it makes left clicks break as well
hello, is it possible to print where method was called? e.g.
void Bla()
{
Foo();
}
void Foo()
{
print("called in `Bar()`");
}
why should it work twice?
does it stop coroutine somewhere?
trying to figure that out rn actually
give your code
figured out it works in one direction but not the other
public class CardFlipHandler : MonoBehaviour, IPointerClickHandler
{
private Image currentImage;
[SerializeField]
private Sprite _frontSprite;
[SerializeField]
private Sprite _backSprite;
private bool faceUp = true;
private bool isTurning = false;
private float tweenSpeed = 0.01f;
private float degDelta = 10f;
public void Awake()
{
currentImage = GetComponent<Image>();
}
public void OnPointerClick(PointerEventData eventData)
{
// Placeholder input, not sure yet
if (eventData.button == PointerEventData.InputButton.Right)
{
if (!isTurning)
{
StartCoroutine(FlipCard());
}
}
Debug.Log("End of pointer click callback");
}
private IEnumerator FlipCard()
{
Debug.Log("Coroutine called...");
isTurning = true;
if (faceUp)
{
Debug.Log("faceUp");
for (float i = 0f; i <= 180f; i += degDelta)
{
transform.rotation = Quaternion.Euler(0f, i, 0f);
if (i == 90f)
{
currentImage.sprite = _frontSprite;
}
yield return new WaitForSeconds(tweenSpeed);
}
}
else if (!faceUp)
{
Debug.Log("!faceUp");
for (float i = 180f; i >= 0f; i -= degDelta)
{
transform.rotation = Quaternion.Euler(0f, i, 0f);
if (i == 90f)
{
currentImage.sprite = _backSprite;
}
yield return new WaitForSeconds(tweenSpeed);
}
}
Debug.Log("Coroutine loop ended");
isTurning = false;
faceUp = !faceUp;
}
}
probably using stacktrace and System.Diagnostics
thx
is coroutine just not called?
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
public class playerMovement : NetworkBehaviour
{
private Rigidbody2D rb;
private float speed = 20f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (!IsOwner) {
return;
};
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
// Calculate movement vector
Vector2 movement = new Vector2(moveHorizontal, moveVertical) * speed;
// Apply movement to the Rigidbody
rb.velocity = movement;
}
}
i think it is being called, i have a bunch of print statements throughout and it covers all of them up until the end of the callback
I can move as a host but not as a client
you think?
then what exactly must be done but isn't?
i have no idea at this point π
i think ima just sleep and try again in the morning lol
what a nice attitude, if you cannot even explain what goes wrong, how do you expect us to help you?
thats a little rude man :/ thats the reason i asked in the first place
we're programmers not the messiah lmao
im at my wits end, as far as i can tell everything in the callback is covered, i was just asking here to see if i could cover my bases
we can't figure out where you've gone wrong without the information
yea i know :/ but thats pretty much all im aware of unfortunately
that's not rude, I have asked you whether you can explain what goes wrong
was just a hail mary wasnt looking to get grilled π
as a programmer you have to learn how to diagnose problems
figure out where your code is going wrong
if I give you random code and say "it doesn't work", will you understand?
yea man i stepped through the entire thing and couldnt find anything. its an annoying heisenbug, was just hoping if i was missing something glaringly simple
how do you even know that it doesn't work if you cannot say what doesn't work?
that sounds like you need help, but you're too lazy to explain
alright, to be fair, i didn't just post and say "sorry it doesn't work", i said "it doesn't work on the second try, i every step of the callback and it covers everything with no errors, and yet it breaks"
be more specific
Use context object parameter to point to the object running the code. If you mean that https://docs.unity3d.com/ScriptReference/Debug.Log.html
don't lose your and our time and just say what you need to do
think of the rubber ducky
if you wanna solve your problem you gotta explain it
if you explain your problem you often times end up finding out the solution on your own
no, that's not what I need.
I think bawsi has mentioned correctly that it should be done with System.Diagnostics
i did π spent an hour trying to explain the control flow to myself and as far is i could tell it was ok, and the prints scattered throughout seemed to have confirmed it either. could have definitely been more specific up front instead of doling out info piecemeal though
If you actually want to pass the method executed in another class you can pass it as action
I don't get it, I know that I can pass it like nameof(Bla)
like i definitely wanted to be more specific but idk man sometimes you just run into some BS heisenbug that you cant even replicate. sorry :(
well, do you even have issue?
what even is the issue i personally am not aware
yeah, it's still broken, but in between this text convo i discovered the positions were looping around from 180 to -180 which may have a role in things breaking (which I didn't know when I typed this)
"smth doesn't work"
what positions?
i'm trying to tween a card flip. i have a coroutine called inside an OnPointerClick() (from IPointerEventHandler). for some reason, it breaks on one side of the flip, but not on the other. i provided my code, and put print statements all throughout to trace the callback, and it ended just fine. couldn't tell waht else was going wrong
rotation Y axis, -180, 180
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
it should rotate from 0 to 180, then flip back from 180 to 0. but once it hits 180, it wraps around to -180. thing is, the other card flip conditions starts at 180 and rotates back to 0. i don't think that should break anything because should be setting the rotation to 180 in the first place, but it's the only lead i've got
thats what im sayin dawg
@vale wren Debug the problem properly. Use breakpoints to walk through the code and state of the objects. https://unity.huh.how/programming/debugging/debugger
ok, no, that can be.
Then ask the full question here when you know what the problem is
bless, couldnt figure out how to use the debugger
use the good old print out every variable you can think of method
it just rotates from 0 to 180 on first click
then back
on second click
thats what it should do, but tracking the position in the inspector it jumps to -180
though that shouldnt break anything because it's setting the rotation
just some weird behavior i found ig
your code should be ok
ok cool π sorry for the headache lmao, been tearing my hair out over what seems like something really simple
goin to bed, gn
@vale wren I would recommend you to use Quaternion.Slerp
thanks!!
never knew lol
that's neat
now i can pull a snarky refer to google or someshit
thanks google
I have just realised I don't need it, cuz I can just Debug.LogException when printing
and it gonna show calls
now I have exception every update
Why? Doesn't normal Debug.Log show stacktrace as well?
it doesn't
How so
dunno
having a bit of trouble thinking out how to actually handle this
any ideas on handling creating spaced objects rotated around an object in a circle?
visualization, equally spaced objects with a set distance from the edge of a circle, handled dynamically
what kind of proc gen are you looking for?
First normal terrain and later add things like buildings trees ands enemies
no I mean like what algorithm?
Noise?
That is very basic geometry
https://stackoverflow.com/questions/14829621/formula-to-find-points-on-the-circumference-of-a-circle-given-the-center-of-the
haven't finished algebra or geometry but thanks π
sorry if that seemed passive aggressive, had some memory issues recently and had to re-learn a lot of math, I get sensitive about it sometimes, appreciate the help

While building a game we import a lot of different packages. My question is, how does Unity build take care about it? Do we need to remove all the junk folders when the project is finished? Will it reduce the package size? Is there any good practice to follow related to this?
lmao sat here trying to solve an issue with it, my dumb ass wasn't multiplying by deg2rad
In my game there is an object which can bee either open or closed. In a level there will be one closed and one open. How should I add these object in game by making two prefabs as open and closed or are there any way that I can set them at the beginning of a level
Using a single prefab is fine, you'll have to flip some flag for each prefab object you place on the scene
and if you've any additional logic you can do it in start
are those lines the same?
yield return new WaitUntil(() => _textInfo.characterInfo[0].origin != 0);
while (_textInfo.characterInfo[0].origin == 0)
yield return null;
they should do the same, right?
because second one with while does throw more errors than lines of code in my script
and wait until works (somehow) normally
I see, damn unity forums and chatgpt lied me about that, it's
do yield return null;
while (_textInfo.characterInfo[0].origin == 0);
You'd have to check the implementation in code in order to determine if they are the same
it the same with do
basically everyone has told they're the same
The post that you highlighted?
yes
oh, no
I have just searched for that forum
anyway I think I'm enough with working with TMP_Text
it's done so badly
how can built-in class have more bugs than every beginner's script
If you look at the specified thread one user literally says that they aren't equal
620 lines of code just to overcome those bugs of built-in namespace
who?
And another reply suggests that wait untill always has a one frame delay
yes, suggests
I have mentioned it sooner
Baste, angusbjones
Baste suggests but doesn't know (and I've seen his name around the forums quite a bit) so if someone like that suggests something you should definitely dig deepers
And Angus in that thread has figured out that they weren't equal
And he was running into problems because of it
So idk how you read that thread but it's definitely in there
they haven't written that it's the same as do while
I have fixed that myself afterall. 1 bug less. 200 more to fix
That's because do while is the same as just doing
yield return null
while(!condition) yield return null
yes, but do while looks better
I disagree
also it doesn't repeat yield return null 2 times
Cognitive load in order to process a do while is significantly higher than to just look at two statements
But that's an opinion thing I guess
do yield return null;
while (!condition);
that's a guess, yeah
Not a guess, an opinion
I don't know what you are doing but this doesn't make any sense
nice.
hold on
And as you can see you haven't proven anything (the times are also not accurate)
9ms difference for such a simple operation
Wed be looking at a microsecond difference
If even that
no, I have returned but forgot it returns just once
ok, that just doesn't matter
I just think I should let my trashy game for a few years
Idk what you're doing if you're trying to measure performance difference between a simple do while and while. It probably doesn't matter at all even if there is a slight difference.
Anyways, everyone knows that while is better than do while when it comes to simple loops...
yes, in that case we have discussed earlier, while is not the same as WaitUntil
I see
apples and oranges
if you want to measure performance you just look at IL
Also true
while and do-while are not interchangable actually
you need to change the codes both inside and outside the loop to turn while to do-while or vice versa
How did you do this?
the only difference in IL is that while starts and ends with a branch and do only ends with it
rest is identical
that's !cdisc
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
hey, adjusting editor tabs make them flicker for some reason, any ideas on how to make it stop?
have disabled NVIDA for unity, but problem still remains
dunno if my graphic cards is just outdated or if a fix is available
weird, no way around it? using 2020.3.45f1
my other devices share the same version, but dont have the problem there
dont know
manifests for me some times, but in different scenario
probably something to do with vertex buffers overflowing
Unsupported
This version of Visual Studio is unable to open the following projects. The project types may not be installed or this version of Visual Studio may not support them.
For more information on enabling these project types or otherwise migrating your assets, please see the details in the "Migration Report" displayed after clicking OK.
- Assembly-CSharp, "D:\Unity_project\Cooking_mania\Assembly-CSharp.csproj"
- Assembly-CSharp-Editor, "D:\Unity_project\Cooking_mania\Assembly-CSharp-Editor.csproj"
No changes required
These projects can be opened in Visual Studio 2015, Visual Studio 2013, Visual Studio 2012, and Visual Studio 2010 SP1 without changing them.
- Cooking_mania, "D:\Unity_project\Cooking_mania\Cooking_mania.sln"
how to fix dis
Have you followed the instructions from !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
Im getting a nullreferenceexception on the Vector3 newPosition line:
//in Building.cs:
private void Start()
{
buildingManager = FindObjectOfType<BuildingManager>();
}
public void Place(string buildingName, Vector2Int position)
{
Vector3 newPosition = buildingManager.CoordinatesToWorldPosition(buildableTerrain, position); //here
...
}
There's a BuildingManager gameobject in my scene which has BuildingManager script attached to it. For some reason buildingManager is returning null, even though it doesn't return null when I test it in Start() with if (buildingManager == null) Debug.Log("null");
The Building script is attached to a prefab, which gets instantiated whenever the player left clicks. I've tried using Awake instead of Start but that returns the same result.
Full error:
Building.Place (System.String buildingName, UnityEngine.Vector2Int position) (at Assets/Scripts/Building.cs:44)
BuildingManager.PlaceBuilding (System.String buildingName, UnityEngine.Vector2Int position) (at Assets/Scripts/BuildingManager.cs:52)
BuildingSelectionBox.OnMouseDown () (at Assets/Scripts/BuildingSelectionBox.cs:34)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)```
Do you call Place() on the newly instantiated Prefab right after isntantiating it?
You should test if Start() is being called before Place() in your prefab, the docs only say that Awake() and OnEnable() are called when instantiating
@swift falcon
they are also only called if the prefab was active
if the prefab was intantiated inactive they wont be called until SetActive()
If I have a Monobehaviour script that I want to require transform children with components that I can reference, is it better to create a prefab and assign references there or to create those gameobjects inside of the main script?
Right now how I have set it up is by having 3 scripts, one for the main and 2 for children, the child ones have "requirecomponent" and methods to reference the required components, it just feels weird to have 3 monobehaviours for one purpose I guess.
I mean if its 1 purpose
then it can be 1 monobehaviour
but if those 3 monobheaviours do 3 distinct different things
or don't align in functionality at all, in such a way that you'd probably re-use them somewhere else
Then they should be 3 different ones :)
But you can always split / merge them later
like i said I tried using Awake instead of Start but it produced the same error.
when using Awake, Awake is being called before Place, which is what its supposed to do?
Welcome!
if theres a better place to put this then someone lmk :]
what is camera space?
(specifically im confused by what the cameraToWorldMatrix is actually doing)
the docs reference camera space but idk what it is and i can't find anything online about it
this is pretty complex and relates to how objects are rendered
technically afaik camera never moves, the objects are transformed by matrix mutiplication
im fine with it being abstracted away like it is in the docs, but im not sure what camera space is supposed to mean
there is view matrix, projection matrix and objects matrix
well camera space is the local space of the camera
screen space?
no
this is related to 3d coordinates
which is what matrix describes
among rotation, scale and various sqews and projections
if you explain what you want to achieve i can point right direction
im not really trying to achieve anything, im just following a paper and the mention of camera space came up
screen space/ viewport space are 2d coordinate systems, local space or camera space is a 3d concept, afaik
so is camera space just the position local to the camera's origin?
relative to camera, if you transform the object to the camera space you would get its offset from the camera
i assume, i never tinkered with it, and i learned the theory quite a while ago
List<RectTransform> transforms = new List<RectTransform>(cardDesinationsObject.GetComponentsInChildren<RectTransform>());
cardDestinations = new Vector2[transforms.Count - 1];
for (int i = transforms.Count-1; i > 0; i--)
{
transforms[i].SetParent(canvas.transform,true);
cardDestinations[i - 1] = new Vector2(transforms[i].position.x, transforms[i].position.y);
}
I'm trying to store the positions of some gameobjects in a grid layout group. This returns the same position for all gameobjects.
Would anyone be willing to help me with this issue? Both of these menus are seperate but for some reason when the copied one is walked near, the menu for the original one opens. However the original one does not open the second one. If anyone is willing to help tell me so I can show you parts of the script! https://gyazo.com/ce69dd12c1dc487e1c26680d65788740
these are for entering the collider and exiting the collider. Im unsure why they're linked in this way
{
if (other.CompareTag("Player"))
{
interactPrompt.GetComponent<interactionUI>().Dino = Currentdino;
isInteractable = true;
interactPrompt.SetActive(true);
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
isInteractable = false;
interactPrompt.SetActive(false);
}
}
How do you assign interactPrompt
Using
public GameObject interactPrompt;
both of the dinos have seperate assigned interact prompts
probably should've made a thread for it, sorry haha
why is hUnit unassigned on the 3rd line?
1 bool result = subUnit is Harvester hUnit && hUnit.Carrying < hUnit.resourceCapacity;
2 if (result)
3 command = new HarvestCommand(hUnit, target);
as I understand it, hUnit is not assigned if subUnit is not Harvester, but line 3 is only called if that is true, so why does it say it's unassigned?
You say falling should not be inside navigation voxel agent, right? like NavMeshAgent unity which does not handle falling.
I'm saying it could or it couldn't, depending on the use cases for each. There's very little "should" about programming.
Why can I not access my second script from my main script?
the value I want from my second script tells in the debug mode:
The identifier `Load_Save_MyDatasSCRIPT` is not in the scope
But why?
I also made a breakpoint on my second script and its getting a value in his integer, so I have no clue why I still can't access it from my main script?
I also made that the onclick of the button will execute the Secondscript first with the Integer: [HideInInspector] public int CurrentPressedButtonNumber = 0; ...to make sure that the value was given, before I try to call this value from my Main script:
I dont think ive seen that specific error with beeakpoints, though it looks like in your "main" class, you created a variable outside your function, and never assigned it, so technically that "myDatasScript" variable should be null - without breakpoints, do you get any errors in the Unity console at runtime?
Yes. That why I made this debug test. The variable is outside, its in the "Load_Save_MyData.cs"
But its getting the values from there and after thus script is done, it should try to access it.
Does anyone happen to know if I can enable .editorconfig analyzers to break the build on error, when building in batch-mode (cli)?
Is this a Unity Engine bug?
Cause "CurrentPressedButton Number = 1" and I just try to see it from the second script, but with zero success.
it is "1" but I cant get it, even if its public.
Do I need to unsubscribe from this? If yes, how do I? Just -= instead?
_moveAction.started += _ => _moveCoroutine = StartCoroutine(Move(_));
You can't unsubscribe from lambdas, you need a full method
Save it to variable π
can you give me an example, please?
or do I just make a method from this?
Action myAction = () => {};
myEvent += myAction;
myEvent -= myAction;
Sure making a method works too
does it need to be action?
private void Bla()
{
_moveCoroutine = StartCoroutine(Move(_));
}
is it better to do Action or method?
Not much difference
I see, thank you
should Actions be declared before methods or after?
cause fields are declared first, then methods
Action is type of your delegate
Well I dont think I have the full context of your script, though there are often 2 common ways to access variables across scripts (there are many others, but at least these 2 are most common) - either by a direct reference, usually assigned in the inspector:
public class A : Mono
{
public int variable;
}
public class B : Mono
{
public A aRef;
void SomeFunc() {Debug.Log(aRef.variable);}
}
Or through the class directly, as a static reference, which cannot be assigned through the inspector:
public class A : Mono
{
public static int variable;
}
public class B : Mono
{
void SomeFunc() {Debug.Log(A.variable);}
}
What you have, looks like you made "aRef" but you never actually assigned it, but your watching the "variable" from A, not from a reference in B (if I am reading your watch list correctly)
Action is the type, so depends on if you make it a field or property. So, along your other fields is fine
I see, thank you
why I cannot use non-static fields, methods or properties with Action?
You're getting an error message aren't you?
yes, I am
Something static cannot reference something that's not static
It's not restricted to fields of type Action, all members follow this rule
Is the Start method immediately called after enabling an object for the first time, so that the main thread works like this?
public class SomeClass : MonoBehaviour
{
[SerializeField] private OtherMonoBehaviour _other;
void Start()
{
_other.enabled = true;
// Now _other performs start operation
// Do something
}
}
I don't make my Action static, is it static by default?
then why?
private Action<InputAction.CallbackContext> bla = _ =>
{
_moveCoroutine = StartCoroutine(Move(_));
};
Ah, yeah it's almost the same thing as the static/instance error. A field cannot reference another field in its initializer (after =). You access moveCoroutine in it, which is probs a field
Because you are defining it with field initializer
so should I make a method instead?
Do you even can use the Scripts directly without making a variable of it?
Load_Save_MyDatas Load_Save_MyDatasSCRIPT;
public void _Start_A_New_Game_OnThisSaveSlot()
{
ButtonAudio_shortcut();
SaveSlotButton_Redbar[Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber].SetActive(true);
print("TTTTTest = " + Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber);
StartCoroutine("VerzoegertesAusfuehren");
}
Declare it only, and assign it in Awake
public class Gyro_script : MonoBehaviour
{
Vector3 rot;
void Start()
{
rot = Vector3.zero;
Input.gyro.enabled = true;
}
void Update()
{
rot.y =- Input.gyro.rotationRateUnbiased.y;
Debug.Log(Input.gyro.attitude);
transform.Rotate(rot);
}
}
Is it possible to use gyro for positioning an object, If so Does anyone know how I can take this gyro script and make it position instead of rotation? (IOS if that matters) I tried to edit the script but it just didnt work and this is the original one
Is there a way to predefine how rooms made in tilemap looks and then randomly spawn them on map?
I see, it works, thank you. Is it still better to use method or not?
This restriction is in place so the compiler doesn't have to determine which field requires another to be set, before it's set itself, avoiding potential infinite loops (a field references another, which references the first field)
=- π
public class Load_Save_MyDatas : MonoBehaviour
{
[SerializeField] private string[] SAVEorLOAD_Slot_Filename_string;
[HideInInspector] public int CurrentPressedButtonNumber = 0;
// Button[1] vvv \\\\\\\\\\\\\\\\\\\\\\\\\\\
public void MyData_SAVEorLOAD_Slot1_pressed()
{
CurrentPressedButtonNumber = 1;
}
}
public class PressSavingSlot_AndStartNewScene : MonoBehaviour
{
[SerializeField] private AudioClip audioclip_LightPressingSound;
[SerializeField] private AudioSource audio_ButtonVolume;
[SerializeField] private GameObject[] SaveSlotButton_Redbar;
private void ButtonAudio_shortcut()
{
if (!audio_ButtonVolume.isPlaying)
{
audio_ButtonVolume.clip = audioclip_LightPressingSound;
audio_ButtonVolume.Play();
}
}
///////////////////////////////////////////////////
Load_Save_MyDatas Load_Save_MyDatasSCRIPT;
public void _Start_A_New_Game_OnThisSaveSlot()
{ //Audio Button Sound - Pruefen, Audioclip-laden UND abspielen:
ButtonAudio_shortcut();
SaveSlotButton_Redbar[Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber].SetActive(true);
print("TTTTTest = " + Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber);
StartCoroutine("VerzoegertesAusfuehren");
}
private IEnumerator VerzoegertesAusfuehren()
{
yield return new WaitForSecondsRealtime(1f);
SceneManager.LoadScene(2); // 2 = World Scene
}
}
- I'm not sure why the colors don't work, but the lower script here is that script what needs to access "Load_Save_MyDatas", for his "CurrentPressedButtonNumber" integer...
oops
configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
was the =- stupid?
how would i program a car building game mechanic like the game my summer car or mon bazou?
Its underlying errors, I configured it 6 moths ago or has there been something new I need to do
it should have underlined =-
More like it should format your code properly
oh, yeah, it shouldn't throw compile error
narrow down the question
So you have Load_Save_MyDatas Load_Save_MyDatasSCRIPT;
This just declares a variable of type Load_Save_MyDatas, but because theres no = and because its not public, the value of Load_Save_MyDatasSCRIPT is null until you set it to something - you then use it SaveSlotButton_Redbar[Load_Save_MyDatasSCRIPT.CurrentPressedButtonNumber], I would imagine this would cause a "Null Reference Exception" cause Load_Save_MyDatasSCRIPT is null, meaning you cant access .CurrentPressedButtonNumber, is this whats happening in the Unity console for you?
but why? without the - it rotates the opposite way of the phone
yes, you're right, I have already said before that it shouldn't. As SPR2 has mentioned, =- foo is just = -foo. I haven't thought about it.
I mean you want -= not =- right?
im new too sort of building proper ai for unity3d everytime i build zombie hordes or smthing like that they end up pushing the player and each other no matter what obstacle avoidance i have them set too?
When I do -= the cube just constantly spins
no
sorru
I must have bumped phone
Its doing this even when I just lay phone down
so is =- Okay?
dont use that either
you dont have a clear understanding of what they are doing
so dont use them
int foo = 1;
foo = foo + 2;
use this syntax
#π±οΈβinput-system
also that's not a link to your code
nice, I gonna paste it there, thx
how can i detect if the player collides with only the up facing part of the ramp?
cause currently they can do some weird wallclimbing abilities on the sides of ramps
.
turning it into a:
[SerializeField] private Load_Save_MyDatas Load_Save_MyDatasSCRIPT;
``` solved the problem, thanks.
You could look into "flock AI" as well as "obstacle avoidance", it sounds like your wanting a similar system, to prevent pushing the player, you can either disable the collision interaction between them, or make sure each AI maintains a minimal distance from the player so they never actually get close enough to physically interact with the player, some AI might also use a "target priority" (donno if thats the correct technical term), basically if that priority limit is say 5, and you have 7 AI trying to attack the player, the other 2 will simply justt sit around and maybe look at the player but wont attempt to move toward it, until one of the 5 units leave or dies, allowing them to take one of the priority slots, this makes it so the player realistically is only fighting 5 AI circling them at a time
Is there anything I can do for a top down 2d game to where I don't have to fight with the coordinate system as to what vectors are considered forward and up?
"forward" is currently Vector.right (all of my sprites point upwards), and the 270/-90 angle offsets are annoying to have to keep track of.
If I left the coordinate system alone I could rotate all of my sprites before importing, or make a custom importer to rotate them on import...
Try putting an intermediate "system" between it all, that does the conversion for you. That way you can import your sprites normally, but when your various classes go to work out what's up and down they just consult that one helper class.
Or a static class or singleton that converts it all. I have one for my map screen that converts "game" directions to world transform coordinates and vice versa. Since the map screen uses tilted non-iso sprites
"Since the map screen uses tilted non-iso sprites" That's an interesting look
Thanks. Unity's Grid component unfortumately won't do this for you, so I had to just brute force it
Couldn't this effect be done just by modifying the view angle of the camera? I'm guessing the problem there is it won't be pixel perfect.
Yeah, pixel perfect look is lost when camera tilting, and movement causes jittering and shifting of the sprites.
Does anyone know a way to detect a collision from a child separate from the parent without writing a new script for the child? I know that the parent can detect the collision from the child but I want different things to happen when the child or parent collides with a specific gameobject. I tried some stuff with thisCollider but that for OnCollisionEnter and not OnTriggerEnter.
If I remember correctly, as long as the rigidbody is on the parent, and there are colliders on the children, they'll all be part of a single collider, and all collision events will be bubbled up to the rigidbody.
So you could have one script on the parent, as long as it's along the rigidbody.
Yes I know but I want different things to happen when the parent collides with a gameobject or the child does
The only solution I know is an extra script for the child
You need one script per child object. Or a giant chain of if-statements that switch on collision.thisCollider to know what's the collider on this object that was involved in the collision
Hmm I see. I wish I could just give the collider I want as the parameter 
Why is my Text color always yellow, if I enter the color code of green?
and why does the color work, if I use "color.green" instead of the color value?
Color takes values ranged from 0 to 1, float
Use Color32 if you need to use bytes
(they convert to each other seamlessly)
what do you mean? I just wonder why I always get yellow if I enter the code of green?
It can't be the fault of my code or a wrong setting, cause "Color.green;" is working perfectly fine.
I mean new Color(255, 0, 0) is incorrect
It should be new Color(1, 0, 0)
You're just passing a very powerful green (HDR color), but you're not seeing it
why 3 ? I have 4 numbers in it.
4 = Alpha
alpha is 255 what means its completly visible.
Color and Color32 are different
I did not used Color32. I got this codeline from the Unity forum:
https://forum.unity.com/threads/changing-color-of-textmeshpro-in-code.949434/
It's just wrong
It should either be Color32 here, or use values ranging from 0 to 1
This is equivalent to Color(1, 1, 1, 1);
Yeah, that's fully white, and if you have HDR enabled you just flashbanged yourself
(passing values greater than 1 I mean)
^ either use Color32 to use a range of numbers between 0 to 255, or divide all your numbers by 255f to remap them to a range between 0 and 1
255 is the highest number
Actually, in that forum post, the very next answer points out the mistake - always read further
We're talkning about code here, not the Inspector
The Inspector probably uses a Color32 behind, or a Color that gets remapped in the back
but I try to get that color values and its the same like in the inspector or every other Drawing Software (16, 255, 0, 255) = green
My dude
You're not getting it
Each color component is a floating point value with a range from 0 to 1.
If you don't want to make the math yourself, to remap the 0-255 values of the color picker to 0-1 range, then use Color32 as per the post: https://forum.unity.com/threads/changing-color-of-textmeshpro-in-code.949434/#post-6875666
It's the thread you linked, but scrolled further down
now I see it.
but why was it yellow?
Because you passed very high values that are invalid for a color that's not a HDR one
It's not always yellow when invalid though, it might be because some numbers are higher than others, it takes a specific tint that tends to go towards some color
If I have a script with a reference to a component, and I want to represent a variable of the component as a local variable that updates the component when the value is changed. Is it better to have an accessor to the component field or should I have some method to synchronize the component and the local value?
I'd obtain the face normal with a raycast and use a cross (or was it dot? I forgot) function to compare with Vector3.up
Dot
Is it possible to have AnimatorController modify variables of a MonoBehavior? Specifically, after a chain of animations have played out, I want to set Busy = false on the MonoBehavior
Would anyone experienced with 2d game dev and procedural generation be interested in hopping on a quick call or chat? I have a few questions about approaches for level generation for my hobby project.
or some varient of that where I can have my monobehavior check in "yo did you finish yet, AnimatorController?"
Id heavily recommend checking out vids on Wave Function Collapse
AnimationEvent
I thought those are fired off by the Animation, not the AnimatorController
Yeah wave function collapse seems good, but i dont know if it works for a 2d platformer
it works for anything and everything
its a very generic algo that largely can be used to do a lot of stuff, and solve a lot of stuff
would you recommend applying it to a tilemap, or instantiate prefabs of all tiles
well yeah, but the AnimatorController does not do anything other than control the animations
right I cant do it with an Animation, because I re-use them and sometimes I do animations A-B-C, sometimes I do A-B, so if B has an animation event of "NotBusyAnymore", then it will fire incorrect for A-B-C
So was hoping I could do it with AnimatorController as that actually delegates under what conditions a given animation is the last in the chain
I suppose I could make a generic 1 frame animation that is the "not busy anymore" animation, which I staple to the end of both chains, so I could have
A-B-Z, or A-B-C-Z, and Z has the event π€
it's unlikely that there is any functionality for the AnimatorController itself to do anything to a MonoBehaviour or anything like that. you can always ask in #πβanimation if you want help with something like that though
but before I do something hacky like that, this seems like something unity outta have support for
You might be interested in: https://docs.unity3d.com/Manual/StateMachineBehaviours.html
is codecademy.com good for learning C Sharp?
As suggested, wave collapse is pretty well documented for level generation. If you want a more in depth comprehension, I suggest that you read also on backtrack algorithm which the WaveCollapse is derived from.
I would suggest that you follow a course that is axed on Unity and C#.
C# is very broad and you will learn more than what is necessary by doing a standard course while also not learning everything that you need.
I strongly suggest that you use Tilemap.
That is true. Either way, it's not for me as I already use C# in my projects. Just wanted other people's opinions.
Thanks, ill look into wave function collapse combined with tilemaps. Any recommended tutorial or material to learn and implement WFC? Right now im looking at a tutorial by sunny valley studios but it seems pretty outdated.
I would suggest that you look into !learn if there is a course appropriate for the person you support.
π§βπ« Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
The fundamental will not change with time. You might have to adapt a bit to make it work with a newer version of Unity though.
ah perfect that looks like what I need, and Im guessing I can work my way up the tree to access the gameobject?
You have a reference to the Animator.
Right, but if you have any source in mind id still love to hear about them, as i want to learn not simply by following a single tutorial.
Oh actually, does GetComponent work by chance with polymorphism?
If reading article is not something you hate, you might be interested in: https://www.boristhebrave.com/2020/04/13/wave-function-collapse-explained/
Like I have abstract class EntityBase, and then the actual MonoBehavior on my GameObject is BatEntity, and then the GameObject also has an Animator on it, which has lets say DoTheThingSMB StateMachineBehavior script on a cell
Is it possible for me to GetComponent<EntityBase> so I can have 1 single StateMachineBehaviour script that will be compatible with all my various Entity scripts I make?
It sure can.
noice
Yes, it'll get any derived class that's on there. Also works with interfaces!
thank god, thatll make this a lot easier
I presume theres an event I can hook into for StateMachineBehavior that will just fire off once on finish or like, on transition out? Lets see here
You would need to define it yourself.
The StateMachineBehavior works pretty much the same as a standard MonoBehavior.
Looks like OnStateExit is what I want
Oh, you mean event in that sense.
yeah unity's weird pseudo magic string name "events" they like to use
I though you were looking for a way to subscribe directly to the StateMachineBehavior OnExit/OnEnter.
oh wait, these ones are actual override methods
I guess they didnt want to make the same mistake then previously.
yeah haha
Pretty awkward how the MonoBehavior works.
Does unity support INotifyPropertyChanged in some way? Specifically, is there a way to bind property of <component> to a variable of <MonoBehavior>?
I have my GameState object which I can have as a singleton or monobehavior or whatever, and Id like to ideally not need to write a buncha code that just handles writing GameState.SomeProperty <-> UIElement.Property, for dozens of properties
I do not think this is something that is usually done.
You want to do MVVM ?
effectively, or anything approaching it where you can just be like "Yo, bind Component.SomeString to MyScript.SomeString"
Unity does not really have the notion of binding integreated in it's Engine.
dang
I guess UITool kit may have it now though.
Not ready to be use for Runtime interface yet.
Also, I suggest that you use other approach then MVVM and data binding.
Not that suitable for VideoGame interface as they are most of the time unidirectionnel.
You just add a layer of complexity that is unneccessary.
I have a gameManager which has a method thats called SwitchState(GameState newState). The newState argument is a public enum that is in the GameManager class. I also have a button. In the inspector when i try to set the onClick event to switch the state of the game, the SwitchState(GameState newState) doesnt show up when I put GameManager gameObject into onClick thing. Does unity just not allow enums and structs as arguments for serialized events?
UnityEvent Serialization is limited. If you want to increase the capability use 3rd party library or implement your own with Custom Editor.
However, you should sparely use event in such a way.
Im making a tiny project
They are hard to follow because they do not appear in most IDE reference tool.
In what way? Serialized?
Isnt it part of the button component?
You can also circumvent the issue by specifically define your event.
I've tried it, but to no success
SwitchStateToStateValue;
Where would I put that?
There is also the option of creating a UnityObject that handles the data.
Exactly at the same place.
If you use proper formatted code I can rearrage your code to show you
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
What should i send, the GameManager script?
So yeah
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class GameManager : MonoBehaviour
{
#region Singleton
public static GameManager instance;
private void Awake()
{
if(instance == null) instance = this;
}
#endregion
public static event Action<GameState> OnGameStateSwitched;
public static event Action<GameState> PreGameStateSwitched;
[HideInInspector] public GameState State;
private void Start()
{
SwitchState(GameState.GameOver);
}
public void SwitchState(GameState newState)
{
PreGameStateSwitched?.Invoke(newState);
State = newState;
switch(newState)
{
case GameState.GameOver:
HandleGameOverState();
break;
case GameState.InGame:
HandleInGameState();
break;
default:
throw new ArgumentOutOfRangeException(nameof(newState), newState, null);
}
OnGameStateSwitched?.Invoke(newState);
}
private void HandleInGameState()
{
//Mb add later
}
private void HandleGameOverState()
{
//Mb add later
}
}
[Serializable] public enum GameState
{
GameOver,
InGame
}
public void SwitchStateToGameOver()
{
SwitchState(GameState.GameOver);
}
public void SwitchStateToInGame()
{
SwitchState(GameState.InGame);
}
public void SwitchState(GameState newState)
{
PreGameStateSwitched?.Invoke(newState);
State = newState;
switch(newState)
{
case GameState.GameOver:
HandleGameOverState();
break;
case GameState.InGame:
HandleInGameState();
break;
default:
throw new ArgumentOutOfRangeException(nameof(newState), newState, null);
}
OnGameStateSwitched?.Invoke(newState);
}
Oh~
An alternative is to create a "SwitcherStateHandleComponent" which can then be use to switch the state.
public class SwitchStateHandler : MonoBehavior {
[SerializeField] private GameState switchTo;
public void Switch(){
GameStateManager.Switch(switchTo);
}
}
In my case it would be SwitchState() right?
Yes
Also, how would this resolve my original problem?
And you would need to either make the GameManage as a Singleton, retreive the Manager through reference or use static reference.
You will be able to serialize the data.
So instead of using the GameManager -> SwitchState(GameState state) you would be using SwitchStateHandler -> Switch() which should be serializable.
This is already done
But now, would i need to switch the value of switchTo via another script?
Cause all im trying to do is;
- Press button
- Switch to state
I mean, you wanted to define an event that was serializing the game state ?
If this is what you want to do you should create a script to manage the state of the currently selected GameState.
So, i put this handler on the button, set the target gamestate, and then call switch in the onClicked event, right?
Yeah.
Hold on
Thank you so much
This has been tormenting me for like 5 days now. Thank you
What is the best place to ask a question about Visual Code Studio? I'm not new to game dev, have been using GameMaker for several years, but recently decided to learn Unity. I have set up everything and even watched videos online, but cannot seem to get Intellisense or Code completion working on Visual Code Studio.
I have VS Code as the default editor in Unity and have these extensions installed following different guides
Like when I type transform.Rotate, then there is no autocompletion with transform
The #854851968446365696 should be able to help you get your IDE setup, though I would personally suggest using Visual Studio Community for coding if you can, it has many useful debug features
Good question, maybe this: https://visualstudio.microsoft.com/vs/mac/
Hmm let me see the VS Code guide here, I'm used to VS Code and it's better for me since it's universal and works on all systems and not just for C# but other languages too
For sure, if VSCode works for you, and the guides help you fix it, then thats fine, if you did want to try Visual Studio Community, you at least know where you could find it
Yea thanks. It's weird that my VS Code is not doing code completion when I followed the exact same steps in the tutorial videos.
Maybe you missed a step? Have you also restarted VSCode, and set it as the "Exertnal Tool" to open scripts in Unity?
Anyone here familiar with Zenject? Its proving to be a pain figuring out how I get dependencies injected into a MonoBehavior that is already placed on my scene, is this straight up not possible and instead I need to instantiate it through zenject from the start, via a prefab or something?
If you have a SceneContext, it will inject into everything in the scene at startup.
found out what was going on, I had an error thrown inside of InstallBindings() and it was getting lost in the pile of other errors throwing due to the injection failing
Did you close out of Unity and VSCode completely, then open unity and double-click on a script to auto-open in VSCode?
Just take note that Unity stopped full support, and the Unity debugger for VSCode doesn't work anymore . . .
Hello i have a question, i have a wall made out of legos in my game and i want to make it so the player can blow up the wall and when they do the wall object gets destroyed but a bunch of lego blocks go flying from the explosion. i am just having trouble figuring out how to do that
Hello. Why would this first struct work in moving the unit, but this second one would not work in moving the unit? The problem seems to be in MoveCommand on the second one, it's time float never increases, I believe its being set to Time.deltaTime instead of increasing, but only in the second struct?
HarvestCommand: https://hastebin.com/share/abezuluhul.csharp (working)
ReturnCommand: https://hastebin.com/share/hivunegego.csharp (not working)
MoveCommand: https://hastebin.com/share/mafejivivu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I also know it has its start and end points set correctly.
Also, the Progress() method is called in Update() for HarvestCommand and ReturnCommand.
at first I thought it was for some reason creating a bunch of ReturnCommands or MoveCommands for some unknown reason, but that does not seem to be the case.
Okay, i found out what's causing the weird behavior but I'm not sure why. HarvestCommand has moveCommand as ICommand, but ReturnCommand had moveCommand as MoveCommand. Changing it to ICommand fixes it. But why would having its type as MoveCommand cause MoveCommand.time to not be able to be updated/saved/set?
Welp, I got my whole round system working, but its sort of made my characters movement across tiles pretty clunky, as each round causes a small hiccup in movement as the next movement is queued up.
I think I need to tweak the way I handle rounds to instead pre-calc literally everything that is going to happen for the queued up n rounds, and then issue all the actions in an array
Because MoveCommand is a struct, which is a value type, while ICommand is an interface, which is a reference type.
In your case, ReturnCommand had a copy of the MoveCommand, not a reference to it.
but wouldnt it still call that method on the copy of it?
It should but I can't tell from your code
It's a bit weird to mark the field as readonly but you modify its members anyway.
yeah, that defeats the purpose . . .
I would even say the commands should be classes instead of structs but idk what your codebase looks like
this is totally a cinemachine question but a coding one too but if im switching between 2 cinemachine virtual cameras, how do i keep the mouse position the whole time. Im trying to get the character to switch forms and the two cameras are different but when i switch it just returns to that old cameras position not the current mouse posiition
Want some opinions on this route I'm going for with stat modifiers. I have a weapon prefab with a scriptable object asset attached to it for it's base stats, and another asset for modifiers (or multiple assets.. depending..) . When the object awakes I instantiate an instance of the base stats so I have a copy just for this object. I then do whatever math between the original base stats and the modifiers, and apply those stats to the copy. All methods and such for the weapon reference the copy I just modified. Since they are all assets based off of the same scriptable object, I can just use some operands to add or multiply the base values with the modifiers..... thoughts?
you could instead give the camera you want to be using a higher priority instead of disabling the other camera so that they are both active and still responding to input. then just swap their priorities when you swap back. of course you'll probably get a better answer if you ask in #π₯βcinemachine instead
awesome that's a good idea, also there's the question in cinemachine before coming here just nobody really uses that chat often
crossposting is against server rules #πβcode-of-conduct
ope my b
Do you mean doing something like runtimeStats = baseStats + modifierStats? Because you'd want to overload the math operators for the ScriptableObject to achieve that.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading
Yep, basically like that
My question was more on the scriptable object shenanigans I was doing
Oh then I personally treat ScriptableObjects as immutable objects. So I avoid making a copy of it and modifying its value at runtime
I would make a Runtime class counterpart to the stats ScriptableObject
but then the operator overload won't work
It can still work
// BaseStats is the scriptable object
public static RuntimeStats operator+ (RuntimeStats a, BaseStats b)
{
var result = new RuntimeStats();
result.Attack = a.Attack + b.BaseAttack;
result.Health = a.Health + b.BaseHealth;
return result;
}
yeah I would have to write a seperate operator overload
and it means I would need to make sure both overloads (runtime + so) and (so + so) are updated
There are many ways to fix that (such as using interfaces) but it's not a hard rule. Use scriptable objects however you wish.
wait.. if I have both the SO and the runtime class off the same interface, I can make the same operator work for both?
How can i make vscode suggest code?
suggest code?
!vscode
thx!
I currently have code that moves a 3D object with a mouse click and drag. Can anyone help me with code that will restrict the movement in the Y-Axis?
Vector3 mousePosition;
private Vector3 GetMousePos()
{
return Camera.main.WorldToScreenPoint(transform.position);
}
private void OnMouseDown()
{
mousePosition = Input.mousePosition - GetMousePos();
}
private void OnMouseDrag()
{
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition - mousePosition);
}
You can't overload operator with interface types so that won't work, though you can instead use method
.NET 7 when 
@leaden solstice ahh.. bummer
In the code provided, when dir is (1, 0, 0), it returns (1, 1, 0), not (1, 0, 0)
Vector3 dir = callback.ReadValue<Vector2>();
dir.x = Mathf.Sign(dir.x);
dir.y = Mathf.Sign(dir.y);
Mathf.Sign gives 1 for positive numbers and zero
shouldn't it give 0 for 0?
Which is different from the actual c# math class
