#archived-code-general
1 messages · Page 323 of 1
Okay, I'm using a playerController that's based around Quake movement
I'm opening my visual studio right now but here's a snippet of how I'm creating the death floor in a sense
This is really vague. Player controller is just what you named the variable or type.
please be patient with me, I'm trying to open my visual studio right now
Actually, It's generated based on a csproj file, the one called... I forgot, it contained a list of all my scripts for compilation
I've put it into Scripts/MessagePack/Resolvers
Guys does anyone have an idea how a file might become completely isolated from the rest of the project? I don't have access to any of my scripts in global nor custom namespace in that file
The context I'm in is the GeneratedResolver.cs made by mpc, it's currently in Assets/Scripts/MessagePack/Resolvers and appears to not have access to any of my structs
access modifiers?
Uh, I'm not quite sure what you mean with that...
If you're talking about public/protected/private etc... no, I'm just simply blocked from any of my own scripts, I can still access UnityEngine, UnityEditor, System etc, but no, none of my own.
Blocked as in, my intellisense don't find their existence, and Unity also log errors saying that they don't exist
I've tried giving some a custom namespace too, it worked as much as keeping them global- not.
Do the errors only show up in the generated resolvers, or any script in that folder? Try creating your own script in that folder and try to access something in the project and see if that raises an error.
Only in the generated resolver
What's not found?
Strangely they never specified where I'm meant to put the resolver tho...
So I put it in the package's folder
It doesn't matter where you put it as long as it's discovered by Unity.
SavedObject struct and StructureData struct
Are those your own structs?
The generated script includes it, but it throws errors cus can't be found, while I'm using those all throughout my project
Yes
Can you show the generated code?
Sec...
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.
Have fun 😊
Jk Idk if you can make any sense of this, either way the error marks all occurrences of global::SavedObject and global::StructureData as can't be found
And I tried using, where it became clear that all my own stuff are inaccessible
I think you posted the wrong thing
It is indeed the file generated by mpc and the one where the errors occurs
there are no references to global::SavedObject and global::StructureData in it and the vast majority of it is just commented out
Ah, I forgot that I commented the vast majority out when I wanted to wipe some errors to confirm some stuff
And I do clearly see occurrences of global:SavedObject and global:StructureData in there
Line 53, 72
Are your SavedObject and StructureData in the global namespace, or are they in your own namespace?
115
Initially global, I tried sorting some stuff to my own namespace during the error
I'm sure that global or my own namespace, none are visible in intellisense
Yeah that's probably the issue, global::SavedObject looks for it in the global namespace, so if you moved them to your own namespace like MyGame.SavedObject then that won't be found.
No, the issue existed before already...
And like I insisted all this time, I know that I simply can't access them no matter the namespace...
I've been trying to solve it for hours on end earlier today
What namespace is your SavedObject now?
ALS.Base, but trust me, I can't access it either
Can you try putting _ = typeof(ALS.Base.SavedObject); in one of the method's code and see if that raises an error?
I heard about something called Assembly definition... Thought that they do compile certain things independently from all the rest, so I've been wondering if I wound myself up in the package's assembly definition
I can't test it anymore for today, but I can say with confidence that my intellisense wouldn't show ALS.Base.SavedObject up, and it's gonna throw a type or namespace cannot be found exception
Even using ALS.Base; is invalid, I've got access to everything except from those
Whelp, pointless for today since I can't test anymore, cya tomorrow guys
Gotcha! I was allowed to test despite it being late and stuff... I'm dying to know what I wasted my day on, guess what?
Both of my thoughts were true! There is an assembly definition asset in the folder, and moving it out of the folder does clear the errors... That was a real dumb waste of time for me
why can I not do this (error can't implicitly convert UISystemBase to T), while when dropping the "where" part, it works?
alternatively, since an "explicit conversion exists" apparently, how do I do that?
oh wait, I figured it out, had to do return (T)result; instead of return result;
next time post the full relevant code
I thought that was all relevant code, my bad, I misread the line that caused the error message
all good
I have a method within my ParticleManager called ShowParticles() but it's not showing up here within my OnAttack invoke. What's the scope needed for this to show up?
it must be a public method
I added an overloaded method and it worked. Something with the number of arguments I think.
I have something like this:
public void RegisterForUIEvent<T>(Action<UISystemBase, bool> toRegister) where T : UISystemBase
{
if (_uiSystems.TryGetValue(typeof(T), out var result))
{
result.OnOpenClose += toRegister;
}
}
and in UISystemBase I have:
public event Action<UISystemBase, bool> OnOpenClose;
But I can't figure out how to instead be able to put
public event Action<T, bool> OnOpenClose where T : UISystemBase;
I hope it's clear enough what I'm going for here?
oh, maybe this'll help make it clearer:
public void Start()
{
UISystemManager.Instance.RegisterForUIEvent<UIInventorySystem>(OnInventoryOpened);
}
public void OnInventoryOpened(UISystemBase uiSystem, bool wasOpened)
{
}
I'm trying to be able to recieve <UIInventorySystem> in OnInventoryOpened, instead of UISystemBase
If toRegister was also generic it would work fine, presuming result is casted to the same generic set up
I can't put T in public event Action<UISystemBase, bool> OnOpenClose;
because it's not recognised
type or namespace T wasn't found
The whole class needs to be generic to use generic fields or properties
the class is a base class for said T
so I was hoping I could do something like that
why* is your method of type T and non of your params are T
my point is to pass an object of type T, instead of an object that is the base of T
but I guess this is too complicated I'll just cast it in the final method
I don't know what that means. If you need to use a generic argument in a field then you need to make the class itself generic, and then its members can use that argument (and it doesn't need to be redefined in the methods too)
I think you probably want some type of generic wrapper
I guess it wouldn't work anyway, now that I think about it
I wanted to:
in class UISystemBase, have an event Action<T>
and in each child class that dervies from UISystemBase (for example childClass1) , it would be Action<childClass1>
making a generic out of it would be way too much hassle because I just wanted to spare myself some typing in the methods at the end of the event chain, so that's pointless
... Why? That sounds like a job that polymorphism/inheritance already handles
...I might be overcomplicating the thing I'm working on
but I don't think just inheritance would work in my case
doesn't matter anyway
usually my train of thought -> I need inheritance -> I need generics -> I should just compare
I usually start programming some generic thing, hit a level of complexity I find stupid and then back off to re-evaluate my life
Sound like you want this?
- public void RegisterForUIEvent<T>(Action<UISystemBase, bool> toRegister) where T : UISystemBase
+ public void RegisterForUIEvent<T>(Action<T, bool> toRegister) where T : UISystemBase
No, because 👆
Ah.
Is there something like the step function but for more than just 0 or 1? Like something that would round to 0, 0.5, and 1? (or whatever I set the inputs to?) Or is that something I would have to do myself?
anyone good with ai behaviour trees?
i want to know how are sequence nodes supposed to work
thanks!
Yo ! In my game I have different type of weapons and attacks. Depending on what I'm doing and using, different animations will play. In all of this animations I have to do things, activate/deactivate hitbox, allow/prevent player from doing certain things, etc... My first choice to do that was to do it using Animation Event. The problem is that it's really painful to do it that way, I have to put so many events on so many animations, and I have to create specific functions that only serve a purpose for on thing that will be used by the event, and it just take so many time for no reason. Is there any other thing that can help me get the same result but with a more modular and scalable system ? I hope the question is clear, thanks !
I'm stumped, what's the play here? Upgraded my project from 2023 beta to unity 6. Which should I pick, and how? Picking either didn't really persist it and nothing changed.
activate/deactivate hitbox
Just add an ID to each enemy hit with current attacks if you're not using physics
allow/prevent player from doing certain things,
PlayerState.Attacking
Maybe I miss wrote something. I want to do things on specific frames, for example frame 10 I want to allow my player to rotate, that's why I'm using animations events, but there is the problems that I said in my first message
In that case, sounds like what you're using is probably the prefered tool for this honestly
R.I.P
probably some variation on how to group the animations/triggers and reuse them, but you probably do want to use the animator
I will look into this a bit more then, thanks for the direction !
Guys I don't really know where to ask but are these good performances for my project? From seeing this it runs approx 200 FPS , is this considered good?
@opaque forge Depending on how much of your game you have done, it's looking pretty good. The EditorLoop will not actually be a part of the game on release, so you'll be looking at a much higher framerate.
I'm stumped, what's the play here?
Thanks
Why can I not click buttons in child canvases? I have one main canvas in which everything works, but in canvases that are childobjects to main canvas, it doesn't
You may have another graphic that's blocking the buttons (even if it doesn't look like that's happening)
For example...
- Canvas
- Button (Blocked)
- Text
the Text might cover a very large area
(much larger than the actual text you can see)
After removing the child canvas component, everything works though
the second canvas is the issue
ah, I see
and I'm careful to deselect raycast target when it's not neccessary
you could check by watching the inspector for the Event System object
to make sure the graphic raycast isn't hitting something weird
Is GetHashCode a good way to convert Strings into IDs for items, if I want items to have unique IDs based on their name?
Sounds fragile, just make an ID once and always use it. If you suddenly want to change the name, you have an issue
Is there a package/util that let's me conditionally render variables in the editor? i'm trying to make a complex script with a lot of moving parts and having every value rendered constantly (even if not needed) is annoying
NaughtyAttributes
Or write your own
Also only serialized variables are shown in the inspector
Most of the time if you don't want it showing in the editor you just shouldn't be serializing it
Most conditional stuff I showIf is pretty much what the particle system does
the choice of fields to use depending if you want constant or random range values is something I use a bunch
unity editor support never ever
ok so i just downloaded naughtyAttributes and it seems pretty cool, but i can't get it to work.
This is my setup
// stage type enum
public enum StageType
{
moveObject,
waitForTime,
setLerpRate
}
// animation stage class
[System.Serializable]
public class AnimationStage
{
public StageType stageType;
[ShowIf("stageType", StageType.moveObject)]
public TransformData moveData;
[ShowIf("stageType", StageType.waitForTime)]
public float waitTime;
[ShowIf("stageType", StageType.setLerpRate)]
public float lerpRate;
}
//main monobehaviour
public class ObjectAnimator : MonoBehaviour
{
public List<AnimationStage> positionalData;
}
No matter what, every option is rendered. Is it to do with how i'm making the AnimationStage class Serializable? i'm not sure how to get it to render as a list in the unity editor otherwise
also i just tested it, it works if i define 2 variables in the main monobehaviour
Do you actually have a stageType variable?
Oh nvm
I'm blind
Lmao
Oh yeah it works now
Thankies :3
I've added some robust bits to it, in response to your critique. Now, there's a dedicated "String ID", so I can easily read it, but that ID is converted into a hash, and if no String ID is provided, it uses the name of the item instead, and registers a Debug.Log error. So now the name of the item can be different from the ID String of the item, and I don't need to worry about accidentally using the same ID number for multiple items, because it will correctly log errors if that occurs.
Also, this only occurrs in Editor/On Enable, so it doesn't have much overhead.
Hey I'm having some troubles Combining animations through Layers. Is there anyone who could help me?
Right now I'm trying to create the classic blend between Run and Shooting animatios, but for some reason I'm not noticing yet, the character animations star doing strange things like this
How do you have your animator layers set up?
Also, this is not the appropriate channel
Hi, I was wondering where do I go for help, as I'm trying to create a death floor, which works but it appears im clipping through objects on spawn
-Attempted elevating the characters/player
-Considered setting the movement speed to 0 but not sure how to call to another file/class
-changed the distance to reach the death floor
Using Scripts to create the deathfloor/checkpoint based system
When I respawn it's as if the colliders to the objects in my project suddenly turn off so I phase through them constantly falling to the death floor
Respawn? How do you respawn?
the top two pictures show how I respawn
In update
that's how I teleport back to spawn
it uses a checkpoint system too
When I respawn it's as if the colliders to the objects in my project suddenly turn off
- Do they actually turn off?
That's a good question, I don't believe so I'd have to double check that
i think its my playercontroller as my speed increases therefore I clip through objects or something like that
Do you have any errors?
no, I don't which is confusing me more
Does the collider of your object go lower than the pivot point of the object?
Alright, could you answer the question about the colliders turning off? Check out in the Inspector whether they actually are
@hasty canopy I was thinking that, so I elevated the initial spawn point of my character to test if it is the pivot point and I don't believe so
I'll load up my Unity now, it'll take me a minute
I'll get a video of it too so you can see more in depth what's going on
Right, consider also showing the colliders that are clipping
guys can someone help about thıs
ı deleted thıs sprite's ın scrıpt but stıll stayıng there
how can ı just turn on or off thıs thıng
Did you save the script?
ı want when ı change somethıng ın code or unıty That changes fast How can ı
do you mean you've deleted the variables? if that is the case you need to make sure to save and that you have no compile errors
yes
ı already saved
if only there were more than one part to that message
Are there errors? Did the scripts recompile?
last day ı was quıt from unıty and when ı go unıty back today that was not the same
there ıs no error
just yellow thıngs
show the console in unity
Then the script is not saved, if the variables differ
ı dont know that I always savıng
even ı am usıng rıder program That auto saves
Now the variables are different from the image we've previously seen
Rest of the sprites are gone
Sometimes unity doesn't recompile on its own, happens to me a lot don't know why
It doesn't recompile on its own if you don't save it properly
ı am always savıng
ı dıd ctrl S ın codes and ın unıty
but stıll that took much tıme for change varıables
Your Unity is not saved though
ıs there any way for fıx thıs ?
Yes, save it
ı already doıng that Need other way
What does "don't save properly mean"?
For me most of the times this happens is when
Create new script
Double click to open
Delete start, update
Create function
Save
Go back to unity, and it doesn't recompile
Go back to script
create a fake variable
Save
Now works fine
What did I do wrong?
maybe ın settıngs ı need to turn on somethıng or
I don't have this issues. Perhaps, this are bugs in Unity
Probably, I've just learned to live with them at this point lol
we same brother We same..
xd
Hello everyone, I have a problem regarding throw parabolas
I want to display slanted throws etc. in Unity, but my problem is that the results are wrong compared to the real world. (They are off by about 0.4m)
var xAngleRad = 30 * Mathf.Deg2Rad;
var initialDirection = new Vector3(Mathf.Cos(xAngleRad), Mathf.Sin(xAngleRad), 0);
var rotatedDirection = Quaternion.Euler(0, -90, 0) * initialDirection;
var _projectile = Instantiate(sphere, launchpoint.position, launchpoint.rotation);
_projectile.GetComponent<Rigidbody>().velocity =
rotatedDirection * 15f;
Example:
S = (vo^2 * sin(2alpha)) / g
That means: A ball with V0 of 15m/s and launch angle of 30 degrees, should fly 19.86 meters.
But with my setup in Unity, the ball flies approximately 19.2 metres.
Drag and angular drag is set to 0 on the ball.
Is it simply not possible to be more precise, or should that actually work as a rule?
Is your rigid body mass and gravity the same as real life?
what about friction?
Maybe try to create a physics material with all exterior forces set to 0 and test what happens, like friction what Steve said
Okay, I'll give it a quick try. The gravity is set correctly and so is the mass.
@gray mural I'm pulling up OBS for the video rn
Simply ping me when the video is sent
Unfortunately it didn't help, the offset is still exactly the same.
@gray mural here's the video and @hasty canopy if this help you too
Quick question, is there a way to serialize the fields within a record?
@brave furnace i most likely am wrong but i think its [SerializeField]
These are different attributes
SerializeField serializes the field in the Unity Inspector, and Serializable makes the class serializable there
public record Foo(int bar)
{
public float smth;
public Foo(int bar, float smth) : this(bar)
{
this.smth = smth;
}
}
Note that the constructor should be derived from this, otherwise an error will be thrown
this answers my quest, thx 😄
Oh, forget it
Haven't understood the question
I have read it wrong enough.
your example is..... interesting....
but it would work 😄
Couldn't figure out yet but I saw there's 2 character controllers and 1 capsule collider in single player . Don't know why
Forget it)
Why do you even use a Collider with your CharacterController?
Is there anything wrong with this, it won't destroy the fixed joint after it collides with a wall?
When do you call CancelFire()?
I don't see CancelFire called anywhere
Where is cancelfire called, and what does destroyjoint do?
Also, not only you send the code as an image, you also have a light mode
1 is for debuging
not sure to be honest
idk if this helps, but I use it in intractable events
- Try removing the useless colliders first
- Then try to clamp falling speed by some value for good practices
- Then try to spawn the object few feet above the ground
- If it still goes through, see if colliders are disabled for player/ground
Do you have to guess how you use it?
okay, I'll check that then
It would be activated/deactivated by pressing a button on my controller
I was following a tutorial for this, and I thought I had it all correct so idk
But you just said that destroy joint will be called after colliding with a wall?
I see. Then pressing a button correctly fixes it!
Sorry yes, that is correct, it returns or gives velocity to the object when a button is pressed
Also send the movement of the player normally !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.
!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.
Using a site
public void DestroyJoint()
{
Destroy(fixedjoint);
}
from another script I have
So put a Debug.Log in there to make sure it is actually called
Not sure why you don't want to send CancelFire so much
Ok that's good to know, so how is cancel fire called? Also as Steve said, put debug in the code
I believe that's called from inside cancelfire
OHHH I think i found something as to why
Sorry?
so on the empty object (player) it never resets for location
Have you even deleted the Colliders?
Bullet.DestroyJoint(); is called from inside cancelfire , I believe the last screenshot is from bullet class @gray mural
Where is CancelFire called though?
No clue
That's what I've been asking for
Same lol
It's not called correctly, and the op doesn't want to send it
I FIXED IT
Aye congrats!!
so it was the empty object, its location never respawned causing me to constantly fall
thanks guys for helping me fix this
Have you even removed the colliders though?
really was a big help, I'm doing this for an assignment
That's why gotta be careful with hierarchy, and do fix the points I mentioned earlier
I did what you guys asked as well
understood, thank you, lesson learnt
I don't think it's called at all
If DestroyJoint() is called from cancelFire() only, and it's never called. There's the answer you're looking for.
And if you're not sure if it's being called or not, then you should just use debugs:3
That way you will know for sure
It's being called, just tested
Any errors?
No
So joints are being destroyed?
No they keep on stacking
and does your Debug tell you which joint you are trying to Destroy?
I only made a debug log so that I could tell if things are being called
Btw quick question, how many bullets do you have as you're assigning bullet script only in start who's joint you're destroying it at some point
There's only one with a bullet script and one with a gun script
Also since you said joints keep stacking do show the entire bullet script
well it might be a good idea to find out
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
FixedJoint fixedjoint;
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Wall")
{
fixedjoint = gameObject.AddComponent<FixedJoint>();
fixedjoint.connectedBody = collision.gameObject.GetComponent<Rigidbody>();
}
}
public void DestroyJoint()
{
Destroy(fixedjoint);
}
}
that's the bullet script
So where is the Debug.Log to make sure DestroyJoint is being called?
I tested, it was coming through, so I took it off
should I have kept it on?
do NOT do that
yes, of course, you keep all Debug.Logs until you have solved the problem
You shouldn't remove debugs unless problem has been solved, and even then having them stay there is plenty helpful in future
put the debug.log back and add fixedjoint as the second parameter
public void DestroyJoint()
{
Debug.Log("Hi");
Destroy(fixedjoint);
}
Why are we adding new fixed joints, without checking if one already exists there btw?
Just reassign values if one already exists
like this?
the second parameter?
one doesn't exist already, and if it worked, it should be deleting the fixed joint, meaning it wouldn't spawn any new ones after
It works but next time make debugs look bit more meaningful like
Debug.Log("DestroyJoint called here"); or something like that
But imagine the bullet collides with 5 objects before cancel fire is called, it will add 5 different joints but when the cancel fire is called, it will only destroy the last added joint
Fixed joint stops velocity, so it wouldn't be able to hit multiple objects
Never used fixed joints so I'm not sure if that's how it works. Add debug in collision enter too?
it looks like it is indefinitely creating fixed joints
#archived-code-general message
Sounds like this would be an easy fix 
how would I check if there is already a fixed joint?
Since there wasn't a fixed joint initially
`if(fixedJoint==null)
//fixedJoint = add joint
fixedJoint.WhateverYouWannaDo`
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Wall")
{
if (fixedJoint == null)
{
fixedjoint = gameObject.AddComponent<FixedJoint>();
fixedjoint.connectedBody = collision.gameObject.GetComponent<Rigidbody>();
}
}
}
public void DestroyJoint()
{
Debug.Log("DestroyJoint called here");
Destroy(fixedjoint);
}
}
like this then?
nevermind gets an error
Only the add component part inside the null check. Assigning connected body doesn't need null check
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Wall")
{
if (gameObject.GetComponent<FixedJoint> == null)
{
fixedjoint = gameObject.AddComponent<FixedJoint>();
}
fixedjoint.connectedBody = collision.gameObject.GetComponent<Rigidbody>();
}
}
tried this, and it's coming back with an error of not being able to use == on null
if(fixedjoint == null)
no errors, will check tomorrow, thank you for the help :)
I'd like to create save folders for my game, are there any objections to saving each of my worlds in multiple files?
Currently the hirarchy is like this:
- Save1 (Folder representing save slot)
- Game (File with binary)
- Pebblefall Island (Folder representing dimension)
- SaveableObject (File with binary)
- Terrain (File with binary)
Is there a way in which I can get all the sprites that are contained within a Texture2D, in an array, during runtime?
I guess I can just drag them all at once into an array in the editor. Not much more work than dragging the texture2D itself
Generally, there shouldn't be any problem. Unless you're loading a huge amount of smaller files. This can take quite a bit longer than fewer big files.
I don't think Texture2D keeps track of such data. You can check the api docs to make sure.
Is it recommended to use States for a simple AI*
I just did everything in a single method now haha
There're no "recommendations". It depends on your project and preferences.
If it works for you, just keep it like that.
Unless you have concerns about it?
Anyone got an easier explanation of what causes this error? Everything was working fine moments ago
https://gdl.space/fotihuqequ.cs
And I all heard it will suck
Only change was removing a time.timeScale line I didn't want
all stack memory used
possible infinite loop
Then you probably have more important things to worry about other than ai implementation.
Try something like ```cs
Debug.Log("Before SaveGlyphVertexInfo");
TMP_Text.SaveGlyphVertexInfo(...);
Debug.Log("After SaveGlyphVertexInfo");
I know sadly :(
Good I have steamworks 🤣
but it still sucks
what does this do?
at a guess i'd say you might be setting text on your input field which inokes the event which then sets the text again which invokes the event, and so on
I'd double check the last stack entry from your code.
use the SetTextWithoutNotify method instead of SetText or .text =
Nah, it's an issue with your code.
So like this?
timeInput.SetTextWithoutNotify(Time.timeScale.ToString());
yes
Before that, I'd look through the logic
is using Linq here (or in general) more expensive in terms of performance than using a classic loop?
Well OrderBy is definitely more expensive than a simple loop to find the closest thing
You don't need to sort a list to find the smallest element
But also yes there are GC concerns here
Doing anything with Linq is always going to be more expensive than writing it yourself
Oh, that's a good point.
Will avoid using Linq then, thank you guys.
Linq is going to be more expensive for two big reasons:
- Everything is a virtual method call, since everything goes through the
IEnumerableinterface - Many things create garbage
I still use it frequently, especially in colder parts of the code (i.e. parts that don't run often)
There are cases where Linq is more performant because it evaluates lazily, unless your handwritten replacement is also written with lazy evaluation.
But yeah as a general rule of thumb, avoid Linq in hot paths.
indeed
but then you are not taking into account the garbage generated or the boxing/unboxing which almost inevitably occurs
That's still a tradeoff
Linq allocations are fixed cost (unless you are allocating per enumerated item), whereas lazy evaluation can save varying amount, to the point it outweighs the cost of allocation.
Is there a way to get reference to another component on the same object while running a script in edit mode?
So [ExecuteInEditMode] script but can also get values from other components on the same game object
I'm trying to run a script to keep the selector of a grid the same size in x, y values as the actual grid
GetComponent
getComponent<T> seems to throw me nullref errors
or is that another issue that isn't related
Then whatever reference you're calling it on is null or that component doesn't exist on the object
NREs are always the same
hm I'll try again
Ok I think I've narrowed it down, I can successfully grab the component reference however when I try to access the value it throws me a null
grid is null
where grid is of type Grid
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.
I did it in Start
I wonder if it's because Start doesn't run when it's runned in editor mode
Awake or OnEnable would be better...
maybe
the other possibility is you have another copy of this script floating around without a Grid
I'll put it in Awake
Checked for that first, wasn't the case fortunately
OnEnable did the trick
Maybe Awake nor Start get executed in [ExecuteInEditMode]
Thanks!
That's right
Use OnEnable for the edit mode instead
I don't think you saw the most important info: no matter if linq or not, you should just scan it linearly and find minimum
linq has MinBy for that for example
As for the performance, just like others said, linq does cost a bit more, but it's in general negligable and you should absolutely benchmark first and foremost, bother later.
"Avoid using linq" is not the correct lesson that should be learned here
code expressed with linq is often far more readable and maintainable, and this is what you should take into account as one of the priorities as well.
It's also important to recognize, that linq can sometimes handle edge cases you can forget yourself, e.g. when a list is empty MinBy would throw InvalidOperationException while your code depending on implementation could be undefined.
Hey guys! can ParrelSync work on Unity 6?
yes
works perfect
better than unity built one tbh
You missed the "avoid linq in hot paths" part.
Allocations is a much bigger concern than the isolated difference in performance.
Idk if he read that as he didn't reply after "Will avoid using Linq then, thank you guys", but yeah.
Although I'm still in favor of "first, test/benchmark", then "readibility and simplicity" and only after that "optimize according to rules"
is there any way to use apply root motion for 2d sprite renderers? I have an animation that makes 2 dashes but i dont know how to make the player to stay where the animation ends
Yes, performance optimizations should always come after profiling, and that's why it's a general rule of thumb
But realistically, in a hot path, allocations will be a killer.
ah, and also it all depends on a use case, in hot paths yeah, avoid allocations
but also only after they are becoming a problem
I think?
just, be reasonable
Technically yes, especially with incremental GC, if you allocate slower than GC can clean up, you shouldn't get GC pauses.
But like if you have positively identified something as a hot path (eg a long live GO's Update method), there's really no need for profiling or wait until it becomes a problem, just avoid Linq right there.
MinBy doesn't seem to be a thing in my code editor. Maybe because I'm using an older version of Unity (2021)?
I occasionally use LINQ without considering its performance implications, planning to address that later. This was just a quick thought I wanted an answer for. When I said, 'Will avoid using LINQ then,' I meant I would avoid it when it's not necessary.
Tip: at the bottom of each page there's a section where it tells you in which .NET versions the feature is available
I see it's a part of C# 8 (.net 9? idk, versioning is confusing as hell in M$ world) which unity support partially iirc, but in your case a Min overload with Selector should work
Do note that .NET version and C# version are different.
.NET 9 will be C# 12 13
i'm mildly baffled by all the different kinds of .NET versions
Oh, I see. Thank you!
Microsoft naming strikes again 😄
Well, now there's only one being actively developed which is just ".NET"
.NET (New Version)
I never really know which of these is "newer"
i guess that's a separate concept though
maybe
Thery're two distinct "branches" which can't really be compared
- .NET Framework: is a runtime, Windows only. It's now considered legacy.
- .NET: is a runtime, cross platform, the modern go to nowadays. It used to be .NET Core but Microsoft later dropped the "Core" part of the naming so it's just .NET now.
- .NET Standard: is not a runtime. Think of it more like a contract/interface, assemblies compiled against this interface can work on any runtime that implements the interface.
I'm trying to install it but it keeps failing. I use this link https://github.com/VeriorPies/ParrelSync.git?path=/ParrelSync through install package from git URL...
ah, okay, that's roughly what I was intuiting
just download the package and install it tbh
.unitypackage that is
guys how can ı close partıcleEffect
ıt follows my mouse posıtıon but Never stopıng
is there any settıng for ıt
when do you want it to stop?
and how are you playing it?
after when ı press of to mouse0 key
what you mean
you would write code to stop it then
ohhhh
I guess it's play on awake?
no
Says play on awake in the screenshot
ı put ın input.getkey
when ı press mouse that always playıng
ı dont know to play partıcle effect
but need to add thıs for my exam
this is the first time when I actually do not understand a supposedly simple error message
There is no argument given that corresponds to the required parameter 'id' of 'InventorySlot.InventorySlot(int, bool)'CS7036
I have a class inventory slot (not deriving from anything) with this constructor
{
slotID = id;
IsOutfitSlot = isOutfitSlot;
}```
and when I try to derive from InventorySlot, I get that error message, on the class if the deriving class is empty, and on the constructor if the class has a constructor
public class ExclusiveInventorySlot : InventorySlot
{
public ExclusiveInventorySlot(int id, bool isOutfitSlot = false)
{
slotID = id;
IsOutfitSlot = isOutfitSlot;
}
}
this gives said error
Yep that's normal
Yes you need to call the parent constructor from any child constructor
You need to call the base constructor
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
public ExclusiveInventorySlot(int id, bool isOutfitSlot = false) : base(id, isOutfitSlot)
And that's it
Since that when you create your own constructor it gets rid of the default, parameter-less one, any derived class will now need to call it so the instance is properly created
Anyone tried Unity 6 ? Is it slower than the previous versions (the same way every version is slower than the previous one) ?
That is not a trend I have noticed, but why not try it yourself?
i have not observed this trend either
That's because you have beefy computers
Or got used to it
I used Unity on and off over a few years, and I noticed significant slowdowns over a few major versions. From taking 30 seconds to enter play mode to having that little "Hold on" progress window pop up when you right-click something, it's getting worse as versions move forward
perhaps your projects are just getting larger
the time taken for things like recompiles is always proportional to how much work unity is doing
Nothing more than ~20 scripts as that's a major turn off
can you actually measure a difference in an identical project across multiple versions of unity?
No, but I vividly remember that everything was "fast" in the 2017 version compared to the 2021 one I tried a few months ago
When they deployed that new dark UI is the point it got worse
I mostly remember when they deployed the busy bar that people all started complaining it got slower vs when they didn't have a busy bar, and it was shown to have been purely psychological
Recompilation/domain reload performance has gotten noticeably worse since one of the versions, it significantly slows down iteration speed.
that being said I'm sure there have been slowdowns and speedups over time due to various factors
"since one of the versions" is pretty vague
if you have a project I can recompile in two different unity editor versions and get significantly different compilation times, i would be very interested in knowing about that
Yeah I can't pinpoint exactly which one, but my first Unity project was with Unity 2019, and comparing to Unity 2022, changing a script in an empty project was significantly faster back then.
Yeah and I don't know if there's memory leaks or something, but the longer you work on the project, the longer the time it takes to reload assemblies or reload domain (whatever that is) when entering play mode
I have observed this.
I have the "enter play mode" settings set to not reload the domain or scene, so i may be responsible for some of that leaky behavior
Fresh editor instance is 5-10 seconds, and after 4-5 hours, it goes up to around 40, that's the time you restart it and it's back to the normal
And the "busy" window might be psychological for some stuff, but I've seen way too many lengthy "Application.Repaint" when opening windows or changing inspectors, pretty sure that wasn't the case before
this seems the most plausible to me
not just you, some days I need to make an urgent change and it takes a solid 2 minutes to get ready
2022.3.19f1
The busy window probably slows down the whole thing lmfao
"Yeah the process is slow, but let's make it slower by instantiating a new window and pushing events to it to tell the user we're doing something"
should I really use unity 6
I am adding multiplayer but you can't see the other player once a session is started,
https://hastebin.skyra.pw/agagomeceb.csharp
Do I miss something?
nobody's gonna read your whole code 😴
its not that big
If you have the disk space for it, try it
Maybe it'll get faster when they switch to the modern .NET CLR?
Start by looking at the hierarchy and seeing if they spawned in at all
yeah, they didnt
But couldnt see why
If not, start debugging your code that is supposed to spawn them
I have the disk space but is it worth waiting 2 minutes every time I want to recompile
Wait, I think its due the matchmaking
I come from photon, is there some View component you need to add to your player
I dont think there is
docs
I think I found the issue tho
my matchmake doesnt make the player instance
using System.Collections.Generic;
using System.Threading.Tasks;
using Nakama;
using UnityEngine;
public class Matchmaking : MonoBehaviour
{
private ISocket _socket;
private async void Start()
{
await NakamaManager.Instance.Connect();
_socket = NakamaManager.Instance.GetSocket();
_socket.ReceivedMatchmakerMatched += OnReceivedMatchmakerMatched;
await JoinMatchmaker();
}
private async Task JoinMatchmaker()
{
var query = "*";
var minCount = 2;
var maxCount = 2;
var stringProperties = new Dictionary<string, string>();
var numericProperties = new Dictionary<string, double>();
await _socket.AddMatchmakerAsync(query, minCount, maxCount, stringProperties, numericProperties);
}
private async void OnReceivedMatchmakerMatched(IMatchmakerMatched matched)
{
Debug.Log("Match found!");
var match = await _socket.JoinMatchAsync(matched);
Debug.Log("Joined match with ID: " + match.Id);
Movement movementScript = FindObjectOfType<Movement>();
if (movementScript != null)
{
movementScript.matchId = match.Id;
}
}
}```
You don't know if it's going to take 2 minutes
Maybe it'll now take 3 lol
💥
No, anticheat
yikes
yep...
i cant find cinemachine in my package manager
where are you looking
The good thing IL2CPP wont compile everything again if you change 1 script only
im searching it up
if it's anticheat I can't help you but there's a thing called Multiplay which lets you run multiple unity instances
but where
so you can test multiplayer easier
there are different sections to the package manager
I know, sadly wont help here
Cinemachine will be in the Unity Registry
you're looking at packages in the project already
btw nakama is a very good solution for a very cheap multiplayer game
you only need a vps
Does it provide skill based match making?
You can make this yourself
trying to figure out how unity websocket work because I'd rather make my own backend solution
It does have those
I m quite confused on how to go about doing it. Currently using photon for multiplayer
photon is pretty restrictive
it's perfect for games like lethal company where there's no matchmaking as you always group with friends
and PUN can easily be integrated
but for anything that requires SBMM you'd probably need better authority than PUN
make your own server 🥱
Yeah, currently thinking of using some service like playfab or UGS to set up matchmaking
you can use photon quantum but idk how that goes
Playfab 😨
Playfab fell off after being bought by ms
They retired the old docs so now all the links on the forum are dead
Really no idea which service would be better as never done it before, just RnD right now 😅
Unity gaming service
But it would be fun to make everything yourself 😈
Big cost
Yea
You can get pretty far with python flask for backend and websocket for multiplayer
Though I've been told off a lot for using flask
I have a few ideas using photon only but I'm not even sure if pros/cons are worth it T.T
ok what kind of game you making
It's a 1v1 puzzle game like matchmasters
ig photon is ok for this but matchmaking will need Playfab
How to make PlayerWalkSound disable when GameOverScreen shows or player IsDead?
when player 3d model walks it start's playing sound so it make realistic
audio source and script
we do not know what your code looks like so we can't help you
Yea there's no avoiding that as code is right now, but haven't had a complain so far
Not looking forward to it either💀
Tower of fantasy used some weird multiplayer solution, somehow exposed the rpc to spawn objects
and chaos ensued
it was so dumb
people were spawning gigantic enemies everywhere
Lmaooo
I'll have to look it up on YouTube sounds fun
What's good alternative for multiplayer solutions except photon btw?
Noooo 😭
Access the desired variable from the script
for unreal they have their own multiplayer solution built in because epic feeds their Devs
for Godot and every other engine they make their own server code
unity is the only engine where there's third party multiplayer solutions
meant specifically for the engine
Damn, wish I didn't give up on unreal so soon
master one first learn everything then
True true
I've made overcooked multiplayer as a c++ console game before which helped me learn a lot about sockets and multiplayer
Give it a try
Which engine?
no engine it's raw c++ printing to console
Wait I'm dumb didn't read properly lmao
Damnnn that's sick
I might attempt it again with raylib though
Hey guys, Id like to ask for a suggestion on how to visualize connections between two objects - I have a spaceship and "wagon"-like addons to it that are meant to be chained together and attached to the player ship's back, kind of like a train. I've currently implemented it using configurable joints, however I cant think of a good way to visualize the connections. Because its a 3D game and the wagons have a pretty wide range of freedom of movement, it means that sometimes they may get into positions in which a simple line would look a bit awkward, which is why Id like something a bit more "bendy" to connect the wagons. However, physical ropes and such can be quite expensive to simulate, so Id like to avoid using complex physics - is there a simple/hacky way to visualize such a connection?
Gif of ship and wagon placeholders attached as a reference, Id like the lines to be drawn between the ship and wagons
line renderer draw chain texture with transparency
set points to the cubes position
might need more cubes in between but yea
hmmm, is there a good way to calculate intermediate points to give it the appearance of a bend?
gotta look into curves ughhh math 😔
oh really? good to know thanks! Ive only used a scuffed modified version of line renderer for UI so I wasnt fully aware of what it can and cant do x)
the math for it will be strange
it's using animation curve which gives you a lot of control but has hurt my brain in the past
needs research
I'm not sure if you can pass in an animation curve of vector3 in but the editor shows a animation curve
wait is the cube gif yours
yeah yeah
diploma project for my uni slowly cooking lol
thanks!
Can also do mini cubes inbetween big cubes, each being attached with more configurable joints
could using more joints become a potential performance concern? it would most likely some-number-x the amount of them 😩
That I'm not sure , but few of them inbetween each cubes shouldn't be an issue I think
actually, I could technically just use the anchor points of the current joints to pretty much guesstimate the positions of would-be smaller cubes right?
It won't really give a bend shape
You can use rotation of the cubes to linecast to each other
Mhhm, but would look like a chain that's in line with the art style
it sounds very weird but hear me out
oh those are just placeholders for now 😭 this branch is way behind the main one with proper assets LOL
for the bottom cube, physics spherecast based on transform.up
for the top cube, physics spherecast based on -transform.up
use the intersection point
as the position for the subcube
Kek, can always swap out mini cubes for chain rings as well then lol
small disclaimer my code is slower than 95% of users on leetcode
might be worth a shot tho lol
i Im gonna be testing out different ways of doing it anyways
Is there a way to make this top list serializable?
slash editable in the Inspector?
Why is the Stat of type Enum?
And what is EstatModifier?
you would need to use [SerializeReference], since the actual types in the list will be various children ofEquipmentStat
remove abstract
basically you'll need those types to be serializable
Equipmentstat doesn't have members to serialize
Oh right also that
This allows you to serialize Parent and actually store instances of ChildOne and ChildTwo
That's not relevant
ah, you meant the setterprotected on the constructor is irrelevant
however, Unity doesn't provide a UI for a [SerializeReference]-attributed field by default
You named a type "Enum"? That's a no-no, it's a C# system type you shouldn't do that
EStat = stat name
EStatModifier = type of modification that this boost will do (i.e. additive, multiplicative, absolute, etc)
Unfortunately they won't give you a drop-down menu to choose between equipmentstats and equipmentattributes
You can't serialize it like this
something like https://github.com/vertxxyz/Vertx.SerializeReferenceDropdown can be used to provide this
I need this
I use the Animancer package, which has its own SerializeReference system
Why isn't this part of unity base 
because [SerializeReference] can do much more than just storing a List<Parent>
it also allows for you to serialize references between objects
although, to be fair, this is all I've ever used the attribute for :p
These are lists of abstract classes.
I'm using it for my quest system I need to distinguish between Dialogue Enemy and Puzzle objectives
Also, even if the parent type was not abstract, it still wouldn't really work
Unity would only serialize things from the parent class.
It would not understand that you have instances of the child classes in it.
This is what I got using [SerlializeReference]. I think I can make something out of this. Thx!
it's Odin 😄
yesn't, it's making me question why I don't just make 2 lists 😛
probably start with learning the basics of Unity and programming
Don't jump directly into a voxel game as that's a bit more intermediate/advanced
(assuming you mean minecraft-like)
no lol
I recommend following some tutorials to get an idea of game development in general. Brackey's is a good play to start 🙂
There are similarities and differences. But C# is quite different from JavaScript
Start with learning the basics
It's tempting to try to dive straight into your dream game
but... you will definitely fail if you try that
been working on my dream game for 10+ years now 💪
Can I use the drag and drop unity offers for coding I saw online to make a voxel game, or should I start learning c#?
I highly recommend learning C#
You can if you want, but C# is way better
can it be done?
yes
yea they have the same components
it's possible, but if you're making complex code, visual scripting becomes quite... convoluted
blueprint flashbacks
yes its bad
I know in coding for a project you have to make it possible for other developers to be able to work on it, avoiding a yandere dev situation. But would visual scripting a whole minecraft like game, would it be dangerous?
you wont get far anyway with that, you should learn the basics first and make simple projects
you will be half way realizing how poor it is to maintain visual scripting
wdym bt "dangerous"
It would certainly be VERY difficult to collaborate with other developers using visual scripting
How does visual scripting deal with merge conflicts? Just pure pain?
if you're woried about good coding practices, i recommend checking "Clean Architecture" by Uncle Bob out. He defines a concept called SOLID which will streamline coding processes 🙂
Can I use visual scripting for the most part then reorganize the code as I learn c# or is that a dumb idea again
mymans obsessed with VS
the logic/components will mostly be the same but seems silly to start with VS
c# is very human-friendly
I tink you should narrow down your scope a little, try making a war themed game (not minecraft based) using visual scripting. This shall give you a good understanding of how feasible your idea is 🙂
I will try that, that sounds fun
if u know JS just seems silly to go backwards with Visual Script
VS coding looks super easy, I honestly hope it is since I haven’t used it ever
ig
I just was trying to make coding a whole game easier on me alone, I don’t have anyone wanting to help me
coding a game in general isn't easy
it's easy, but also limited in the amount of resources you have about it. If you were to make, for example, an inventory system, you might find 1 or 2 videos that do it through visual scripting, while a regular C# version can be obtained by a plethora of sources, you could even ask ChatGPT.
no gpt
Chatgpt 4 sucks at javascript, you will spend more time debugging it then you will anything else
yes same with any other code
LLMS don't reason or logic
they just regurgitate info based on database match
yeah everyone says the same thing but turns out they made simple kiddie scripts with it
copilot is more legit because its more like predictive code based on other code you wrote
well yeah, that's what most of our scripts are. Small, self contained scripts.
ehh better to just learn the right way
what
Can't instantiate gameobjects in constructors
seems you're trying to call some unity API in separate thread, this isn't allowed
I tried to fix that with ```cs
using System;
using System.Collections.Generic;
using UnityEngine;
public class UnityMainThreadDispatcher : MonoBehaviour
{
private static readonly Queue<Action> _executionQueue = new Queue<Action>();
private static UnityMainThreadDispatcher _instance = null;
public static UnityMainThreadDispatcher Instance()
{
if (!_instance)
{
var go = new GameObject("UnityMainThreadDispatcher");
_instance = go.AddComponent<UnityMainThreadDispatcher>();
DontDestroyOnLoad(go);
}
return _instance;
}
public void Enqueue(Action action)
{
lock (_executionQueue)
{
_executionQueue.Enqueue(action);
}
}
private void Update()
{
lock (_executionQueue)
{
while (_executionQueue.Count > 0)
{
_executionQueue.Dequeue().Invoke();
}
}
}
}```
var go = new GameObject("UnityMainThreadDispatcher");
idk but its saying this needs to be done in the mainthread . so you aren't
yeah accessing that singleton from anywhere other than the main thread if it does not already exist will fail because instantiating it can only be done on the main thread
I mean this is more to do with multi-threading not multiplayer
unless it was like JOBS unity doesn't like its functions being out main thread so fix that lol
are we even certain this is related to multiplayer or threading? this could easily just be trying to instantiate something in a field initializer or some object's constructor during scene load
this is the only thing happening
Not seeing where I did anything outside main-thread
But I am pretty blind
_socket.ReceivedMatchmakerMatched += OnReceivedMatchmakerMatched;
is UnityMainThreadDispatcher some custom class or something
this handler almost certainly runs on a background thread
unless they do some magic for you
UnityMainThreadDispatcher.Instance() make sure that instance exists before you do anything off of the main thread
like i said before, since it gets instantiated if it does not exist it will fail if you only ever check it off of the main thread
since 2022 when it was replaced with FindObjectByType or whatever the new one is called that doesn't automatically do sorting by instance id
why do you even need to use it anyway. literally just call UnityMainThreadDispatcher.Instance() in Start
the new one (FindFirstObjectByType)
You mean use it on ```cs
await NakamaManager.Instance.Connect();
_socket = NakamaManager.Instance.GetSocket();
just call it as the first line in Start. all that will do is ensure that the instance exists before you do anything off of the main thread
lol guess the null check can't even be done off the main thread either
pff
you could cache the result of the Instance() call and just use the cached value instead of calling that method again to access the singleton
ty
Like ```cs
using System;
using System.Collections.Generic;
using UnityEngine;
public class UnityMainThreadDispatcher : MonoBehaviour
{
private static readonly Queue<Action> _executionQueue = new Queue<Action>();
private static UnityMainThreadDispatcher _instance = null;
private static bool _initialized = false;
public static UnityMainThreadDispatcher Instance()
{
if (!_initialized)
{
_instance = FindObjectOfType<UnityMainThreadDispatcher>();
if (_instance == null)
{
var go = new GameObject("UnityMainThreadDispatcher");
_instance = go.AddComponent<UnityMainThreadDispatcher>();
DontDestroyOnLoad(go);
}
_initialized = true;
}
return _instance;
}
public void Enqueue(Action action)
{
lock (_executionQueue)
{
_executionQueue.Enqueue(action);
}
}
private void Update()
{
lock (_executionQueue)
{
while (_executionQueue.Count > 0)
{
_executionQueue.Dequeue().Invoke();
}
}
}
}
and then in start dispatcher = UnityMainThreadDispatcher.Instance();?
Mhm
public abstract class Singleton<T> : StaticInstance<T> where T : MonoBehaviour
{
protected override void Awake()
{
if (Instance != null)
{
Debug.Log(gameObject.name + " singleton confliction");
Destroy(gameObject);
}
base.Awake();
}
}
So my singletons have DontDestroyOnLoad() on them for scene changing, but if I change to a scene that original spawns the singletons, I get the confliction which I need to resolve by removing the newest one from the scene. However, it seems this method of resolving also destroys the Instance reference of the original singleton, even though it still exists in the scene. Any idea how to resolve this?
My idea is just make a main Main menu to never go back into and load all the singletons there
You forgot return;
base.Awake() is still going to run after you call Destroy here
which... depends on what's in there, but it will likely assign Instance = this;?
public abstract class StaticInstance<T> : MonoBehaviour where T : MonoBehaviour
{
public static T Instance { get; private set; }
protected virtual void Awake() => Instance = this as T;
protected virtual void OnDestroy()
{
Instance = null;
}
}```
yeah...
public abstract class Singleton<T> : StaticInstance<T> where T : MonoBehaviour
{
protected override void Awake()
{
if (Instance != null)
{
Debug.Log(gameObject.name + " singleton confliction");
Destroy(gameObject);
return;
}
base.Awake();
}
}```
do this, no?
lemme try
What exactly is not working?
still seems to do similar
blah, I don't usually work with multiple scenes, especially with moving singletons around
but kinda dont want the audio bg just cutting out
where should i attatch the script i have it to my player, should i attach it to GameOverScreen object or no? because the sound still don't dissapier and i think i need also to disable playercontrolls because when it starts walking the audio source starts playing
So, you want to disable the PlayerWalkSound when GameObjectOverScreen shows up or the player is dead?
-
- Which script should disable it?
-
- Which script checks for the
GameObjectOverScreento show up?
- Which script checks for the
-
- Which script checks for the player being dead?
i want to disable PlayerControll so it would can't walk and PlayerWalkSound so it wouldn't play when Game Over Screen shows when he is Dead
Have you already created a boolean for the GameManagerScript?
Also I wonder why you would add a "Script" after its name if it's already a script. Simply GameManager
GameManagers are usually Singletons. This makes it easier for the other objects to reference them.
I would suggest you make it a Singeton. If you don't know what that it, you should google it.
Create a simple generic Singleton<T> and derive the GameManager class from it. Access the boolean using GameManager.Instance.yourBoolean in the other scripts when required
okey, i will try
This are the generic Singletons
- with
outDDOL - with
DDOL
Chose the one you need.
my brain is not working, I don't understand anything here ;Dd
Actually, simply copy-paste one of the scripts to your code and derive the required class from it.
Singletons make you able to reference the class using the Instance
This way, the class derived from the Singleton<T> acts as a "static class", you can say
public class GameManager : Singleton<GameManager>
{
public bool yourBool;
}
// access the GameManager's variable from another class
// without having a variable to reference it
GameManager.Instance.yourBool;
This should be enough for you to understand, I suppose
Actually, I haven't mentioned that the 1st one is also with DDOL. Remove it if needed, usually not.
More than 1 MonoBehaviour cannot exist in a single script. It's going to throw you an error. Add the Singleton to the another script and, have you even seen the links I've sent? Simply copy the code from there and remove the commects if required.
not entirely true but a good general rule
Also I don’t see any MonoBehaviour definitions in that script?
So not quite sure what you’re talking about when replying to that
Im gonna go watch youtube tutorials nothing works for me
these are not monobehaviours
Let me take a crack at it. What’s going on?
I don't understand anything :d I want to automatically turn off the PlayerController so the player can't walk and the PlayerWalkSound audio source won't play when the Game Over Screen appears.
"automatic" doesn't really exist, you gotta code it yourself
What have you tried?
Ok, so what triggers the game over screen?
Player isDead
not sure what that means
magically?
So the GameManager triggers it?
ok, so you already know when the player is dead. What's the problem? Just put the code there to disable the things you want
any idea why this happens
lemme rephrase
you made an error in your code!
how can i fix it
change the protection level
how do i do that
you learn c#
make it public
what's the command for learning c#?
this problem is extremely beginner
Ok there's a lot going wrong here
looks like you made a duplicate variable in this script for some reason
that's completely unecessary and actually will probably cause bugs
im watching a guys video and it causes him no issue
the second problem is, again, you don't have the right access modifier on PlayerMovement.isFacingRight to be able to access it here.
you didn't copy it properly then
^^^^^see here
im sure i did
I'm sure you didn't
and i see
okay
link the video and show the full relevant code
this sort of thing is not something that changes with a Unity update, it's definitely copied wrong
yup
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
In this Unity tutorial, we'll be re-creating Hollow Knight's camera system using Unity and Cinemachine.
We're going to cover...
This is what he did
Already I can see that your code says _player.isFacingRight and his says _player.IsFacingRight, so that's one thing copied wrong.
i mean
another one for the counter
i've done the movement in a different way
ok but
that doesn't let you write invalid C#
Anyway I think this tutorial is a bit too advanced for you
I know
and especially if you don't know the basics yet and they go thorugh the code EXTREMELY fast here
i see..
so it's expected you already sorta know how the basics
honestly just learn good old regular c# first, don't jump straight into unity.
its for a project to be fair thats why im watching a video, im planning to learn c# after but the deadline is soon so i dont have time for that + we didnt have time in the beginning
my teachers are pretty shit anyways
but thank you anyway
school semesters are ending about now, I think you had time to learn c# first.
Anyway as you can see the variable is public in the PLayer script and in fact it's a property and not a field, but that won't make a huge difference
i dont live in the us
Well I find it hard to believe the teacher gave an assignment with something you've never seen before and said ok its due in a week or something
I don't, but your best bet is to learn c# first then follow that video. I suggest codeacademy https://www.codecademy.com/catalog/language/c-sharp do the "Learn C#" lesson, it shouldn't take you too long compared to trying to struggle through the video without knowing
its an awful college that doesnt teach at all, rather they encourage us to google or copy off other students
I am pretty stuck on this for a hour now
https://hastebin.skyra.pw/gegebesewe.csharp
NullReferenceException: Object reference not set to an instance of an object.
Movement+<InitializeSocket>d__32.MoveNext () (at Assets/Scripts/Player/Movement.cs:201)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <fe22fa1c9ce44af491c6d67e6c35b4a4>:0)
once the player matched
I think this causes the player to not be able to move
Line 201 is:
var seedState = new Dictionary<string, string> { { "seed", tileMapGen.seed.ToString() } };```
I believe tileMapGen is null, since seed seems like it would be an int or uint based on your other code
The only things that can be null here and cause this error are:
tileMapGen OR tileMapGen.seed
ty
BTW
doesn't seem like you even use seedState at all
so maybe just delete the line?
wait nvm you do I see it
But the problem kinda is the player prefab when I try to assing them in the inspector will do
also be careful with those lambdas and those interfaces. Those lambdas are being subscribed to an event it looks like, and if the object that script is attatched to is unloaded the event will have a null reference and stop propogating that event.
As for the interfaces they don't serialize in the inspector.
when I am ingame the Tile map gen is indeed empty
But this:
var seedState = new Dictionary<string, string> { { "seed", tileMapGen.seed.ToString() } };
var seedStateJson = JsonConvert.SerializeObject(seedState);
var seedStateBytes = Encoding.UTF8.GetBytes(seedStateJson);```
Seems like a really roundabout way of just writing this:
```cs
var seedStateBytes = Encoding.UTF8.GetBytes($"{ \"seed\": {tileMapGen.seed} }");```
Well what does it say?
"Type mismatch"
what could that mean?
Well should I do it this way then? I am pretty confusefd
What do you think "Type mismatch" means
that the object type is not the right fit
Great! So why don't you check what you're dragging into there
I am dragging exactly what supposes to be dragged into it, and it works ingame just not in the editor somehow
ok, show me what you're dragging into there, and show me what object that screenshot is from
great! Now show it to me
like the object
and show me the object you're trying to drag into there
Because you said it only happens when you make it a prefab
which is weird, but perhaps it's trying to tell you it's a scene object and those can't be dragged into a prefab file
this is if I do it in the scene itself
ah yeah prefabs can't reference scene objects
oh
Is the tilemap generator a singleton?
You can use that
otherwise pass the reference to this script when you spawn the Player
seems kinda weird that your player cares about the tilemap generator at all to be honest though
I believe you have some separation of concerns issues
your player script is doing too much
its for getting the spawn location now
you could also just pass the player the seed itself
rather than the whole tilemap generator
if you just need it for the seed
I mean it's called "movement" but just based on those variables it's also doing:
- Interaction with objects
- Punching
Any ideas?
might be an editor thing
public IEnumerator PreloadMusic()
{
audio.bg_source.volume = 0.0f;
audio.bg_source.clip = audio.Game_BG_Clip;
audio.bg_source.Play();
yield return new WaitForSeconds(2);
audio.bg_source.clip = audio.Boss_BG_Clip;
audio.bg_source.Play();
yield return new WaitForSeconds(2);
audio.ChangeBGMusicState(BGMusic.MainMenu);
yield return new WaitForSeconds(2);
musicPreloaded = true;
}```
What is the actual way to prewarm your audio because this is my fix here
you should see what I do to prewarm my shader cache
isnt there literally a checkbox that says preload audio data which loads it when the scene loads?
my god you may be right
If you don't expect it to play right away you can also check off the "load in background" thing so it doesn't make the scene loading take longer
now to figure out the shader cache issue but I looked for boxes for that
there is an editor method for it but I've not seen anything else
shader cache issue?
first time a shader becomes used somethings I get a hiccup, but I'm talking about hundreds of shaders sometimes showing up at once
so there is some pre-warming issue it seems
it's probably just an editor thing, wouldn't happen in a build
it's funny I was watching some godot video and the dude blacks out his scene for a second and loads every object in front of the camera to cache it all
I'm pretty sure you won't have a problem in a build
i've built and it persists. I think it's more of a webgl issue though
Well there's a method: Shader.WarmupAllShaders(), it ays it prewarms all shader variants of all shaders currently in memory. It says DX12, Vulkan, and Metal might not work correctly.
https://docs.unity3d.com/ScriptReference/Shader.WarmupAllShaders.html
bunch on it, but none of this stuff wants to work
honestly, sticking stuff in front of the camera seems to be the idea as that does actually work
what specifically is happening?
first time a new shader variant object is rendered, Unity must be making and cachign the buffer then
There's also "ShaderWarmup.WarmupShader" But it's marked as experimental
but that's a problem when rendering multiple new shaders at once
but whats the effect that's happening, and how is it happening
windows build I think the method may have work? But no difference in a webgl build
well try the second experimental one
but maybe you need a shader variant collection and prewarm it?
probably something like that yeah. The camera idea does work though so I'll always fall back onto that if not.
ok, i still dont know whats happening other than there's some vague problem
not vague. It's how the shaders are being cached. It doesnt warm shaders apparently so there's something additional work to be done
I don't know how to be more clear on that.
yea, what is the result of this?