#archived-code-general
1 messages Β· Page 77 of 1
will do later on, just didn't want the hassle rn cuz i wanted to check it out really quick
but ty 
Hello everyone, I have a quick question. In my scene, I have a public class called GameAdmin, which stores critical game data and variables. When I instantiate different players, I have to access the GameAdmin by using FindGameObject or FindObjectWithTag commands. It is getting heavier while having more objects trying to get data from GameAdmin. Is there anyway to achieve this by using something else like static methods?
Sounds like you might want to apply the singleton pattern to it.
Something like that
Then you can access it using GameAdmin.Instance
Note this only works if you are sure to only have a single GameAdmin
Yeah, I want only one of them
If you want to really make it look good, you should implement a sort of dependency collection where you get it from, instead of having each manager have their own Instance. Then you grab it from that collection, or allow it to make a new one if it does not exist. This is how Dependency Injection works in C#
But as a quick fix, having it implemented in the behaviour itself works
I have many dependencies and cached objects, variables in the GameAdmin. If I do it static, I would not be able to use its instance in the scene?
Yes
Just know that if your scene unloads, the singleton object no longer exists, but the reference does. So be careful with it
You could add an OnDestroy method and set Instance to null, but this gives edge cases where it might not exist so honestly you should just make it persist between scenes and clean it up properly when you need it to.
Thank you, I will check the link and try to implement
anyone know how to fix this?
[Collab] Collab service is deprecated and has been replaced with PlasticSCM
stop using collab and use unity Version Control (formerly called PlasticSCM)
or switch to git. either way, it's been more than a year since collab was shutdown
my version control is 2.0.3 tho
fixed it, just turned off collab π€·ββοΈ
Hello everyone !
I am currently working on a part of the UI for my game : displaying skill trees.
As these are randomly generated, I am currently creating a script that will draw the skill tree for the user when needed.
I have already done the part where I decide which skill goes where (pixel-wise), and I have created a list of "skills" (using an interface so I can easily grab their icons and names and stuff), and a list of coordinates (Vector2) where I want them in my tree.
now, on to the real "drawing" part :
I have my "container" where I want to create my prefabs.
should I just instantiate them inside it (with the container as parent transform) like I would to with units/enemies/projectiles in the game world, or is there a UI-specific way to do it ?
You wouldnt instantiate the skill as a gameobject if that's what you're asking. Your container should have a script that contains a reference to the data of the skill, and information to display such as the sprite which you can put on the skill tree.
what do you mean ?
I should have "already created" empty skills in the container, ready to be filled and moved when changing the tree to display a new skill tree ?
Your container, the visible part is displayed as a rect, right? You'd send a raycast or however you want to select to that gameobject which will contain some script such as a 'Slot'. This slot should contain the data (to instantiate into the scene) of your skill which you can then retrieve it from.
I didn't understand a thing you said :/
Using the UI and canvas is usually the way to handle such things if you're interested in that method.
But since it looks like you're doing 2D I'm pretty sure you can handle it in a similar way.
They're asking how to do it in UI though
Yes you would just instantiate an object like you do regular transforms @urban marsh, however an additional layer of complexity with UI is how RectTransformss are anchored to the screen, so it depends on canvas scale, aspect ratio and more
thanks for the help and the comment about using rectTransform and the anchors : I was wondering why my things where offset weirdly π
when making triangles in a mesh is it better to go clockwise or counter clockwise?
also when setting Mesh.MeshData.subMeshCount, is there any specific required time to set it, or can I set it directly before I call Mesh.ApplyAndDisposeWritableMeshData()?
why do i get this error : The referenced script (Unknown) on this Behaviour is missing!
UnityEngine.Resources:LoadAll<MoveBase> (string)
ScriptableObjectDB`1<MoveBase>:Init () (at Assets/Scripts/Util/ScriptableObjectDB.cs:10)
GameController:Awake () (at Assets/Scripts/Gameplay/GameController.cs:18)
there are the classes : using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Move", menuName = "Creatures/Create New Move")]
public class MoveBase : ScriptableObject
{
public string name;
public string description;
public CreatureType type;
public int power,
accuracy,
pp, priority;
public bool alwaysHits;
public MoveCategory category;
public MoveEffects effects;
public List<SecondaryEffects> secondaryEffects;
public MoveTarget target;
}
[System.Serializable]
public class MoveEffects
{
public List<StatBoost> boosts;
public ConditionID status;
public ConditionID volatileStatus;
}
[System.Serializable]
public class SecondaryEffects : MoveEffects
{
public int chance;
public MoveTarget target;
}
[System.Serializable]
public class StatBoost
{
public Stat stat;
public int boost;
}
public enum MoveTarget
{
Foe,
Self
}
public enum MoveCategory
{
Physical,
Special,
Status
}
!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.
the docs do say that this stuff is advanced, so perhaps this question is better suited to #archived-code-advanced? (but if I move it there the mods might kill me for cross posting)
Not an error, but a warning
Click the message and it shows you the missing script. Replace it with the correct script
You probably renamed it so Unity has no reference to it anymore
Also !code next time you paste 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.
ye , thats what i thought, didnt work, but it works now
oh, oke
thanks for trying to help anyway
hmm anyone know how to load TMPro.TMP_FontAsset from resource to edit it, my issue is atm that when i try to do using TMPro it says it does not exist. WHen i ResourceLoad and Debug.Log it says TMPro.TMP_FontAsset, tried loading using generic FontAsset but then i got null
hello everybody, i try to use a websocket in unity (client) my server is node js. it's working in editor but not in my browser (in build)
i try with System.Net.WebSockets; and WebSocketSharp
@potent sleetI have another question about my quest system if you don't mind.
Basically, I have implemented the system as you suggested but I have a problem: I have my Quest in a list in my QuestManager, however these can't be MonoBehavior and so I can't for example do my onLoadScene function(which is called by my QuestManager) with calls like FindObjectOfType<> or GetComponent<> inside. What am I doing wrong?
Is it faster to write cs myInt2 = myInt + myInt than cs myInt2 = myInt * 2 ? Or does the compiler fix it? Or does it just not make a difference?
The compiler would probably optimize the multiplication to addition.
Yep, exact same on output machine code
Either way, it's not something you should even be bothered about.
Indeed, there's no significant difference. Try catching bigger performance hogs like repeated uses of Find and GetComponent
No difference
Thank you. What is that? It looks cool
Sharplab
is there a reason you can't have QuestManager as Monobehavior ?
You're trying to access something you haven't assigned in the inspector
Yes, it's because I cant make a list of Quest in my QuestManager. I need to instanciate them.
They can still be MonoBehavior?
No they can't otherwise I cant make a list of all my Quest in my QuestManager.
I don't understand.
huh? how is this not possible?
Is it possible to edit this in game ? or through script
oh thanks.
It's how it works, Unity wont let me create a list of class objects inheriting from monobehaviour at runtime
I'm trying to make a pickup script in unity. When I walk over a weapon I want it to be placed in the players hand. My current attempted solution was to parent the weapon to the lowerarm of the player. But the scale and rotation is all wrong when I do this. Also I seem unable to rotate my weapon to the right angle
This is my code
public void OnTriggerEnter2D(Collider2D col)
{
// Pickup gun
if (col.gameObject.CompareTag("Player"))
{
Shooting shooting = col.gameObject.GetComponentInParent<Shooting>();
if (shooting.holdingWeapon) return;
this.transform.position = shooting.LowerArm.transform.position;
this.transform.parent = shooting.LowerArm.transform;
}
result
does your player have any non-uniform scaling?
i.e. scaling that isn't 2,2,2 or 0.5,0.5,0.5 or whatever
RuntimeNavMeshBuilder: Source mesh Cylinder.001 does not allow read access. This will work in playmode in the editor but not in player
How can I fix this? I genuinely have no idea
ah yeah, I ran into this recently
and it did, indeed, not work in the player!
so you're trying to generate a nav mesh at runtime
yeah, because I have a procedurally generated level
yes, my lower arms scale properties are the following
if you tell it to use render meshes, not colliders, the meshes will need to be marked read-write
I'm not sure if you can mark the built-in meshes as read-write..
its not builtin
o right
where would I mark that?
I dont see that
This will keep an extra copy of the mesh data in main memory, iirc
Show me the inspector.
i think i need better names for those two concepts
np
lets see if not break
ok yeah, just need to do that for all imported models
then the thing should work
next step is solving the freezeframes whenever a new chunk is genned and generates the navmesh
you can select many assets and check the box all at once
yeah, I only have 2 rn so it isnt that bad
I might try coroutines for this
i don't know too much about runtime navmesh generation yet
well I'm boiling it down to "Laggy thing happens and suspends running"
so if I try coroutines maybe it wont suspend
if the function that builds a navmesh returns after the navmesh is built, coroutines will not help
you can still hang the game from a coroutine
coroutines are not magic; they're just capable of yielding to suspend execution
ok mayb async then
ah yes
UpdateNavMesh(NavMeshData)
AsyncOperation is just a coroutine that peeks at an async operation to see if it's done
time to learn β¨ Threading β¨
Can I get some help please?
Been waiting for 10 minutes now
not sure
if you parent something to another transform, that child will then use the parent scale as their reference, which means a non uniform scaled parent will cause weird scaling and rotation in their child. Usually, if it is absolutely essential to scale a rendered object via the transform, people tend to parent it put the renderer as a child to the uniformly scaled transform that is then used for logic animation etc.
So the first step to solve your warped gun issue is to make sure the transform you are trying to parent it to is uniformly scaled (as in all three numbers in the scaling vector have the same value)
You can't parent it directly under the hierarchy when you have it scaled like you do. you have other options like using a script to copy position and rotation from another transform in Update
Alternatively reorder your hierarchy like Christopher is saying
non-uniform scaling is, in general, The Devil
it's okay for "leaves" -- transforms that have no children
@rose token in addition to this, thereβs this component https://docs.unity3d.com/Manual/class-ParentConstraint.html
Ah sure, nice!
Could I get an example of how to use the ParentConstraint
It's free help from others on their own time, doesn't matter how long you're waiting. People will respond if and when they know how, be patient . . .
Everything you need is in the documentation
i remember it being a little confusing to set up a constraint via script
here's how I configure a LookAtConstraint
void Awake()
{
target = GetComponentInParent<Entity>();
health.target = target;
lookAt.AddSource(new() {
sourceTransform = Camera.main.transform,
weight = 1f
});
lookAt.constraintActive = true;
}
i use ParentConstraint to get around how VRChat scales your head down really tiny
it's handy
Why can't I have two variables with the same name in different cases in a switch statement?
oh lord, switch statements...
the tl;dr is that a switch statement is one big block
notice how it's all wrapped in a single pair of curly braces
However, there's nothing stopping you from doing this:
switch(Time.frameCount) {
case 1: {
int x = 3;
break;
}
case 3: {
int x = 5;
break;
}
}
in fact, you can slap down block statements wherever you want!
{ { { { { { { { { {
print("hi :)");
} } } } } } } } } }
You usually use them after if because if only affects the next statement
A block statement is a single statement that contains several statements
thus letting you execute all of the statements in the block if the conditional is true
this is why they're optional for one-liners
if (foo)
bar();
if (foo) {
bar();
}
both of these have one statement after the if statement
I wonder what the performance impacts are of one versus the other, if any
all of this gets chewed up by the compiler
it just needs to know, logically, what stuff should be skipped if the conditional fails
the IL (intermediate language) has no notion of "statements"
hey everyone. so I was wondering if I can have a child class not having to write a redundant line of constructor...
i.e. parent is
class P {
public P(int a){}
}
``` and child is
```csharp
class C:P {
public C(int a) : base(a){}
}```
is there a way to escape this insanity?
why can't the compiler just realize that when I don't write anything for the child, i want it to use the parent's constructor?
fyi this gives error
class C:P {}```
them's the rules
it's very, very inconvinient for large objects...
three lines of redundant code.
yeah youre right. should be greatful
i used to love Java, back in college
π«
C# is just Cooler Java, when you think about it
if we factor this out, that is (the blue lines are redundant but forced)
we could use required and initializers in modern C# versions. but not in Unity's old C#
me too. What I loved about Java was... umm, there wasn't any reason other than I only knew Java back then
I like ummm the uhhhhhhh
the uhhhhhhhhhhhhh
well it was a managed runtime
java was like sweatpants
i say, as i sit in my bedroom, wearing sweatpants
(i'm sick ok)
it's just the Java syndrome kicking in. you'll be alright after a few more lines of C#
crux@Fens-MacBook-Pro Scripts % find . -name "*.cs" | xargs wc -l | tail -n1
5031 total
just a few more lines bro
i believe in you
Something really weird is happening. I add 7 elements to a list in the editor but when I debug the list it's got 0 elements in it
hmm, I wonder if it has something to do with multiplayer
how so?
[hands waving around]
Show your console tab.
but I wouldn't expect that, hmm
this class works everywhere else fine
and if I set this state to be the first state in the state machine it works fine
that's the console
so there are definitely 0 elements in the list
When do you call onEntry?
that's the state in the editor, with 7 transitions in the list
when the state is entered
The code shown won't help us. It'll only tell you/us where you've printed the value.
What code should I show?
Does the class have further code and any that changes the List?
Anything related to the List.
I'll send the full class, but it shouldn't change the list
Else it's an empty list if you've not added-to/modified the List
Which is important to be considered
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I've added elements in the editor, no?
Maybe this is referring to a different object and not the one you've posted above.
Try printed the name of the object.
Debug.Log($"The object in question is {name}", gameObject);```
I accidently have 2 playPolicyState
and had the state transition going to the second one
omgg
thanks
I'm dumb
Well, you'll be able to move on now 
aha, that'll do it :p
passing the object to the second arg of Debug.Log is super useful
yo i coded my player to sprint but it wont change the speed. It does think its sprinting though.
here is the code: https://paste.ofcode.org/33gB38XCqvt3N9pJNkReKpC
Thank you for the explanation. I really appreciate it π
you're welcome!
if (safezoneCollider.bounds.Contains(PlayerHit.point))
{
// Player is inside the safezone, do nothing
}
else if (Physics.Raycast(transform.position, RaycastDirection, out RaycastHit Playerhit, VisionRange, PlayerHit))
{
this.VisionConeMaterial.color = new Color32(255, 0, 0, 255);
onSpot?.Invoke();
Debug.Log("Player detected");
}```
hi. why my "PlayerHit.point have error? π¦
the point have error
Provide the actual error message.
and give us a paste with the code in it
I know that you can get some weird line numbers when dealing with coroutines
It has to generate a whole class to store the state of the coroutine
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hence that <ChangeTurn>d_18 thing
There's a bug in the compiler which causes it sometimes to have index out of range errors point to the end of the block that contains them
interesting
Yeah, I have had it happen before
I just gave up lol
Not this time though
It happens before line 24
Debug.Log("Reached for loop");
for (int i = 0; i < gridPositions.Count; i++)
{
manager.tiles[gridPositions[i].x, gridPositions[i].y].controller.EnableTileSelect(moveTypes[i]);
}
#endregion
Debug.Log("Reached while true");``` It's in here somewhere
either moveTypes is smaller than gridPositions or manager.tiles doesn't contains some of the positions
Good morning everyone π
Wanted to inquire- has there been any changes or open issues regarding saving w/ persistantDataPath coming from Unity 2020 lts to 2021 lts? The plugin I am using stores assets onto the persistantDataPath, ex: AppData/LocalLow/CompanyName. In the new engine, some files can be written correctly to disk while others- such as a texture, model, and photo files- no longer write correctly. Previously on the older engine, all files would write to disk successfully from an API call and download. On the new engine, this process does not start, presumably because it is getting stuck? No errors are caught nor does it exit the program, it just loops forever. The API returns 201 so its making a connection, just not initiating the download process.
Nothing has changed between these projects besides their engine version. I am searching through the code to see if there is a particular place it could be getting stuck but I am not sure where to break - I have been going through the code line by line with the debugger and have not hit where its getting stuck. If anyone is familiar, I am using AvatarSDK Cloud UMA Plugin 2.4. Overall, I am mostly trying to see if there are possibly external changes to the engine that could have disrupted this process to reconcile with the code. If anyone has any advice on how to debug this, its all welcomed. I have researched this to the best of my ability and did not see any open issues or changes that could match these symptoms.
hello, it seems like my new project somehow doesnt have any realtime shadows.
im in the 3d urp preset, so far i only have disable ambient light.
Hi all, I've got a question regarding UnityEvents. Is there a way to pass in both a dynamic parameter and a static parameter that's been set in the inspector? I haven't been able to get that to work directly, and I've toyed around with setting up a custom struct to allow me to but I can't come up with anything solid so far. Does anyone have any ideas?
Could someone check my code here? I have an array I am trying to use that I have set to size 5 but it says index 0 is out of bounds??? I don't know what's going on in it. The array is declared on line 39, and I try to use it on line 300. https://codeshare.io/QnN03R
you mean you use it on line 302?
So im trying to make an andriod game and wanted to test out the InputSystem. What im trying to do is when the player touches the screen a joystick appears on their finger and if they move their finger the joystick will also move. Ive deleted my code multiple times because I couldnt get the joystick to move when the player moved their finger. Any advice or documentation anyone can link me too would be extremely helpful.
You can only pass one parameter through the inspector
A very simple workaround is this:
public int param1;
public bool param2;
public void DoButtonThing() {
SomeOtherFunction(param1, param2);
}```
you can thus pass any number of parameters you want
!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.
please use a paste site for big blocks of code
okay thanks
Yeah 302, the if statement starts on 300. Can you see any reason index 0 would be out of bounds? I am so confused with this lol
the array is non-serialized, right
yeah, it's private
if it was, then it could have some other random size
Yeah, it a private array I am using internally
U can see I declare it as string[] behaviorParameters = new string[5];
So how is it possible for index 0 to be out of bounds?
behaviorParameters[1] = "1"; is line 302
that's index 1, not 0
can you show your error
Yeah, it's the same with index 1
1 sec
IndexOutOfRangeException: Index was outside the bounds of the array.
(wrapper stelemref) System.Object.virt_stelemref_sealed_class(intptr,object)
LevelEditor.OnGUI () (at Assets/Scripts/LevelEditor.cs:302)
UnityEditor.HostView.InvokeOnGUI (UnityEngine.Rect onGUIPosition) (at <6a5b55f2e18b419e9faedac06ac6af94>:0)
UnityEditor.DockArea.DrawView (UnityEngine.Rect dockAreaRect) (at <6a5b55f2e18b419e9faedac06ac6af94>:0)
UnityEditor.DockArea.OldOnGUI () (at <6a5b55f2e18b419e9faedac06ac6af94>:0)
UnityEngine.UIElements.IMGUIContainer.DoOnGUI (UnityEngine.Event evt, UnityEngine.Matrix4x4 parentTransform, UnityEngine.Rect clippingRect, System.Boolean isComputingLayout, UnityEngine.Rect layoutSize, System.Action onGUIHandler, System.Boolean canAffectFocus) (at <171d8a8f3bd84fa7b9eb1f330018a789>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
@leaden ice Could u look at this if u have time? I have no clue why I am having this issue with basic stuff like array size lol #archived-code-general message
i wouldn't ping specific people into your questions . . .
hey. i need help, i cant find the "project settings" documented everywhere.
i only have these sorta settings
dammit messed up the screenshot
why are you using Unity 5.6?
im using a version that supports new 3ds.
so what's the issue exactly
what are you expecting to see and what are you seeing instead
i cant find these playmode editor things
it's all under the Player settings
oh thanks
you sure i cen edit the playmode configurations or something there
i want that reload scenes option
what reload scenes option
That's clearly under the "Editor" section
sure.
That being said it either:
- Might not exist at all
- Might be in a different place
since you're looking at a much older version of Unity
then i would have another question...
can i detect scene change in a persistent object?
wdym by "persistent object"
ah
its created in every scene, if it does alr exist, destroy recreated copy
its always there and doesnt get destroyed
So i declared an action:
public event Action OnJump;
and whenever i try to call the action (with OnJump()) it results in a NullReferenceException, how could I fix this?
OnJump?.Invoke();```
is the typical approach
You will typically get an NRE if you haven't assigned any subscribers to the delegate and you try to invoke it
note this is basically short for:
if (OnJump != null) OnJump();```
Oh alright
yep!
This may be an odd question. How do I save multiple ints or some other save method to playerprefs that can be split up. I am making a shop, but need to toggle each button to unlocked or not, I dont want to have a spam of prefs since the shop sells like 50 things. This is local saved to reduce database calls
There's nothing wrong with having many entries in PlayerPrefs
especially just 50 things
That means my unity inspector will have 50 int variables, and 50 if else statements...
well, you probably want to abstract that a bit...
you'll have a list of 50 item definitions somewhere
I was hoping for some method like saving 10000100101 and then grab the 0 or 1
similar to an array
If you only need this data to persist for the run of the game (as in, closing the game will lose the data), you could store it in a static or serialized class instead, if it does need to save after closing/opening the game again, id suggest maybe using JSON, or possibly a scriptable object (although you cant make changes directly to SO's in builds)
code tho?
its a shop with unlockables, it would lose their progress if it deletes when the game closes
So after a couple changes I made (pretty much unrelated to this). This method is being called twice really fast for no reason. I am only pressing the button once? it was working a minute ago. Any help is appreciated thank you!
pauseAction = input.actions.FindActionMap("Player", true).FindAction("Pause", true);
pauseAction.performed += context => CheckPause();
////////
public void CheckPause()
{
if (!GameManager.Instance.matchPaused)
{
GameManager.Instance.PauseMatch();
MenuManager.Instance.Load("Pause");
}
else
{
GameManager.Instance.ResumeMatch();
MenuManager.Instance.UnloadAll();
}
}
If you want to keep the progress, then you could save it with a JSON file, the data would have to exist somewhere for it to remain persistant, PlayerPrefs could work its just limiting, and for a shop, it sounds like it could be a growing headache parsing a string or something similar to get each shop item
using json will still have the same problem of 50+ if else statements
again, no, it will not
imagine you have a setup like this
Code example?
public class ItemDefinition {
public string identifier;
public float cost;
}
List<ItemDefinition> items;
you would save whether or not you have unlocked each of the items, using the identifier as the key
maybe you'd keep it in a Dictionary<string, bool> in-game or something
to save it, you'd iterate over that dictionary, and, for each key, write the corresponding bool into a playerpref (using 1 for true and 0 for false)
to load it, you'd go through all the item definitions and try to get an int based on its identifier
foreach (var key in itemStatus.Keys) {
PlayerPrefs.SetInt("Unlocked-" + key, itemStatus[key] ? 1 : 0);
}
something like that for saving
Checked a video and it requires creating a new public function for each 50 items
what?
for toggling the object on and off or something
Not if you use a collection like the Dictionary here
Use a collection such as an array or a list
you write the logic once
then you just apply it for every item
this is fundamental to...game programming in general, really!
thats what I mean, you want me to create a function for each item
no, I do not.
What did I say that made you believe that? maybe there is something unclear.
apply it for every item
As long as you manage to bind one item of the collection, to one item of your UI for example, it can be done all at once. Like with the foreach loop
You are giving me a lot of terms, but not an example, I have to google each of these
you have a list of items
one function, with a parameter specifying which object to modify, or using a loop and modifying all of them
you do the same thing for every thing in the list
you mentioned bit fields, so im watching a video on that but it doesnt seem to be the right thing
yes that would be nice
I mentioned it because that's what you were describing.
I do not think it is a good choice.
Sample, assign a new value to a list item
void EnableItem(int index)
{
list[index] = true;
}
and it saves the list to local data how?
id prefer prefs
Do you know where I can file request for In app purchases plugin to have assembly definition?
By looping over it, and storing each value. Refer to <#archived-code-general message>
It's not really the use of PlayerPrefs though, as its name suggests it stores preferences, like resolution, graphics quality, etc. You're better off saving that to a file.
Reading is one line of code, same for writing
its mobile
No problem. That also has filesystem access
they usually have permission issues
nvm, im writing a bunch of spaghetti code and i just deleted some stuff π
Each app has its dedicated storage location created, when it's installed
Under Application.persistentDataPath
Maybe I can save a list to binary file
Or JSON, whatever works for you. No BinaryFormatter though, it has security vulnerabilities and is unsafe to use on unverified serialized data
json has too many lines, its odd
this is quite possibly the worst code i have ever written that actually functions
what
i am genuinely confused by this statement
Not if you don't tell it to display expanded. Most serializers will strip out the whitespace to achieve the smallest size possible.
just use .root you animal
json uses too many brackets
wait, .root exists??
Yeah it's nice to check if you have a parent or not, transform == transform.root
then id have to do like root.child.child or something cuz it's inside a canvas which is inside another gameobj π
Hi everyone! I have my player to have a Shield in front of him with box collider and different layer and tag from player. when player click RMB. But when it collides with an enemy it still takes away my health and I dont really know why cause it shouldnt do that based on my scripts. This is my Health script: https://hastebin.com/share/humemiyixu.csharp This is Script to take damage from a player when collision happens:https://hastebin.com/share/aforebepag.csharp This is player attack script where shield using is:https://hastebin.com/share/uyelerajez.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.
or just assign it in the inspector like a normal person
wont work since the item its checking for is constantly being added and removed
assign the thing that holds the added/removed thing
and/or make a variable for it.
Code like this that relies on the hierarchy being arranged in a certain way is begging for difficult-to-debug bugs later on
when you inevitably rearrange the hierarchy
yeah i will likely change it but for now i am too lazy and stubborn
I prefer to just do GetComponentInParent as long as I know that the thing will always be a child
thats a problem for future me
the UI system in one of my games has lots of components that all look for the UI manager by getting a parent component
can someone pls try to help me with this
Hi I'm working on a Multiplayer project with Netcode for GameObjects. I'm trying to make a rigidbody object but it moves laggy and unnatural in clients.
I added Network Object, Collider, Rigidbody, NetworkRigidbody and Network Transform to my gameobject
the built-in components for this are going to be laggy looking
they don't do some of the more advanced stuff that makes modern multiplayer games smooth (like client-side prediction)
for example, NetworkRigidbody is only simulated by the owner of the object
for everyone else, it's kinematic
interpolation in networktransform makes it too unnatural but when i disable it stops in air and teleports to next position
there is unfortunately no generic solution that looks good for everyone in all situations
what is the game?
It's just and picking up and dropping items
and does this have to be over the internet or just the LAN?
for the sake of prototyping
what is the game though?
It's a coop fps game
over the internet I'm going to use steam matchmaking
do you have a screenshot
and how far along are you?
I just started last weak not much
okay well i guess you can fiddle with the interpolation settings
is that the only thing you want to know about?
yesterday someone asked about making a networked fps and it was really difficult to talk about so i am pretty spent on this issue. it is way harder to make internet networked FPS experiences in unity than it appears.
yeah I don't have problems with other things for now
I was going well but then i noticed object was lagging/jittering
if anyone has a moment i need help with smth
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
based on this message, i don't think you're ready to do this either i'm sorry
you are mutating your knockback force so this isn't surprising
you have a knockbackForce *= damping line
you might get better help in #π»βcode-beginner
sorry im not the best with understanding c# yet, how should i fix this?
as i said i just started last week this was the first problem that i came up with
it is way harder to make internet networked FPS experiences in unity than it appears.
like here is what you think the difficulty is:
1
and here is what the difficulty actually is:
1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
take a look at that line and debug it π
you can print it too
and see how knockback changes
it may be but I'm trying to learn why would i just drop off the game because it has difficulties
alr thanks
sorry i can't be more help
still not sure how to fix this
i want the speed that the player is being knocked back at to gradually decrease each time it gets knocked back, but i dont want seperate knockbacks to differ from each other if that makes sense
is there any way to cheat the number that DateTime.Now returns, for debugging purposes?
other than changing the pc time
wich is I guess what i'll end up doing
Whats the code to read json or loop through entries? I used entries.Add(new InputEntry(producttype.ToString(), 1)); on each item purchased, now what I need is all of them who have 1 or data entry at all will have a gameobject enabled
I assume I will have to add every button to a serialize field
Thats the file managing class (got it from tutorial) but they didnt show usage of it
does anyone know why my Couroutine stop at the yield return and doesnt execute the StartCoroutine at the end ?
IEnumerator OnCompleteAttack(bool succeeded)
{
success = succeeded;
if (success)
{
Interface.SetDialogText("Attack succeeded !");
DecreaseEnemyAppreciationBy(10);
yield return new WaitForSeconds(1);
Debug.Log("marche ta mere1");
}
else
{
Interface.SetDialogText("Attack failed !");
Debug.Log("marche ta mere2");
yield return new WaitForSeconds(1);
}
Debug.Log("marche ta mere3");
StartCoroutine(EnemyTurn());
yield return null;
}
Put some debugs after you start the coroutine and inside of EnemyTurn
Does anyone know why my knockback doesnt work on my enemy, this is enemy take hit script: https://hastebin.com/share/pitabodosu.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
So I put a Log at the beginning, it works. This is weird, it seems like yield return stop my Couroutine
Instead of yield return null, try yield return StartCoroutine(EnemyTurn());
I expect it be a scoping issue, but I still think the coroutine would live on the mono somewhere. I forget exactly
It doesnt work.
My IEnumerator is a local function is that a problem?
Like here is the full function
private IEnumerator PlayerAttack()
{
bool success = false;
attackMenu.OpenMenu(Player, OnSelectAttack);
void OnSelectAttack(AttackObject a)
{
if (a == null)
{
return;
}
Debug.Log("Selected attack");
StartCoroutine(performAttack.StartAttack(a.input.sequence.ToList(), 15, OnCompleteAttack));
}
IEnumerator OnCompleteAttack(bool succeeded)
{
Debug.Log("123");
success = succeeded;
if (success)
{
Interface.SetDialogText("Attack succeeded !");
DecreaseEnemyAppreciationBy(10);
yield return new WaitForSeconds(1);
Debug.Log("marche ta mere1");
}
else
{
Interface.SetDialogText("Attack failed !");
Debug.Log("marche ta mere2");
yield return new WaitForSeconds(1);
}
Debug.Log("marche ta mere3");
yield return StartCoroutine(EnemyTurn());
}
yield return null;
}
remove the return null
It makes an error if I return nothing
oh yeah you got it nested uh
I feel like it should be fine, but I'm rusty at them. I'd probably need to fool around with it for a bit to refresh myself.
Because even if the first coroutine returns, your other (inner) coroutine should still be running
I dont know what to do
There's no reason for this outer function to be a coroutine at all
And typically if your coroutine is not resuming from a yield it's because the GameObject it's running on was destroyed or deactivated
What are you trying to download?
virus detection is...messy
Yeah
it's very likely that you just randomly wound up with something that looks vaguely like a bad thing
Does it scan what the application does? or something like that
it's a real rat's nest of different techniques and signatures
one thing that comes to mind is flagging things that appear to be, say, starting other processes, or downloading files
oh hey (:
perhaps that's what is making it mad
Oh yeah, I didnt include that but I did include a File.Create
But that usually doesnt do anything for the virus detection, ive done it before
can anyone help with this? sorry if im being annoying about it lmao
its just been on my to-do list for a while but i have no idea how to fix it
Okay buddy
Thats def not in my app π @heady iris
they're probably both seeing the same (wrong) signature
this may be a basic question, but i want the spotlight to be NOT smooth
just a little, but it should clearly be a circle.
i changed angle and stuff but it doesnt affect it...
Inner Angle (%), at least in the HDRP
using unity 5.6.5
ah
@heady iris I found out the Issue
Windows really doesnt like "GetAsyncKeyState(Int32 i)"
I put it in there for testing and experiments, it seems to think the program is a virus if that function is used
Quite annoying
Probably because that function would be something a keylogger/screen recorder virus might use
Thanks
likely func, AudioUtil doesn't seem to have a method called GetClipPosition in my version (2021.3.19f1)
it doesn't actually matter if the clip is null
that won't cause an error on that line
the only thing that could be null (and problematic) is func
I have a feeling its new System.Object
there ain't a function with that name.
there's a thing called GetPreviewClipPosition ...
I tried
var func = type.GetMethod("GetPreviewClipPosition", new [] { typeof(AudioClip) });
i'm going off of https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/Audio/Bindings/AudioUtil.bindings.cs
Thanks for your help, sorry I'm kind of dumb
this code is causing an error:
Invoke(JoinLobbyByCode(joinCode), 2f);
The error is Argument type 'void' is not assignable to parameter type 'string' and its under the method
anyone know why? can invokes not pass a value in as a parameter? the function im trying to call is also an async. could that be the issue?
OHHH
you are calling JoinLobbyByCode(joinCode) and then trying to give its return value to Invoke :p
omg i forgot
so it cant pass parameters
ive made this exact mistake before i just forgot lmao
use a coroutine, yeah
Assets\Movement.cs(5,38): error CS1003: Syntax error, ',' expected
ik this belongs in beginner but no one was responding please help
the syntax for a class declaration is
public class ClassName : ParentClass {
// ...
}
compare this to your code.
so
i changed to semi colon to the end brakced
public Rigidbody RB3D;
is in they way
Dude just configure your !ide. It will make your coding life so much easier
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.
yes, you still need to do this
The config is done from an open Unity project, and the Visual Studio Installer program, as VS is already installed
Skip the steps you already completed, like the part where they use the Hub to install VS
Configuring your IDE is required to get help here
everything from this point on is in the unity editor
i dont get it.
What do you not get?
i cant find
this
are you still looking at the unity hub?
if not, are you looking at the Project Settings?
not currently
follow the instructions. Edit > Preferences
im in my project
not Edit > anything else
it's not "not working"; you have a compile error
what is the error?
ah, yes
it's because the method is a static method of GameObject
or Component
so, if your class derives from Component, you can just say FindObjectOfType directly
because it's implicitly like saying MonoBehaviour.FindObjectOfType
you just need to prepend GameObject. to that
Common7/IDE
np
i just like wut
no, you need to select a version of Visual Studio that you have installed
if your version of Visual Studio is not listed, you did not follow the instructions.
i have one installed version from 2019
peeps
Did you just install it?
no ive had it since i started
Does it show up in that dropdown list?
I have to deliver an essay in like a day and have one simple question, up until incremental GC did unity use generational GC?
this and browse is all i have
that looks fine, then
what
Yes, I think you should uninstall your copy of Visual Studio and install VS 2022
then follow the rest of the instructions
.NET uses generational GC, so I would expect so, yes
although, a generational GC is incremental
I had the same impression but I read some articles stating something about mono NOT having generational GC hence so did unity in turn. But this helped, thanks!
how do I change a [SerializedField]'s value from in another file
its too late and my brain is dying
Thatβs possible, yeah. I am not familiar with the internals of Mono
[SerializeField] Vector2 maxPos;
[SerializeField] Vector2 minPos;
public Vector2 MaxPos
{
get
{
return maxPos;
}
set
{
return;
}
}
public Vector2 MinPos
{
get
{
return minPos;
}
set
{
return;
}
}
code rn
Being serialized is irrelevant
Itβs private.
(Since fields are private by default)
but I public it in my code right
You have properties.
Their set methods do nothing.
Both of them just instantly return.
i should probably head to bed π
you need to assign the value to something
(in a setter, the value youβre trying to store is called value)
i dont get it i know i sound dumb bvut my unity hub install portion literally doesnthave an add button the onlyh option or upodate or any thing on my visual C is 2019
would this work then
get
{
return minPos;
}
set
{
Vector2 maxPos = value;
}
public Vector2 MaxPos
{
get { return maxPos; } set { maxPos = value; }
}
public Vector2 MinPos
{
get { return minPos; } set { minPos = value; }
}
okay ill just head to bed and do this tomorrow since my brain cant even work out this simple stuff anymore
i need some help wrapping my head around this. shold i take this to beginner?
That looks correct
Eh, reflection and editor stuff arenβt beginner
is there documentation on Director Timeline/Animation programing?
this is the script that is giving me errors and im trying to fix it but it might be over my head and like @mossy snow mentioned AudioUtil might be depreciated
if UnityEditor.AudioUtil was depreciated how do i look though the UnityEditor API, Library, or dll for an alternative?
I figured out how to poke at it.
Hey guys, have a problem, I put my player in a prefab folder because I have a dungeon generator and it spawns the player randomly and for that it has to be a prefab and the player needs in his script the camera but as a prefab I can't assign cameras, why? Or how do I fix this?
because This is a 2D roguelike game and he shoots in the direction where the mouse arrow is and for that he needs the camera.
okay
ah okay
https://sourceb.in/NTa26r3hJl my Player Script
Hey guys! I'm a little stuck with this thing I want to implement. I wanted a dynamic screen, wherein I push a button and the camera would pan to specific location. I was thinking of moving the camera with a lerp, where the startposition is where the camera is located and then the ending position is the targetposition, and I put it in a function that is then attached to the buttons onclick. ... Should I not have done that? Because it seems like every tutorial I've seen puts lerps in updates haha...
xD
nope didn't do any poking just looked closer at AudioSource and AudioClip cant find audioutil
is that how it should be?
no I mean the punch animation
sorry i mean sword animation
ah okay, but looks nice
but even if I separate that, how do I do that with the camera?
nice
The lower camera should be assigned not the normal
Camera Movement works everything only the player does not turn to my mouse because it needs the camera
Followed some tutorial and then found this dungeon generator with the 2 cameras
both
good question
https://github.com/mihailt/LevelGeneration this is the generator which i use
https://www.youtube.com/watch?v=L_GPgTeTpZI&list=PLfX6C2dxVyLyBec8ibuPibcpTtoQRbo7n&index=8 and the tutorial
In today's video we finish off our game with a Death Screen and a Highscore system!
Playlist: https://youtube.com/playlist?list=PLfX6C2dxVyLyBec8ibuPibcpTtoQRbo7n
Previous Video: https://youtu.be/bwi4lteomic
// JOIN THE COMMUNITY DISCORD!
https://discord.gg/BYGkHuGWAe
// PLAY MY DAMN GAME ALREADY?
https://play.google.com/store/apps/details?id...
I did the tutorial and then found the generator and just copied it into my game
I have just tried to use one no matter which of the two, as soon as I remove one goes nothing more
They're using Cinemachine. One is a virtual camera, the other one is an actual camera
That's how Cinemachine works.
It's a package for controlling the camera. You can google that.
In the "LevelGenerator" script I have to drag in the camera "CM vcam1" and in the cam is in there:
yea
And a tag then give the camera and assign that in the script and done?
google says that ```public Camera catchingCamera;
if (catchingCamera == null)
catchingCamera = GameObject.FindGameObjectWithTag("CatchingCamera").GetComponent<Camera>() as Camera;```
okay, iΒ΄ll try
I'm trying to put AudioUtil back so i can use it but i cant find mono
i tried putting it in Assets but i got errors
and i cant find it when i type in
using UnityEditor.AudioUtil;
//or
AudioUtil _AudioUtil;
windows search didnt find anything
"Put back"?π€
Where do i put this on my computer
https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/Audio/Bindings/AudioUtil.bindings.cs
Why would you want to put it anywhere? It's just for reference. The actual code is in the unity dlls
how do i look at what is in the dll?
You don't... I mean, I guess you could try inspecting the correct dll in the ide, but what for..?
What the heck are you trying to do?
im trying to use this to scrub through audio so i can do facial animation
https://github.com/keijiro/AudioPreviewTrack
But this Line of code
var type = Type.GetType("UnityEditor.AudioUtil,UnityEditor");
var func = type.GetMethod("GetClipPosition", new [] { typeof(AudioClip) })
return (float)func.Invoke(null, new System.Object [] { clip });
Is giving me an error whenever i move the play head
Error
NullReferenceException: Object reference not set to an instance of an object
Klak.Timeline.AudioPreviewPlayable.GetClipPosition () (at Assets/AudioPreviewTrack/AudioPreviewPlayable.cs:49)
Klak.Timeline.AudioPreviewPlayable.PlayClip (System.Single time) (at Assets/AudioPreviewTrack/AudioPreviewPlayable.cs:62)
Klak.Timeline.AudioPreviewPlayable.ProcessFrame (UnityEngine.Playables.Playable playable, UnityEngine.Playables.FrameData info, System.Object playerData) (at Assets/AudioPreviewTrack/AudioPreviewPlayable.cs:30)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
and when i debug fun it returns null
Don't you need binding flags for static methods?
someone said AduioUtil is probably depreciated but i cant figure out how to take a closer look at AduioUtil or UnityEditor to find an alternative
Try generating project files in unity - preferences - external tools with all the checkboxes above checked. Then you should be able to see the editor assembly in your ide. You can explore it to find the class you're looking for.
did you read the notice at that link? There's probably a reason it's 6 years since an update
yah but theres got to be a way to get it to work today or make a better or new one.
Isn't... that what the notice is talkiing about?
That there's a setting to do this now?
there is??!!
... did you not read it?
It's the very first thing in the readme in the link you sent
sorry i just figured life is hard and there is never an easy option to anything ever
my bad
my serialized field is just not showing up in the editor
it's a simple [SerializeField] private static Rigidbody _rigidbody
because its static
can not serialize static fields
oh god I'm dumb
Second one tonight #π»βcode-beginner message
So weird that these come in waves like that
lmao
Thank you @cosmic rain, @mossy snow, @leaden ice
Sorry about wasting your time π¦
just got back into it after years off
kinda remembering things slowly
I use rust mainly anyway, so C# isn't the most intuitive
Well this is more of a Unity thing than a C# thing
Your bug probably isn't in this snippet. Look inside InventoryObject and see what it has in Container. Setting a breakpoint on line 25 of InventoryReader and working thorugh what that loop is doing and why will show you whatever is causing this
I need help with a bug in my game. Whenever the scene is reset the values of some variables are set to 0 or null. for example, when the game is reset, the player's speed is set to 0 for some reason. This has never happened to me before. I'm using github, I don't know if that could have anything to do with it.
Where is that variable that's resetting? On a scene GameObject component?
Did these variables have a different value prior to you pressing play?
Any chances you may have some static variables around?
GitHub is definitely 100% irrelevant π€£
bruh does anyone know why googles giving me this despite me already having the snippet: <uses-permission android:name="com.google.android.gms.permission.AD_ID"/> inside of my android manifest?
Hey guys
sorry, thanks
i mean if it works it works right ?
well you can firstly just probably do
while (!loadingOperation.isDone)
{
yield return null;
}```
if (minLoadingTime > 0)
{
yield return new WaitForSeconds(minLoadingTime);
}
loadingOperation.allowSceneActivation = true;
the line yield return null after setting loadingOperation.allowSceneActivation = true is unnecessary
I don't think there's a need for refactoring, but I think there's an issue with your waitTime and totalWaitTime.
at least you noticed it was kinda not needed tho
// should this even be here?? ??
Maybe what Null suggested though.
Is there a way to determine if a urp decal projector is rendering without constantly checking the distance the player is from the decal βboundsβ?
I would expect it to cull if the bounds are not* in camera view, or maybe I'm mistaken. Usually how it works with the vfx graph.
Hi, I'm trying to use tweening (DotTween) to make my object move in a random direction on the screen, then come back and slam into a position quickly.
my code is as follows:
if (targetPiece != null)
{
var captureDestination = pieceMoveDestination += new Vector2Int(UnityEngine.Random.Range(-1, 1) * 5, UnityEngine.Random.Range(-1, 1) * 5);
var captureTween = DOTween.To(() => movingPiece.transform.position, x => movingPiece.transform.position = x, captureDestination, 1f);
while (captureTween.IsActive())
{
yield return null;
}
}
// Standard movement
var tweener = DOTween.To(() => movingPiece.transform.position, x => movingPiece.transform.position = x, pieceMoveDestination, 1f);
while (tweener.IsActive())
{
yield return null;
}```
my issue is that it goes out as expected, then teleports back to the original position and then slowly going to the final position.
Any ideas?
There is a draw distance I know on the projector, but I'm not too sure if there's a sure way method to checking if it's being culled
Hello there, I would like to use the cellular noise from the unity mathematics package and preview it , however I dont know how to activate it; I want to preview this noise into a 2d texture but it uses a float2 instead of a float, so How do I render this ? standard noise is as easy as this
Nvm, it turns out it returns F1 and F2 from cellullar so you can use x or y value
Am I'm running into precision problems?
private void OnDrawGizmos()
{
var pos = transform.position;
var nearClip = _cam.nearClipPlane;
var horzFrac= (Screen.width + 0f) / horizontalCount;
var vertFrac = (Screen.height + 0f) / verticalCount;
Vector3 screen;
screen.z = nearClip;
for (var x = 0; x <= horizontalCount; ++x)
{
for (var y = 0; y <= verticalCount; ++y)
{
screen.x = x * horzFrac;
screen.y = y * vertFrac;
pos = _cam.ScreenToWorldPoint(screen);
Gizmos.DrawSphere(pos, size);
}
}
}
revised for better naming convention.
hey can someone please help me with my code
i was told that I shouldn't rely on singleton too much
but I can't think of a better pattern to do this.
basically i want a pool of bullets
so i was thinking of making it signleton
so guns can quickly access that pool and recycle bullets
the only problem is if I want to access different types of bullets with different propperties i would have to make more pools
idk if this is a good approach
What you can do instead is create one Singleton to handle serving services.
E.g.
ServiceManager.Instance.Get<BulletPoolManager>();
You would then create a interface to justify which class can be treated as ServiceManager, only that it includes some sort of function to properly initialize/spawn if it doesn't exist initially.
Otherwise, consider looking into Dependency Injection.
The variables are on script on a game object. If I set the value of a variable and then hit play, it works fine, but when the scene is reloaded the variableβs value is set to 0
And is it set to 0 before you hit play?
No
Object pool is probably one of the better uses for a singleton
What if you set it to some non 0 value, then close the project and open it again. Does it keep the value that you set?
It does, it only changes the value when the scene is reset during play
It doesnβt happen only with floats, if I assign a game object to a public variable, it is set to null when the scene is reset
Pretty sure Unity has implemented their own version of object pool in the recent version of Unity....
And if I stop the game the variables go back to normal
I think I looked at that, and unless it does something under the hood that does anything fancy, it's very similar to that of a singleton design
unity's object pool isn't a singleton at all. but you can use it in a singleton
What exactly does scene reset mean
Load the current scene
Ok and is this script on a DDOL object?
What is a DDOL?
DontDestroyOnLoad
I donβt think it is, but Iβve never used that I this is the first time Iβm having any trouble with this
Ok
Here is a screenshot before hitting play
Here's during play before resetting the scene, everything works fine here
Ok go on...
Noting that some values have changed in screenshot 2 which means your script is changing them
Show the code?
ok
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
// Start is called before the first frame update
//Author: Yatharth Padharia
//Code: To make player move
public float minfallspeed = -0.08f;
public float maxfallspeed = -1f;
public float moveSpeed;
private CharacterController control;
float t = 0.0f;
public float fallSpeed;
public float maximumFallingSpeed;
public float acceleration;
void Start()
{
control = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
fallSpeed = Mathf.Lerp(minfallspeed, maxfallspeed, t);
t += 0.5f * Time.deltaTime;
//print(fallspeed);
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontalInput, 0, verticalInput);
//Tied the movement to time (Andre)
//Make player move in the direction they're looking (Andre)
//Normalized horizontal player movement (Andre)
control.Move(Quaternion.Euler(0, CameraController.horizontalMouse, 0) * direction.normalized * moveSpeed * Time.deltaTime);
//Separated vertical velocity from horizontal movement (Andre)
control.Move(Vector3.up * fallSpeed * Time.deltaTime);
//Slowly make the player fall faster over time (Andre)
maxfallspeed = Mathf.MoveTowards(maxfallspeed, maximumFallingSpeed, acceleration * Time.deltaTime);
}
}
!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.
I'd guess one or more of your other scripts are at fault
How's your slow time script work?
which script reloads the scene?
I'm not sure is a script, I just noticed now that a whole script disappears when the scene is reloaded
Here's is the script before hitting play
And here it is after reloading the scene
The WinState script disappeared
I think it might have something to do with the game object being a prefab
looks cool but what is it for
Ray marching π
Why may I get a vector like this even though I Debug.Log myVector.normalized?
(-0.26, 0.00, 0.97)
that is a normalized vector
Is it?
Bad for me then, bug is in something else
public class RotatingBody : MonoBehaviour
{
public Vector2 RotatePoint;
public float Angle;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector2 v = RotatePoint - new Vector2(transform.position.x,transform.position.y);
float length = v.magnitude;
float rotationAngle = Angle * Time.deltaTime;
float x = v.x * Mathf.Cos(rotationAngle) - v.y * Mathf.Sin(rotationAngle);
float y = v.x * Mathf.Sin(rotationAngle) + v.y * Mathf.Cos(rotationAngle);
v = new Vector2(x,y);
transform.position = v;
}
}
Im simply trying to have my sprite rotate around a point.
Its working, but its flickering between the sides of the point.
Hello everyone !
Is there a difference performance-wise between using fixedUpdate and Update in a script ?
FixedUpdate does not run every frame. you should use it for physics related logic while using Update for most other stuff
my probable guess u forgot to override changes to your prefab;
Yeah, that was it, but it still shouldnβt happen
And also when I assign a game object to a script it is set to null when the scene is loaded, is there a way to fix this?
Overriding the changes worked with variables like floats, but not game objects
a prefab cannot hold another game object which is not part of the the prefab; u have to access that game object runtime;
u can assign it; but as soon as u will hit play it will loose its refrence;
@strange epoch
It works fine when I hit play, the problem only happens when I reset the scene
Would the same happen if the object wasnβt a prefab?
I understand that it "should" be like that, but : what is the reason ? π
i dont think so; havent tried this; let me check this;
because FixedUpdate runs in time with the physics engine updating
It's useful to stick stuff like spherecasting and grabbing colliders in it since you don't want to be doing that every frame
by reset scene u mean to reload the scece; or load scene from from one scene to another?
Reload scene
okay it doesnt break; confirmed checking it; it keeps the refrence no matter what; im on 2019.4.20 lts
Hi guys! Quick question, is it possible to have multiple instances of PointerEventData across different classes? Or would that produce conflicts?
It's just a class so I don't see why not
Oh okay. But for EventSystem, would there be conflicts should I plan on multiple instances of such across different classes?
hi, is it alright to use reflection when building with IL2CPP?
I could try, but if anyone has before, i'd be glad to let me know
id rather suggest to create a common controller for handling pointerevent data; for optimization purpose; as if too many of those classes are active and loaded; would impact performance; nothing else is the issue; and if mulitple events are trying to modify the attributes of the same gameobject that can be a potential problem ;if u handle that with care no issues with having multiple pointerevent data
(finding a value by a dynamic string. so no AoT string magic)
as long as you're not using System.Reflection.Emit, it's fine.
if something isn't found via reflection it has been stripped, and you need to indicate to keep it
yea this is what I thought of as well. Was just trying to confirm if what I observed is correct
Thanks for the help, everyone!
ah right makes sense. so anything else that's not stripped can be accessed via reflection? and I mean using a dynamic (unpredictable) string query
Yes. Everything works unless something was stripped because nothing referenced it explicitly
ah, thanks π
Hello everyone, I was wondering if there's a way to add a dependency to a project to require a certain package, for example, I'm making a prefab that needs the 2D sprite package, do you guys know a way to tell the developer that it needs it to use the prefabs?
is System.Guid not serializable with JsonUtility?
It can only serialize what the unity serializer also can serialize (if it doesnβt show up in the inspector there is a good chance it canβt handle it)
Aye - have found a wrapper for it, good info though, thanks
Probably not. You're better off using a better serializer such as Newtonsoft or System.Text.Json, because JSONUtility is very bad at doing the thing it's made for. I believe Newtonsoft has a package for Unity. Alternatively you can put the DLL of it in a Plugins folder in your project to use it. System.Text.Json is much more work to get to work.
Guys do you know if you can do a coroutine to execute in edit mode?
Yes. There's a package for editor coroutines.
Hey guys so i have a quick question
Should i define EnemyManager at start then use it on update
or use it in update like this?
EnemyManager.Instance.CanAttackPlayer();
It's not going to be a big deal either way
There's basically zero difference as long as you aren't scanning the whole scene for the EnemyManager or something
If it's a small game, it doesnt matter. If it's a big game, consider caching it during Awake which would allow for you to extend/change it more easily in the future.
oh okey thank you guys very much
Caching during awake is going to potentially introduce script execution order issues
indeed.
That doesn't seem likely...
It seems certain to me
Presumably Instance is assigned in Awake
EnemyManager manager;
void Awake(){
manager = EnemyManager.Instance;
}
We are thinking this right?
Yes and if that runs before the Awake that assigns it?
It depends on how you implement EnemyManager.Instance, I guess
I would assume that Instance is lazy initialized
If it's assigned by the EnemyManager during its own Awake call, you're going to have ordering issues
If it's lazy-initialized, then it oughta be fine.
That's a dangerous assumption
And not very common
Relative to awake
The other side of that coin is, imagine you have built a game where you have 50 psuedo singletons and want to migrate to a DI, now you have to fix hundreds, perhaps thousands of calls.
Such is the nature of refactoring code
That's why I said If it's not a small game
You're not caching anything
The reference to EnemyManager.Instance already exists and you're "caching" the same reference
PraetorBlue is right. "Caching" the instance can be troublesome because Instance is most likely assigned in Awake of EnemyManager. This can cause a race condition.
So you're going to want to call it in update like that, or make a property to access it a bit easier:
private EnemyManager EnemyManager => EnemyManager.Instance;
void Update()
{
this.EnemyManager.CanAttackPlayer();
}
I would argue that this is a good way to do this because you abstract the access to Instance. This might be nice for refactoring later if you decide not to make EnemyManager a singleton but instead get an instance of EnemyManager from a collection of dependencies, for example.
properties are a nice way to abstract it, yes
Yup, and in this case it will only try to get EnemyManager.Instance when you call it.
If, for some reason, you do want to cache it, you can make the property store EnemyManager.Instance in a manually defined backing field, and retrieve it from there with later calls.
in unity2D. I want to make it so when you enter a specific area it changes the references to things to be things in that area. my first idea is a trigger box collider that covers the area and use OnTriggerEnter. is there a problem with everything always being in a trigger? can it screw with other triggers?
Is there any advantage on Invoking movement via InputAction like ctx.action.ReadValue<Vector2>() as a coroutine instead of reading the value on Update()?
Why not place boxes at certain entrances? I can imagine a massive square doesn't exactly cover the area that well.
Also, you need OnTriggerEnter2D, not OnTriggerEnter
hmm
doing it in a coroutine feels weird
use a coroutine when you need to perform an action across several frames with state persisting from frame to frame
Wall-sliding for Unity 2D
Okay thank you
without any context whatsover on what you're doing, the advantage would be the normal advantages of using a coroutine
more specifically, you should use a coroutine when:
- you're doing a one-off action
- the action needs to take place over several frames
- the action requires state to persist from frame to frame
the advantage is that you don't have to manually persist that state
you just let the coroutine hang on to it for you between yield statements
in case that's too abstract, by "state" I mean any data that's needed to do the Right Thing: a coroutine that shrinks an object over time needs to store the start and end sizes, and also remember how far along it is, for example
Movement doesn't really fit any of those criteria
you're always doing it (or, at least, you just toggle it on and off), and you're always doing the same thing every frame
The original question comes from whether or not it's cheaper to listen to an invocation (user pressed w to go forward) rather than calling update every frame.
It depends on the context
If you're getting an event pretty much every frame anyway
then it doesn't really make a difference
Thanks for the explanation, this seems what I'm curious about
I prefer to just read values directly every frame
I found it awkward to do
OnMoveInput(InputAction.CallbackContext context) {
lastMove = context.ReadValue<Vector2>();
}
I'll look into that as well, thank you
"polling" just means asking for the value yourself
much cleaner in Update
versus "pushing" (?), where the input system tells YOU when something happens
(which is great for button inputs)
Great, this all adds clarity, thank you for the responses!
np!
Pushing is often better because it means you aren't constantly spamming the input system / the server / etc.
Just out of curiosity, if i have an Update, and i call a function twice within that update, does the function happen twice or only once?
i.e
void Update(){
if(1 = 1) function1();
if(2 = 2) function1();
i think its twice but since its per frame i dont know if it can be done twice per frame
there is nothing special about Update
you'll get two function calls
(note that 1=1 is not valid syntax)
If that function MUST only run once per frame, I'd just move the logic to somewhere that only runs once
ye i know i just put it as an example
also alright thanks
Why would it only invoke once? This is not how c# works π
Ye im not sure why i thought that
Hey boys. Need a quick fix for a problem im having right now.
I'm making a retro-style 2D RTS, and i have a map as an UI object, just an Image, sent on a world space canvas. On top of it i have some other screen-space ui objects.
I want to disable my mouse cursor clicking on the map when i interact with this other Ui objects. How would i approach this?
how do you detect interactions with the map?
Input.GetMouseButtoDown
and then you read the current mouse position and do a raycast?
I Need someone that can help me making a unity battle system similar to undertale, there is someone? It will be very helpful, it's not that hard but i need help
please don't repost the same question in several places
no, i get currentMousePosition then proceed with the algorithm.
The Algorithm? :p
the program xD
It sounds like you need to be able to detect when the mouse hits a UI element, and then bail out
uhm... makes sense
I have this thing: cs [System.Serializable] public class Vector2IntEvent : UnityEvent<Vector2Int> { }
I use it in a script: cs [HideInInspector] public Vector2IntEvent onPositionChanged;
What is the correct way to add a listener to onPositionChanged? I get a red line under ChangeListeners when I put nothing in the parenthesis
positionHandler.onPositionChanged.AddListener(ChangeListeners("WHAT TO PUT IN HERE?"));```
what is ChangeListeners?
A method
is that the method that you want to call?
Yes
then just pass it directly to AddListener
i see. the problem is that i have these multiple canvas overplacing eachother
public void ChangeListeners(Vector2Int _oldGridPos)
{
}``` It looks like this
if you do this:
x.AddListener(MyFunction(/* ... */))
so i have multiple graphics raycaster
you're gonna try to call MyFunction, and then pass the return value from it to AddListener
which is void, in this case, which is impossible
onPositionChanged.AddListener(ChangeListeners());``` Is that not what I'm doing?
Oh
Yes, you're trying to invoke ChangeListeners with 0 arguments
you will get an error
even if you gave it an argument, you'll still get an error, since AddListener wants a function that takes a Vector2Int
What argument do I put? I want the Vector2Int that is passed with the Vector2IntEvent
(and you'd be giving it void)
Nothing.
x.AddListener(MyFunction);
So I just delete the parenthesis?
Right. You are not invoking ChangeListeners here
you are passing it as an argument to AddListener
if you hover your mouse over AddListener, your IDE should show you the type of that function
IIs that always the case with UnityEvents?
This is how it works for anything that expects a function as an argument, yes
Functions can be treated like objects in C#
for reference, a "frame" is not a thing in C#, it's just a basic loop that Unity runs
we might say they're "first-class"
there's nothing special about it
meaning that they're treated just like any other types
in some languages, you can't just do something like
Alright, thanks :)
in C, for example, you can't pass a function as an argument (you have to pass a pointer to a function instead)
What do you mean pointer?
(well, in C# you do this too, function code isn't allowed to move for many reasons)
(you just don't hear about it)