#archived-code-general
1 messages · Page 81 of 1
yep
oh it happens with findwithtag too though
The whole guide?
the script cant find anything out of itself
that is weird
yep
also possibly that we are just being like stupid
Where exactly did it say that you need to install .net 7?
but honestly if it gets bad, maybe make a component which has a variable storing each different child you need to access
not sure how mcuh else i can help you here
from the link that provided in the guide
not particularly knowledged in buildissues
to be exect microsoft
ignore the inefficiency
Ok, did you also install .net framework 4.7.1 developer pack?
i did but its not showing of 4.7.1 its only showing 7 and 6
Where?
have you heard anything about the builder tampering with access
because the entire problem seems to be that they can access anything outside their gameobject
Check the dotnet\sdk path for wether it has the 4.7.1 installed.
But honestly, I'd just use VS instead of VS code.
never had any problems with GameObject.FindGameObjectWithTag
or anythign elselike that
before
so no...
could it possibly be a bug of my editor version?
its not showing of 4.7.1 should i install again
Or it might be in a different directory. I don't know enough about vs code to troubleshoot it. On thing though: did you restart your PC after following the guide?
Alright, then you have an option to look for people that understand vs code, or forget about it and use VS instead.
idk maybe? like i said its hard to say with this
Yes. Vs code is just a fancy code editor with plugins that add certain ide features. That's why it's so hard to configure.
VS is a proper ide that requires minimum configuration to work.
it could be a bug, or something system specific i really dont know
i havent seen anyone else use 2021.1.16f1
Unlikely. Maybe start a thread where you summarize the issue and the troubleshooting steps you took so far? Because it's really hard for anyone to follow on your conversation.
all right
@cosmic raini figured out the solution i just needed to regenrated project files in unity
This is more like a unity’s backend question
I was wondering why you cannot change an Axis directly, like position.x = 123
Is it some weird Vector stuff that doesn’t let you do that
I always wondered this but never knew why lol
Can’t find anything like that on google, or I’m just bad at searching with proper wording
Because vector 3 is a struct and that means its a value type, so when you do position.x= n you are actually accessing a copy of that struct. To change a value in the original you need to reassign the whole struct.
So the copy of a struct is like a read only thing?
Its not read only it’s a full on copy, living somewhere else in memory
The reason that you cannot do e.g. position.x = 1; is that Vector3 position is declared as a property not a field and you can only set an entire property not just a part of it
Because a property is secretly a method, and value types are copied when returned by methods
so you are modifying a copy
https://paste.ofcode.org/hjDjJKsaHh5CTudMfXA7LS -this is my code and there is a short peiod of time after my button is clicked where I am still moving in the direction of whicheevr button i pressed any tips?
dude the link is not working
o well let me fix that
https://hatebin.com/hyzmpyyziz new code because the pasteofcode website is down
Try using raw input axis instead.
thank you so much you are alife saver and its 4:00am and i can happily go bed
Hey guys, anyone knows what happened here? I reinstalled visual studio community, uninstalled visual studio code but it’s still here
I also reset the package managers, but the package folder will be empty, nothing inside
it's some issues with packages u have downloaded
@young hamlet is it actually the .unitypackage?
I manually downloaded Unity 2022, because my Unity hub couldn’t install it, and this one is a 3D Upr project. I didn’t do anything else😳
Is there a way i can make Everything dark in my 2D top down game? and then i use unitys built in light to make a cind of spot light which acts as a flashlight for player?
delete the directional light in the scene and/or use postprocessing
i dont think this is in code though
I have another 2021 version installed by Unity hub, the one with problem is 2022 and downloaded manually, no idea what happened😳
what did ya download?
delete Directional Light I guess
Unity 2022 installation from the official web
I mean
does 2D even have a light object
@young hamlet you had errors on the package
yeah
idk, I forgot
why cannot you make screenshot? i do not see anything
(01:28:18] An error occurred while resolving packages:
One or more packages could not be added to the local file syster
(01:28:19] Librarv\PackageCache\com.unity.render-pipelines.universi
mob.csi8 6reror cSOZ46: the tvbe or namespac
BurstCompileAttribute' could not be found (are you missing a using directive or an assembly reference?)
1(01:28:19) Library Packagecachelcom.unity.render-pipelines.univer
AinMax2Job.cs(8,61: error CS0246: The type or namespace name 'BurstCompile' could not be found (are you missing a using directive or an assembly reference?)
(01:28:191 Library PackageCachelcom.unity.render-pipelines.universal@14.0.4\Runtime\Tiling\ReflectionProbeMinMaxZJob.cs(8,6):errorCS0246:Thetypeornamespacename'BurstCompileAttribute'couldnotbefound(areyoumissingausingdirectiveoranassemblyreft
CS0246: The type or namespace name 'BurstCompile' could not be found (are you missing a using directive or an assembly reference?)
[01:28:19] Library
CS0246: The type or namespace name 'BurstCompileAttribute' could not be found (are you missing a using directive or an assembly referenc
012619 Librar
101:28:19 Librar Package©
CS0246: The type or namespace name 'BurstCompile' could not be found (are you missing a using directive or an assembly reference?)
This is part of the errors 😳
Kinda sounds like you're using incompatible packages or unity versions.
how have you downloaded this package?
is it even .unitypackage?
I didn't download this package, It's all default
Now this is a new project with same problem
when im trying to open this file, there's no default app to open.
Yes I have Visual Studio 2022
yea, I see, thank you, I will reinstall everything and try again
2022 and 2023 have problem to open project
2021 everything is fine, but now im studying a tutorial with 2022
@young hamlet these?
lol, why do you have four Unities?
@young hamlet everything is fine with 2021 version? word there then
yes, everything is fine with 2021
I also work there, new versions can be quite laggy though
I'm studying Code monkey's tutorial, he recommends the 2022 version, so i just follow his step, then it doesn't work..
so what is your problem right now?
I even downloaded the finished project, then got the same problem.
The problem is some packages have error, I'll show you.
Now i'm using 2021 to set up a new 3D Urp project, everything works perfectly.
but if i use 2022 version to set up a new project, then i got this
If 2021 has the same functions like 2022, I can just 2021 then ignore this problem
I remember seeing something like this exactly once (on someone else's computer)
make a fresh project and just install the necessary packages yourself
maybe hit it with Help > Reset Packages to Default
It seems to not be isolated to you alone https://forum.unity.com/threads/error-opening-project-in-2022.1287842/
Someone in the forums suggested restarting your computer.
I tried this, then the package will be empty with nothing..
ah, right, I guess that's the expected result :p
Hello? Is any random person here?
just ask, do not ask to ask or even ask to ask to ask
When you describe things, anything code or asset or file, that is used my multiple different things, do you prefer the word "common" or "shared"?
Or even "universal"?
restart already, the same. I spent almost a whole day for this yesterday...
what?
Hey, I just encountered the weirdest bug I've ever seen since I started game dev. So I have this storage UI system that allows the player to simply drag an item from one storage to another. The system is quite straight forward, it removes the item from one, adds it to another then reinitializes both. And in most cases it works fine. But sometimes, super inconsistently, it just skips the part where it adds the item to the other storage. It's not because of some if else statement, it just straight up skips a line. I tried debugging, and when I tried debugging, it fixed the issue. When I removed them or added another line somewhere else, or simply tried adding documentation between the lines. It broke again. Then it magically got fixed after playing with the comment lines again. But then reappeared in the build.
This bug is just driving me nuts. Any idea why could this be?
I tried everything, I mean probably not everything but I tried everything I can think of... Debugging, play testing with other things, trying out other ways of approaching, going through every single line... but I just cannot see a pattern. It just seems totally random... Will share the code if necessary but I don't think it will make sense as it's just a small part of a rather complex system of many scripts.
Thanks!
I'm just asking which of these two words you prefer
Show your code. I can't tell you anything without seeing at least the part that's going wrong (:
in what context?
Alrighty. Sorry bout that. It's on the way
If it seems to change when you mess with the layout of the code/add debug statements, then it's probably just some kind of inconsistent behavior that happened to occur
I've definitely run into situations like that
is a screenshot okay?
no, !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.
For example when you wanna give name to a folder that holds very simple sprites like square or circle; would you name that folder "common sprites" or "shared sprites"?
would you rather the whole script or only the method that handles the relevant part? It's quite chunky.
if you're fine with sharing the entire script, you can share the entire thing
just tell us where the problem portion is
alright
#Prefabs if I use them
I would lean towards "common"
"shared" makes me think of "shared library", which is strictly a code thing
@hexed forum I guess default sprites
No I mean in a very generic way not specifically prefabs. It could be like scripts that are used by multiple things like "wheel.cs" is used by both "car.cs" and "gamingChair.cs"
@heady iris https://gdl.space/ikegasehox.cs
The problem seems to be in SwitchDrawer(Item item, StorageUIElement fromStorage, StorageUIElement toStorage) Line 243: storageDrawer.Storage.AddItem(item, false);
Default?
i would only call something "default" if it is actually a default
the thing that gets used if you don't specify something else
a folder full of sprites that many things use is not a "default"
scripts should be from the capital letter => Wheel.cs, Car.cs
i know I'm just
the names do not matter
me too
you know what, bye
it references another script. can share that one too.
so, what makes you think that line is getting skipped?
those are default namings
The debug lines
will record a video showing it's inconsistency, is that okay?
will take a few minutes.
What I did was; I put a debug.log line checking if the item is actually being added to the storage. In most cases it returned true, which meant that it actually worked but sometimes, it returned false. The AddItem Function is pretty straightforward. it just adds the item to the storage.
hold on got an idea where the problem can be. Going to investigate and report back.
I'd need to see the definition of AddItem.
yep seems like I found the source
it doesn't tell you if the item actually fit or not (:
Anyone experienced with networking, espexially mirror? Im getting really desperate over a seemengly simple problem
Oh okay!
It seems like it cannot fit item in storage. The reason I missed this seems to be that the fit item function actually prints something out when it cannot fit item but it seems like that was on another overload. Thanks a lot!
Now will investigate why it thinks that the item cannot fit!
yep. stupid me
there ya go
rubber-duck debugging works (:
trying to explain exactly how your code works can help you find problems
Right!
While you have a big chunk of my code, how readable or how good quality is it? I don't really have a chance of getting feedback on my code as I am quite isolated. I am just one dude working on a project. So don't have a teammate that can tell me if my code is shit.
Would really appreciate some feedback!
@heady iris but I still don't get why adding debug lines would change the result. Is it simply that the results are random and I am just delusional or is this a thing that can actually happen?
It's probably randomness, yes.
I swore that adding debug statements was affecting the behavior of the program once
but i'm pretty sure it was just because one of my components was grabbing a reference to another during OnValidate, resulting in surprise behavior changes
ah
something was fluttering between being null and non-null
hi, I'm working on a simple ability system but there is a bug that I can not fix and I don't even know what causes it in the first place.
so with using any ability, you will lose an ability point. there are two abilities that I implemented currently: dash and double-jump.
it is perfectly fine in unity but when I build the project, the dash costs 2 or more ability points per use.
can anyone help? (I'm using the new input system btw)
private void OnAbility(AbilityType type)
{
if (abilityAvailability[type] == false || abilityPoints <= 0) return;
bool condition = false;
switch (type)
{
case AbilityType.DASH:
condition = _controller.CanPlayerDash();
break;
case AbilityType.DOUBLE_JUMP:
condition = _controller.CanPlayerDoubleJump();
break;
}
if (condition)
{
GameEvents.instance.OnUseAbility(type);
abilityPoints--;
}
}
well, show us how you trigger that function with the input system
public void Awake()
{
input = new MainInputAction();
input.Main.Enable();
input.Main.Dash.performed += (context) => SendAbilityInput(context, AbilityType.DASH);
input.Main.DoubleJump.performed += (context) => SendAbilityInput(context, AbilityType.DOUBLE_JUMP);
}
public void SendAbilityInput(InputAction.CallbackContext context, AbilityType type)
{
if (context.performed) abilityInput?.Invoke(type);
}
this is my scriptable object input class
_input.abilityInput += OnAbility;
and this is a line of my awake function in AbilityManager class
Overall, it seems pretty good. Here a list of comments that you could consider.
- Use [SerializeField] instead of public variable.
- Use [Tooltip()] Instead of comments on serialize field.
- Keep consistency in your ordering of function base on qualificator. (Public/Private/Static/Protected).
- Use Private qualifier instead of not putting one.
- Consider removing unused code instead of commenting them. Version Control is there for that.
- Consider an interface for the Input instead of directly calling
Input.GetMouseButtonDown(0) - Do not use
staticif the object is a Singleton. - Review
public static void SwitchDrawer(Item item, StorageUIElement fromStorage, StorageUIElement toStorage)to not do a switch case on the type of object. Use polymorphism/inteface. - Create separate files for your Utility function
- Remove obvious comment like
if (!IsInteractable) return; // Return if this drawer is not interactable.
okay, that sounds reasonable enough
^ and yes, that last point is especially important to me
a comment should be used when there is something unusual
something that is not self-evident from the line of code
or when you need to describe a higher-level idea that wouldn't be clear from the code
or when you want to apologize to your future self 🫠
i have been hit by at least one of these "sorry, future me" comments
so what is the problem?
have you tried logging to see if the ability function is getting called twice?
in unity, yes
and as I said, perfectly fine
but didn't test something like UI text for the build to debug
ah, I see
You can look at the player logs.
i'm not sure what would be causing this..
Is there a way to make preset for collider? Im picking random sprite for an object to avoid and the sizes isn;t the same. Should I make more objects or there is a solution to make collider to be picked with sprite?
builds contain logs?? where?
thank you
how do i visualize box cast on button press?
draw the gizmos yourself or use a convenient debugging library that does it for you like this one https://github.com/vertxxyz/Vertx.Debugging
thanks this will be useful
I am looking to generate an UI like the screenshot. I will have between 2-4 local players. What is a good approach to generate this UI?
I should probably add that with generate I don't mean making all UI from code, just what is a good way to only show or instantiate parts of the UI that is necessary
and if possible have a template that I can instantiate and by tweaking some values have different values and colours tied to it
For some reason the less frame rate the higher character jumps, even tho all my physics are in FixedUpdate and values are generated by Update and IEnumerator with WaitForSeconds
Im starting to lose it
Anyone who knows how to fix this?
Can you show the start of your file?
First 10-30 lines should suffice I think
using UnityEngine;
public class AudioTestScript : MonoBehaviour
{
private AudioSystem audioSystem;
private void Start()
{
audioSystem = FindAnyObjectByType<AudioSystem>();
}
private void Update()
{
// Test if audio system can control a single source
//audioSystem.PlayFirstWithName("SingleSource");
// Test if audio system can coordinate multiple sources
//audioSystem.PlayAllWithName("MultiSource");
// Test if audio system can play random source from a collection
audioSystem.PlayRandomWithName("MultiSource");
// Test perception of sound created via audio system (participants needed)
}
}
I first got this error when I created this file.
Don't you need a using directive for AudioSystem?
Peculiar error, it says something about Unity UI which is not present
'AudioSystem' is a script I created myself btw.
Ah okay nvm
Not sure what it is either, looked it up on the forums and most point to something with VS2022.
you can always try and reboot vs2022
Hello somebody help me pls
hey
do you use Time.deltaTime?
ah
you are in fidedUpdate, i see
@ancient sail would you like to share your code then?
Looks like rebuilding the solution fixed it for me, thanks! 😊
it is a pretty big character controller so I doubt that i can send it, I will try and send issue related parts
it's better for you to send it whole
You can always use pastebin, github or upload the .cs file
@ancient sail !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.
so I downloaded the library and it works, however sometimes I get " missing reference exception universal addition camera data " after stopping the game, and then i cant see any objects. If I restart I can see them again. Any ideas?
"and then i can't see my objects" meaning that the game view goes blank?
Hey! Thanks a lot! Got a few questions though...
- Use [SerializeField] instead of public variable.
Does it make that big of a difference? I find it easier to read.
- Use [Tooltip()] Instead of comments on serialize field.
I previously used Tooltip a lot but I felt like it was better to do it by commenting because easier to read from the code and I usually check what they are through code and not from the inspector. And kinda makes it harder to read from the code.
- Keep consistency in your ordering of function base on qualificator. (Public/Private/Static/Protected).
Didn't exactly get this one :))
- Consider removing unused code instead of commenting them. Version Control is there for that.
I left a bunch of stuff commented because I was still in the precess of building the code and wanted to have the older version there so I can copy from it and all but will remove them when I'm done!
- Review public static void SwitchDrawer(Item item, StorageUIElement fromStorage, StorageUIElement toStorage) to not do a switch case on the type of object. Use polymorphism/inteface.
Didn't get this one either :))
- Create separate files for your Utility function
I already do have a Utility namespace with a bunch of classes but these ones are only used for the StorageUI, but creating another one for everything storage UI related actually sounds good.
Thanks a lot for the feedback. Will do the rest of your suggestions :))
you have destroyed the object and try to access it
do you need help or feedback?
this happens after i stop the game so i dont know how you can destroy anything then
I guess a mixture of both lol
is there a thread on here if im looking for game devs to build a mobile game?
@peak halo
- Keep consistency in your ordering of function base on qualificator. (Public/Private/Static/Protected).
=> it's nice when you writeprivateorpublicfor fields, do not just let isprotected
private bool nice;
private bool nice;
bool nice; = protected bool nice;
=> also use static and readonly fields in case you will never change them
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
thanks bud
idk then
I wrote it, now how can I send it
what?
I use static for things that are shared between all instances. Is that wrong?
copy the code in your VS and paste here with 3 "`"
you still have to use Time.fixedDeltaTime
you mean multiply code in FixedUpdate by Time.fixedDeltaTime?
I only edited the part where my issue is
all the variables are working properly, I checked it multiple times
you are still doing the jumping in the Update() method
wait nvm
my bad
it's a very confusing architecture
if you mean this one it just stops vertical velocity first
rb.velocity = new Vector2(rb.velocity.x, 0);
- By making your variable public you are not respecting the encapsulation which make your code less clean for the user of the class. (https://www.sumologic.com/glossary/encapsulation/)
- By not using Tooltip you prevent potential user to understand the utility of each field without reading your code. Also, you always wonder what something that is serialize does from the inspector, not from the code. (Visualize the way someone that does not understand coding would use your script)
- By reading your code, I saw multiple static, public and private qualifier entangled. It affects readability. https://resources.unity.com/games/create-code-style-guide-e-book
- Beware of commented code, it tends to stick around longer than you imagine
- Read this for the usage of Polymorphism instead of conditional. (https://refactoring.guru/replace-conditional-with-polymorphism)
yeah im pretty bad at this
actually yes, look at the example below:
public bool nice1;
public static bool nice2;
private void Start()
{
this.nice1 ... // nice
this.nice2 ... // Error! "nice2" does not exist in the current context
}
yes, multiply the jump vector by Time.fixedDeltaTime
strange that you are using velocity for jumping though
AddForce is only a wrapper around the usage of the Velocity on a Rigidbody.
no mean something like:
public static string MainName;
public bool OverrideMainName;
public string OverridenName;
private string _name;
void Start()
{
if(OverrideMainName) _name = OverridenName;
else _name = MainName;
}
I know this is a very stupid example but I usually use static for singelton and apparently that's wrong so I don't want to use that as an example.
It just a question of perceptive. I prefer to keep everything as velocity. Also, AddForce delayed the actual adding of the velocity which can cause issue.
The physics system applies the effects during the next simulation run
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
what's that?
It seems to me that you are reinventing the concept of prefab.
- By reading your code, I saw multiple static, public and private qualifier entangled. It affects readability.
Like this?
I did multiply it, it still is different based on framerate
Keep all static, public, private, protected regrouped
alright thanks
where are those static, public and private qualifiers then? I do not get it
sorry that was stupid. Maybe a function could make more sense
or not.
I just don't get the static variables should never be changed part
You can change static, it is just not a good idea.
It means to fully qualify the variable. If it does not change, make it readonly/const.
the IEnumerators are probably the problem then
actually they most definetely are
why?
ah okay
Because it favorize high coupling which is generally not a good idea.
they are called in Update()
last a set amount of seconds
which can be a different frame count
the whole system is really really weird
@ancient sail
i'd suggest just using AddForce instead
and let unity handle these things instead of reinventing them wrongly
Disagree: I group methods by meaning. If I have three private methods that are used by a public method, then they're getting grouped together in the source.
however, I do agree that the example shown there is very confusing
it seems like things are arbitrarily either part of the public interface or kept private
I see, thank you, but I think I will stick with velocity for now, I have already made most part with it, if problem is with IEnumerators I will change that
@ancient sail, you need to increment the velocity, not override it when you jump.
If you group method by meaning it is because your class does more than 1 thing. Everything should have high cohesion.
...what?
There is also the usage of local function for things like recursively.
a class should perform all of the tasks necessary for the concept the class represents
And a class should only have one responsability.
Which means, it should not have blocks of code that have significative higher cohesion together than the rest of the class.
That being said, in practice you might find yourself a bit more relaxed on the principle. If you absolute needs to do that, make #region in code.
it's a guiding principle, yes
if I have an inventory class, then some functions will need to be able to find the index of an item in the inventory list, and others will not
it would be patent nonsense to cut the inventory class in half because of that
i agree that you should probably split a class up up if it has two very obvious different roles that it's juggling
Not sure I understand your example.
suppose there is a private method that retrieves the index of a specific item in your inventory (or tells you that the item is not contained in your inventory)
some public methods will depend on that, and others will not
You put in the private section of your code. This is a capacity.
Suppose that you have multiple public methods that depends on it
Where you put it ?
Suppose that you have multiple public methods that depends on multiple private methods, how do you organize ?
There is no way to keep the code coherent.
If there are several public methods that all depend on the private method, then I will, indeed, punt it to the end of the class definition
or, at least, to the end of that group of public methods
it's essentially the order I'd have written the functions in
DoesntUsePrivateA
UsesPrivateA
UsesPrivateB
UsesPrivateC
PrivateThing
DoesntUsePrivateB
You cannot group method base on their usage of private method because they might use multiple different private method
I can see the value in just sorting by visibility, though
yes, and if it gets too complex, I will rearrange it
and in making this the default, so that there aren't a bunch of people making judgement calls on this
yeah, that's fair enough
So, you need to constantly reorder your method.
Using JsonUtility. so i have a debug.log for saving and loading it seems to save right but loading after the game closes it doesn't do right. ill send the code for the entire game.
https://gdl.space/iqefatewum.cs -PlayerData Script
https://gdl.space/bedaqebiga.cs -GameManager Script
https://gdl.space/foxuyoquna.cs -MenuManager Script
https://gdl.space/juludoxeco.cpp -JsonSaving Script
https://gdl.space/uxipukidoq.cs -Restart Script
https://gdl.space/oyokovugub.cs -SpringMovementController Script
https://gdl.space/awafetuxem.cs -ScoreManager Script
thank you for any help you can provide! 🙂 ik this is prob alot lol
you need to narrow the issue down
it's very impractical to analyze the entire game
what is wrong? does the game not write the .json file correctly?
does it not read the .json file?
does it write and read the file, but not load any data?
well its in the json loading i think. the debug.log for the save seems to work and save it i see the value also in the json savedata file but when i close the game and open it and load it doesnt load the value
okay, so it is writing the .json file
yes i is
so, test if it's reading the file
write to the console when you hit that part of the program and check if it's getting data
public void LoadData()
{
Debug.Log("Loading data");
using StreamReader reader = new StreamReader(path);
string json = reader.ReadToEnd();
PlayerData data = JsonUtility.FromJson<PlayerData>(json);
Debug.Log(data.ToString());
}
that function does nothing
debug.log it loads the highscore value in the debug i just dont think its setting it right
it reads a file, creates a local variable calld PlayerData, loads data into the variable, logs it
and then quits
yea so i need to set the logged variable to gamemanager highscore value
you need to do something with data, yes.
Hello there, I got a question about job system, how can I call a job after lets say 1 second? I'm making a voxel game which currently generates chunks in parallel with an IJobParallel for, its very fast, however it loads instantly whenever the whole job task has finished, so it leads to a small stuttering at first
sounsd like a timeslicing thing
I would like to load each chunk progressively in order to have an smooth experience (same way minecraft does)
if you have a giant array of data representing chunks, just load a fixed number of chunks per update
And how do I go with that? do I use coroutines?
You could use a coroutine, yeah, or just advance by, say, 100 chunks every Update
I guess the ideal setup would be to sort the chunks by distance to the player, then process a fixed number every update
public void LoadData()
{
Debug.Log("Loading data");
using StreamReader reader = new StreamReader(path);
string json = reader.ReadToEnd();
PlayerData data = JsonUtility.FromJson<PlayerData>(json);
Debug.Log(data.ToString());
GameManager.Instance.highScore = data.highScore;
}
}
I understand, thanks for the suggestion!
so i did this and i see where it saves it and reads it right for debug.log after i close the game now i need to set it to show on mainmenu highscore..
using TMPro;
using UnityEngine;
public class MainMenuManager : MonoBehaviour
{
[SerializeField] TextMeshProUGUI _highScoreText;
private void Start()
{
var highScore = GameManager.Instance.highScore;
_highScoreText.text = "HighScore: " + highScore.ToString();
}
}
Hello ! I need some help to make my tank work correctly... I have a video of the problem but basically I'm making a tank game and the tank won't go up on any kind of hill.... Any idea on how to fix ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class tankController : MonoBehaviour
{
public Rigidbody rb;
public float speed = 10f;
public GameObject shootPrefab;
public Transform shootPoint;
public float fireDelay = 0.16f;
public float lastFireTimestamp = 0;
public Vector3 velocity;
private float verAxis = 0f;
private void Update()
{
verAxis = Input.GetAxisRaw("Vertical");
velocity = transform.forward * speed * Input.GetAxisRaw("Vertical");
if (Input.GetButton("Fire1") && lastFireTimestamp < Time.time)
{
lastFireTimestamp = Time.time + fireDelay;
GameObject currentMissile = Instantiate(shootPrefab);
currentMissile.transform.position = shootPoint.position;
currentMissile.transform.rotation = transform.rotation;
currentMissile.GetComponent<Rigidbody>().AddForce(transform.forward * 5000f, ForceMode.Acceleration);
}
}
void FixedUpdate()
{
performMovement();
}
void performMovement()
{
rb.AddForce(velocity, ForceMode.Acceleration);
if (Input.GetAxisRaw("Horizontal") != 0)
{
rb.MoveRotation(rb.rotation * Quaternion.Euler(new Vector3(0, 2 * Input.GetAxisRaw("Horizontal"), 0)));
}
}
}
well, you can access GameManager.Instance, right?
yes
and that's where the high score is stored, right?
Try to use multiple Wheel Collider.
I tried on another project... it never worked
This happens essentially because you are moving your tank by using pushing force, so makes sense it collides with hill colliders; I would use a raycast under the tank and check for the hit normal angle, then use that angle on the neccesary rotation axis (probably Z axis)
i just got to set it to the ui. i feel that is what the mainmenu script is currenetly doing so kinda confused it should be pulling the value from gamemanager
This is the simplest way to go. Try again.
Agreed
Mhh I think I can go with this solution thanks
Simplest isn't always the best unfortunately... + The wheel collider just goes away everytime
This is because you did not use it correctly.
what do you mean by "Goes away"?
I watched at least 3 tutorials but that's not the point I'll try both
It flies through the air
goes at insane coordinates
then something is wrong with your code
Did you manage to make a simple vehicle ?
I'm talking about the wheel collider
Yup, I mean , either your wheel collider setup is wrong, or the code you use for your wheels is wrong
yes but it only works on a flat plane (the tank code not the wheel collider + code project I abandonned)
Don't you need to apply Torque ?
try settinp up a basic vehicle controller with wheel colliders
Did you manage to make a simple vehicle with Wheel Colider ?
nothing
Start there.
Believe me, I tried... I can try again but the Raycast solution sounds also sensible
Yes, torque is what moves your vehicle pretty much
as I do not really want to realistic physics
there is a specific Wheel Collider type
I know
You do you.
😄
Thanks for your solutions
I will try both and tell you back
is there a way i can find multiple transforms by finding them using the tag "SpawnPoint"
for loop
You take each instance and for each you take their transform and add it to an array
any ideas what would be causing this error?
well, what is the error?
yes
ah, it's underlining public
CS1002
no, that's just the error code
you always want to provide the full text of the error.
I guess you already have script with that name
Definitely!
it's a syntax error; I can see it
click down here; that should open the Problems window
indeed
I did not even see it
forget what I have just said
ooohhh
public float foo
public float bar;
I see it now
thanks lmaooo
its after the "using UnityEngine.Audio;"
I missed the ;
so think the gameManager need to load highscore from player save data for the mainmenuManager to read it and set it. becuase in the inspector the gamemanager after a restart of the game (pressing play and stop playing) it resets to 0.
I would say that the code that loads the save data should do the job
it's the one that knows the old highscore, after all
ok so jsonsaving should set it in gamemanager when pressing load hmmmm okay so there is the problem then its not setting it when loading still
public void SaveData()
{
highScore = GameManager.Instance.highScore;
playerData = new PlayerData(highScore);
string savePath = path;
Debug.Log("Saving Data at " + savePath);
string json = JsonUtility.ToJson(playerData);
Debug.Log(json);
using StreamWriter writer = new StreamWriter(savePath);
writer.Write(json);
}
public void LoadData()
{
Debug.Log("Loading data");
using StreamReader reader = new StreamReader(path);
string json = reader.ReadToEnd();
PlayerData data = JsonUtility.FromJson<PlayerData>(json);
Debug.Log(data.ToString());
GameManager.Instance.highScore = data.highScore;
}
there is save and load functions of the Jsonsave script
I've got multiple Prefabs based on the same base class which requires a sprite. The problem is, some of my sprites are 2x2 and others are 3x2 in size. Is there a "best practice" for dealing with this? As in, how should I go about "centering" the sprites in the Prefabs so they align with the tile grid? Alternatively, is there a way I should be slicing sprites that isn't this? Should I keep all 2x2 sprites in one file and all 3x2 in another?
https://gdl.space/enuruzayix.cpp here is full code for json saving /loading
//Start is called before the first frame update
void Start()
{
CreatePlayerData();
SetPaths();
}
private void CreatePlayerData()
{
highScore = GameManager.Instance.highScore;
playerData = new PlayerData(highScore);
}
i think this is the issue?
it still loads the value tho from the savedata file so idk haha
public void LoadData()
{
Debug.Log("Loading data");
using StreamReader reader = new StreamReader(path);
string json = reader.ReadToEnd();
PlayerData data = JsonUtility.FromJson<PlayerData>(json);
Debug.Log(data.ToString());
GameManager.Instance.highScore = data.highScore;
}
the relevant part
this looks fine
now make sure this runs before you use GameManager.Instance.highScore anywhere
can i put loaddata method used in the Jsonsaving script in GameManager for it to run on awake?
It would be reasonable, yes.
the game manager's first order of business is to load save data
thought so
assuming the game manager isn't recreated when you change scenes, of course
then you'd load your save every time
idk how to implament it. no it doesnt its got a singleton
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public int highScore;
// Awake is called when the script instance is being loaded
private void Awake()
{
//Singleton Pattern
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
right now the save data and load data metheds are called by pressing S key and L key.
you can probably just make the entire load function static. it reads a file and sets some values on the GameManager.
I guess it reads path from that JSONSaving class
yea it makes an error 😛
the data is there like its ok if it doesnt load instantly i press load and it will show from the last game the highscore so even if i press load somthing is not pulling it to write it in the ui
in console it shows
its over my head for sure haha
wait i got it i had it //
public PlayerData (int highScore)
{
like this- //highScore = GameManager.Instance.highScore;
this.highScore = highScore;
}
public override string ToString()
{
return $"{highScore}";
}
}
removed the comments and it worked. i did that at one point because of an error
so it loads it now
mb
Now i just got to run it when the game loads 🙂
Hi there, I have a maze renderer script which runs at the start of the Start Game scene. I'm making an infinite maze runner so when the win tile is touched, the scene is called again so a new maze is generated. How do I go about making the maze bigger every time? - So increasing the Maze Renderer scripts Width and Height attributes every time the scene is called
would this script work to save the three variables for other scenes?
cause I wanna keep the variables of these objects and have the values that get changed for next level
If any of those GameObjects is not also DDOL, it will get destroyed on scene change and the reference will become null
If they are DDOL then there should be no problem
i have this in the player
and I have this object refrenced in "GameObject player"
but it still disappears
the DDOL gameObject cant be child of other gameObject
it worked ty!
use without this, just gameObject
does anybody know if I need to use Time.deltaTime with rigidbody.AddForce?
No, you shouldn't
why?
and this.gameObject and gameObject are the same thing
second one is better
because forces already take deltatime into account, if you add it yourself then it gets added twice
thanks
all ForceModes?
it uses the default forcemode to do a jump
yes
yes
AddForce with the default force mode tells the game how hard the thing is being pushed
the amount of force being applied does not depend on the timestep
no, it's the amount of time that passed since the last update
unless you use it in FixedUpdate; then it gives you Time.fixedDeltaTime
at 60 fps, deltaTime is 1/60f
fixedDeltaTime will be whatever the project is configured to use (0.02f, by default)
If you add Impulse or VelocityChange forces every frame, it will not be timestep independent
true
But the names suggests you how how its meant to be used (impulse for singular impulses, VelocityChange for changing velocity)
transform.Translate(Vector3.forward * Time.deltaTime);
so, in this code, if there are two players with 30 and 60 fps, then their position equals just every one second?
their position will go up by [0,0,1] every second
yes
and at the first frame it's gonna be Vector3(0, 0, 1 + 1/30) for 1st player and Vector3(0, 0, 1 + 1/60) for second player?
yes
nice then
Yes, except its * not +
oh, yes :p
oh, I mean Vector3(transform.position.x, transform.position.y, transform.position.z + 1/30)
1/30 would be 0, you should do 1/30f
In my game I have enemies and player, both sides have rigidbody
If enemy collides with the player, then the player is repelled in the opposite direction
How do I make the player not being repelled, without changing it's mass?
Both enemy and player have the same Physic Material btw.
so you want the player to pass through the enemies?
thx btw
Mass is the calculation used to determine how objects get moved in rigidbody calculations
just like player is very heavy, but his gravity stays the same
Mass does not affect gravity, just change the mass
yes, that's how gravity works
I'm still a bit lost on what you want to happen and what is happening
what do you mean by repelled
idk, my english might be bad
like
moves in the direction, where the player collides with enemy
so you want the enemy to stop the player from moving instead of being pushed around?
enemy pushes him away
how are you moving the enemy?
player just does not care
Rigidbody.AddForce()
try increasing the mass on the enemy so the player can't push them
Why not change the mass though?
Mass doesnt affect gravity, it will still fall the same way. You just need to adjust for mass if your force uses mass
they could use a ForceMode
yea, if the force they use, uses mass, then account for it
ah
i actually realised that I shouldn't do chat, because enemy won't collide with player, when I change my scripts
@shell scarab and @lean sail, sorry for taking your time
dont worry, still a learning experience. Im just browsing these channels to learn more about unity anyways
can .kcl be used in unity?
its a collision file format
I do not think so. Can it be transform into an FBX ?
It's not really a jump, just an upward thrust, it just happens to use the "Jump" button
The doc example is using GetButton so it happens every physics step
I'm rotating an object like this:
transform.Rotate(input, 0, 0);
```how can I clamp this rotation?
Ah, so it is
im not sure, but thats the collision format used in some nintendo games
how can i make something increase each time a certain amount of score is added right now this is my solution but im not sure what i would have to do if i wanted to say double the multiplier at 25 and then triple it at 50
oh wait
never mind im having ideas right now
why does this code not delete child gameObjects?
private void ResetPowerups()
{
foreach (object powerup in powerupDocument.transform) Destroy(powerup as GameObject);
}
powerupDocument is UIDocument btw
you cannot cast a MonoBehaviour to GameObject, however MonoBehaviours do have a gameObject property
maybe you can share the way to make it work?
well for one you want to use Transform for the type instead of object, then it should be fairly obvious what to do from there
Pretty sure Nintendo is not using Unity to create their game.
i wanna do it in foreach loop actually
yes i see that
private void ResetPowerups()
{
foreach (Transform powerup in powerupDocument.transform) Destroy(powerup.gameObject);
}
I feel you are going to be there a long time otherwise.
you've run into an annoying quirk of transforms
when you iterate over them, they don't give you a specific type
they just say "here's an object lol"
however, you can just write it as Simferoce did
@steady moat haha, lol, thank you, I didn't know I can just write Transform there
yeah
your problem was trying to cast to GameObject instead of Transform
maybe you saw "object" and though that was like GameObject :p
but no
object is System.Object
cause when I used var it showed that it's object
also, UnityEngine.Object is not UnityEngine.GameObject, too
GameObject is way more specific
yeah, I also ran into that
I didn't get that before
tried to do a foreach with var
if all you know is that it's an object, you can do very, very little
because that's very, very vague
then next time say that instead of reiterating that you wanted to do it in a foreach loop
sure, thx
is there any algorithms that allow removing items from list conditionally while iterating it?
for example doing reverse loop
but only removing elements that match
yeah, do a reverse for loop and remove the elements that match the condition you want
there's also the RemoveAll method from linq (turns out it's an instance method on List and not from linq) that you can pass a predicate to
wait, I think I confused myself
for some reason I decided that I can't just RemoveAt while doing reverse loop
guys idk what happened i was up all night trying to learn movement relative to camera nd i finally got it and i saved i know i saved and i loaded into my project when i woke up and its basically a completely new project , i know i saved and even if i didnt it wouldnt have brought me bac to square 1
sounds like you just need to open your scene
Is there a limit to how many components a script can require?
Terrifying question
probably not, but if you find yourself requiring an absolute fuck load of components then your code may be way too coupled
Ahaha I was just wondering
i know the ctor for the attribute can take up to 3 parameters, but you can add the attribute to the class more than once
static void SetActive(Object obj, bool active)
{
GameObject go = null;
if (obj is Component component)
{
go = component.gameObject;
}
else
{
go = obj as GameObject;
}
go.SetActive(active);
}
I am not able to figure out what this line means
if (obj is Component component)
the is operator there is testing to see if the object can be cast to that type and then it casts it and stores the result of the cast into the component local variable
oh thanks
woa, you can also store the result?
i didn't realize that
nice
I've been following up with x as Foo
I'm doing a lot of casting in an inventory system, because I just say "equip this item" and then it has to decide what kind of item I asked to equip
i'm still not sure if i'm making a terrible decision by doing that
depends on the c# version you're using, i can't remember which version it was added in, but it's kind of recent (at least in unity terms)
e.g. melee weapon, ranged weapon, consumable item
each one has to go into its own list of equipped items
In this example for a function
public void InitPool(UnityEngine.Object prefab, int size)
``` can we put GameObject instead of Object ? or are there any usecases of UnityEngine.Object ?
I was trying to follow some code of FPS kit which is available on unity learn and there are various things that i dont understand now
The idea of using UnityEngine.Object is that it's very vague
you can give it a GameObject, or a MonoBehaviour, or MyCoolSpecificMonoBehaviour
if you don't care about anything other than 'this is a unity object', you can just say you need a unity object
(note that GameObject is very specific; UnityEngine.Object is a super vague concept)
Hey, I can't find what color operations do exactly. Will 0.5* color1 + 0.5* color2 give me an average color? What does multiplying do in maths term?
that will give you the result of adding half of each color's values together
multiplying scales them piecewise
r1 * r2, g1 * g2, ...
Yeah I was checking that but I don't really understand it 😄
So which one feels more like the average color? adding them?
the idea of an "average" colour isn't that simple - there's a whole topic of colour theory to get into with it, with various blending modes
k I think that's what I thought it did
there are so many color spaces
for example, GameObject inherits directly from Object. MonoBehaviour inherits from Behaviour, which inherits from Component, which inherits from Object
RGB is linear right?
I mean technically it seemed like it
in practice, the human eye notices differences between dark things more than differences between light things
so there's this whole gamma curve thing
and oh lord it's a lot
so if all you need to be able to do is instantiate and destroy something, you can just ask for UnityEngine.Object
Thanks for the info 🙂
Is it possible to load an object from a scene that is not loaded?
Oh thanks for the explanation
So Im trying to make it so you can pan the map camera around but for some reason when ever I click and drag it jumps away
{
camView = GameObject.Find("MapCamera"); //finds the map camera
cmDefPos = camView.transform.position;
canvas = GetComponentInParent<Canvas>();
viewCam = camView.GetComponent<Camera>();
}
public void OnDrag(PointerEventData data)
{
Difference = viewCam.ScreenToWorldPoint(data.position) - camView.transform.position;
camView.transform.position = cmDefPos - Difference;
}```
Ive tried so many things and nothing works for this goddamn thing
you need to record the position the mouse was in when the drag began
and then check how its position differs from the starting point
right
I would record the position the map and pointer were at
so
newMapPos = oldMapPos + newMousePos - oldMousePos
roughly
would that be in the begindrag or ondrag?
I have been working and implementing this rope syste4m for a few months now and I have gotten it to a stage that works wonderful. There is a small issue where the player will randomly detach while swinging and won't change back its rotation. Is there a way I can fix this? Thank you! https://pastebin.com/s57Xa7u4
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.
record your position in begindrag
use it in ondrag
so, that code would show up in ondrag
you're finding the delta between the starting position and the current position
and then applying the same delta to the original map position
this code just finds the difference between the touch point and the map origin
so it will always snap to the same position, I'd expect
oh wait, between the touch point and the camera
same result, though
Ok i tried it but for some reason the x and z values of the camera go negative at when i drag causing on screen map to flicker
show your code
{
PointerEventData pdata = (PointerEventData)data;
oldMapPos = camView.transform.position;
oldMousePos = viewCam.ScreenToWorldPoint(pdata.position);
}
public void OnDrag(BaseEventData data)
{
PointerEventData pdata = (PointerEventData)data;
currentMapPos = camView.transform.position;
Difference = viewCam.ScreenToWorldPoint(pdata.position);
currentMapPos.x = oldMapPos.x - Difference.x;
currentMapPos.z = oldMapPos.z - Difference.z;
camView.transform.position = currentMapPos;
}```
Difference is not a difference in your code.
it's just the current pointer position
remember:
newMapPos = oldMapPos + newCursorPos - oldCursorPos
(where everything is in the same coordinate space, of course)
when i try that the map goes offscreen
doing this causes the camera to move extremly far away
btw the camera position starts at (45,120.4.3)
is this allowed in a coroutine? yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Return)); it seems to not be working but it feels right to me
I need a method like TransformPoint but unaffected by scale
i need it to be affected by position
wdym affected by position
TransformPoint: position, rotation, and scale
TransformDirection: rotation only
TransformVector: rotation and scale only
i need position and rotation
the position is what you input into the function
what exactly is your goal
like what are you using this for
to see global vector coordinates in player local coordinates
it is affected by scale
it doesnt include position
wdym??
i'm not sure what you mean by "affected by position"
it is the position
but if you really need to involve the position another time, you can just add + transform.position to the end
do you know how the methods work?
but like if you have a transform object and you do transform.InverseTransformDirection(some point) it will use that transform's position
yes they use matrix multiplication
okay tell me then what does it mean "affected by scale". i mean if we use player. transformPoint will it mutiply the vector by player scale or what
yes that is correct
so if the scale is (2, 2, 2) then all the numbers will be twice as far away when you call the function
okay so i just divide the vector by player scale then
no just use the other function
the player's local coordinate system is affected by its scale too
so if you want to convert a world space point to a local space point you want it to be affected by the scale otherwise it won't actually be accurate
the local coords are affected by the parent's scale, but not its own scale, i thought
i could be wrong idk
what does it mean local coordinate system affected by scale?
i mean if a player is at scale 2,2,2 then 1 unit in its local coordinates is equivalent to 2 units of world space localposition is affected by ancestor scale
i don't think that's right, i just tried it in the project i'm working on rn and that is not the case
i set the scale to 2, 2, 2 and the position to 1, 0, 0 and it moved to 1, 0, 0 in world coords
not 2, 0, 0
but if i add a child to that one and set its local position to 1, 0, 0 it moves to 2, 0, 0
ah right, but either way the methods on the transform class will do precisely what they are trying to achieve
yeah
but my point was that if an object has scale 2, 2, 2 and you call transform.InverseTransformDirection(some point) then the result will not be multiplied by 2, 2, 2
so i think that's the function waif should use if i'm understanding the goal
at least try it, and if it doesn't do what you want then come back here
show me your code.
yes i think it will work without the complications. i still dont understand the difference between methods though.
between which methods? TransformPoint and InverseTransformPoint?
have you tried reading the documentation
btw i fixed the whole thing
currentMapPos.x += oldMousePos.x - newMousePos.x;
currentMapPos.z += oldMousePos.z - newMousePos.z;```
this worked for me
thanks for the help though
are you updating oldMousePos every frame?
only on BeginDrag
that doesn't make sense; I'd expect this to make the map move every frame based on the total amount of distance the mouse has moved
oh wait
TransformPoint changes a point in local space to a point in world space, this is affected by position, rotation, and scale
TransformDirection changes a direction vector from world space to local space, this is directly affected by rotation
TransformVector changes the magnitude of a vector from local space to world space, this is only affected by the scale
I dont know if i mentioned this but the map uses the render texture of a camera
maybe OnDrag gives you a position delta?
that would make a lot of sense
no, you'd have to read .delta for that
{
PointerEventData pdata = (PointerEventData)data;
oldMapPos = camView.transform.position;
oldMousePos = viewCam.ScreenToWorldPoint(pdata.position);
Debug.Log("old map position" + oldMapPos);
}
public void OnDrag(BaseEventData data)
{
PointerEventData pdata = (PointerEventData)data;
currentMapPos = camView.transform.position;
newMousePos = viewCam.ScreenToWorldPoint(pdata.position);
currentMapPos.x += oldMousePos.x - newMousePos.x;
currentMapPos.z += oldMousePos.z - newMousePos.z;
camView.transform.position = currentMapPos;
Debug.Log("current map position"+ currentMapPos);
Debug.Log("current mouse position" + newMousePos);
}```
why are you even using BaseEventData for the parameters anyway? you can just use PointerEventData so you don't have to cast it
PointerEventData is the default type the interface uses too
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.IDragHandler.html
ah ok
hey anybody got a good tutorial on an monster ai that can patrol and attack you if it find you?
im blank right now and i have one but its not that good
any examples of what you want the AI to be like?
like in those horror games that walk around an when they see you
they will do kill u for example
I don't really know of any tutorials, you could probably search horror enemy AI
the concept of an enemy that walks around and then chases you isn't exactly specific to horror
there should be plenty of resources
however, if you want my own take on how to do it:
the enemy normally picks random locations and walks to them
if the player gets too close, enter combat mode
in combat mode, just move towards the player
if the player gets far enough away, go back to wander mode
You could look into FSM (Finite State Machine) AI, it is a common approach for handling the kind of AI it sounds like your describing
I'd also look into behavior trees which are also really common for handling ai
I guess you are looking for an AI that chases on sight and maybe wanders around. I dont have any tutorials on that, but what u essentially want to do is check the transform forward angle between the monster and you; if the anlgle is less or equal to an angle you set, then it means the monster sees you, but you will also need a raycast to check if there is an obstacle in front of the monster to perform the condition mentioned before or else, it will see you at the specified angle, no matter if there is an obstacle in front
I would like to make a list of Layermasks, how do I reference a layermask?
LayerMask is a struct not a reference type so you can add copies of a layer mask to your list
yes, that is what I want. Should I use getMask?
i mean to get a LayerMask from layer names, yes you would use GetMask
are you saying I should just take copies of the layers themselves and then add them to the list
you haven't really said what the purpose of what you are doing is or what exactly you are trying to achieve. I provided info based on what you said which was about referencing a layer mask in a list which implied you wanted to store references to some other object's layermask variable/property in a list
sorry, I used the wrong terminology, but your copy suggestion was what I needed. I was trying to reference the layermasks directly, which wasn't working.
right you cannot reference a layermask because it is a struct which is a value type not a reference type. value types are passed around by value which means when you add it to the list it adds a copy to the list
I'm good now, dw about it. thanks tho
Given the displacement of a vector, how would you go about adjusting the position of a nested canvas object? because whatever im doing is not working.
I currently have https://hatebin.com/zoapdqkkap
is there any way to get pathfinding to bring the agent to the closest point possible, then stop, as stopping area stops as soon as the agent reaches the wanted area
Hello, please help me, this button is not displayed for me when using the Admob demo key, do I need to add it myself or is it generated by Admob when using a non-demo key?
It's part of the ad. If your ads display correctly, it should be present. Although I'm not sure about placeholder ads.
Might want to give some more details on what you're trying to do.
hes trying to make money
Reduce the stoping range🤷♂️
I did that, but the amount of agents moving to the target ranges, and they keep pushing to get to the target
Well, it's either one or the other.
If you want multiple agents to align nicely, you'll need some kind of group steering behavior implemented.
how would I do this, as I also need it to avoid obstacles
Look up flocking and steering behavior.
ok thanks
NullReferenceException: Object reference not set to an instance of an object
Unity.PlasticSCM.Editor.PlasticWindow.ClosePlasticWindow (Unity.PlasticSCM.Editor.PlasticWindow window) (at Library/PackageCache/com.unity.collab-proxy@1.17.2/Editor/PlasticSCM/PlasticWindow.cs:1014)
Unity.PlasticSCM.Editor.PlasticWindow.OnDisable () (at Library/PackageCache/com.unity.collab-proxy@1.17.2/Editor/PlasticSCM/PlasticWindow.cs:183)
?
What is this
Something about plastic and it's ui.
If it doesn't repeat, just ignore it.
ok
it only repeats when i start my game
Try resetting the windows layout.
If you're not using plastic, removing the package(version control I think) might also help
ok ty
A hint for flocking and steering behaviour in a performant way is by dividing your world into cells, so instead of calculating stuff for all agents in all world space, it would only calculate stuff within a world cell, which is many times faster. You may get more information of this on Boids algorithims
thanks
is it possible to set a breakpoint that stops the code when a certain variable's value is changed? i have a variable that mysteriously changes and i can't find where in my code it could possibly be changed
It's possible. Break somewhere where you can access the value first, then hover it - right click the floating variable field - break when changed(or something like that).
Then just resume execution and it will break automatically when the value changes.
Helo there, I want to know if this way of using my job is actually ineficient
I am calling this function over and over
so my concern is the result array and the dispose part of it
Is it way too ineficient to create and dispose an array each time?
I assume it is a heavy task
so I'm making a player upgrade system. Upgrades can be dependent on multiple previous upgrades. I'm trying to implement this system using a ScriptableObject but I'm confused on how it would work later when trying to actually fetch all of the upgrades for rendering them to a UI or applying their effects. Would I have to manually register them all or in a specific place, or is there a better paradigm to use?
https://pastebin.com/yVF86vm7 here's a paste bin of my code, but it is pretty messy and the custom editor is due to the fact Dependents is autoupdates and it looks bad cause I've never made a editor before
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 was busy the last few days creating some fairly difficult mechanics for my game, however ive now came to a point where 1 simple mistake can cause an infinite loop which causes freezing or unity selfpause or something. Any way how i can prevent such things? It started with a 'while' function which caused a freeze. I fixed that by implementing a break but now i stumble upon freezing without a while loop
And it is becoming more and more difficult because of like 15 scripts working togheter at 1 time and passing variables here and variables there trough all of the scripts. One complete mess
You'd need to provide context to get proper suggestions
Its pretty late ill provide some clips and scripts tomorrow while referring back to the message i send above.
hey I am having a problem with something I thought was simple. I am creating a list of bools and getting it to start with x amount of slots(4) but it is created and has no slots
List<bool> _condition = new List<bool>(4);
prints(0)
I just stick all my upgrades in individual lists and update my UI accordingly when acquiring new upgrades. As for applying their effects, you can go about recalculating and pre-caching the the ability data every time you get an upgrade, though you'd probably want to optimize it a bit if you've got much more than a handful of abilities and upgrades. And, then there's just applying the effects and calculations when being used which could lead to some performance issues when dealing with larger amounts of units. It's best to balance it around both of these if possible.
That's the capacity of your list not its count
That is the initial capacity of the list, ie. the size of the backing array when it's first created
You probably want to use an array instead of a list if you want a predefined fixed length
okay, thanks heaps. I'll try that.
Im definitely not planning to implement the system in a way that requires manual updating when any upgrade is added, I was planning to have an automatically drawn skill tree ui using LineRenderer components. But I first need to get a list - preferably automatically - of BasicPlayerUpgrade instances.
Anything that adds additional overhead that can be forgotten isnt preferred
One way or another the UI needs to know about the upgrades being added, so I'm not sure how you'd resolve that besides just refreshing the UI every frame.
anyone have advice for making a modular or polymorphic method of taking values from arbitrary value sources (floats, ints, float2's, 3's, 4's, lists of them, quaternions, etc...) and formatting them all into a 1 dimensional vector of floats?
right now my best guess is to have a class that maintains a list, with overloads to append it correctly for each datatype
and then list.ToArray() when i want the actual float array
since i have to clear and rebuild this list many times, im hoping to make it sensical
Would avoid using ToArray() as it cause memory allocation and produces garbage collection
i see
I'll definitely modify it to be a cached array of a given size then, and increase the size wen necessary
this means i definitely need the overload approach
thanks very much @plucky karma !
I was thinking of simple technique to render Directional light shadows
Basically the directional light is like a camera, and all places the camera doesnt see get shaded
Does this already exist? If it does what is it called
I have these 2 pieces of code which in my opinion must be equivalent but somewhy they aren't, could you please help me to find out why is that?
public class BodiesController : MonoBehaviour {
private Transform _head;
private SnakeMovement _snakeMovement;
private void Start() {
_snakeMovement = FindObjectOfType<SnakeMovement>();
_head = _snakeMovement.transform;
}
private Vector3 movementVelocity;
[Range(0.0f, 1.0f)] public float smoothTime = 0.5f;
private void FixedUpdate() {
var firstPart = _snakeMovement.bodyParts[0];
firstPart.position = Vector3.SmoothDamp(firstPart.position, _head.position, ref movementVelocity, smoothTime);
firstPart.LookAt(_head.transform.position);
for (var i = 1; i < _snakeMovement.bodyParts.Count; i++)
{
var curPart = _snakeMovement.bodyParts[i];
var previousPart = _snakeMovement.bodyParts[i - 1].position;
curPart.position = Vector3.SmoothDamp(curPart.position, _head.position, ref movementVelocity, smoothTime);
curPart.LookAt(previousPart);
}
}
}```
public class SnakeBody : MonoBehaviour {
private static float overTime;
private int _myIndex;
private Transform _head;
private SnakeMovement _snakeMovement;
private void Start() {
_snakeMovement = FindObjectOfType<SnakeMovement>();
_head = _snakeMovement.transform;
_myIndex = _snakeMovement.bodyParts.IndexOf(transform);
}
private Vector3 movementVelocity;
[Range(0.0f,1.0f)]
public float overTime = 0.5f;
private void FixedUpdate(){
if(_myIndex == 0){
transform.position = Vector3.SmoothDamp(transform.position, _head.position, ref movementVelocity, overTime);
transform.LookAt(_head.transform.position);
}
else{
transform.position = Vector3.SmoothDamp(transform.position, _head.GetComponent<SnakeMovement>().bodyParts[_myIndex-1].position, ref movementVelocity, overTime);
transform.LookAt(_head.transform.position);
}
}
}```
SnakeBody works correctly, while BodiesController doesn't
SnakeBody behaviour
BodiesController behaviour
In the first snippet you move all of the parts towards the head. In the second code you move parts towards the preceding part aside from the one that has index 0.
Now it is
curPart.position = Vector3.SmoothDamp(curPart.position, previousPart, ref movementVelocity, smoothTime);```
But now I get this behaviour:
Have very slow internet ATM, so can't view your video.
In short, works incorrectly too
is this the right area to ask a question about occlusion culling? can anyone help?
I managed to build something that allows me to blacklist folders in my build pipeline
chopped off about 20mb from each build so far, just a matter of finding the problematic assets for each build type and adding their paths to the blacklist
helps me gut out client specific content from headless servers etc.
If it involves coding and it isn't advanced or a beginner topic, then yes
is there a way to make the camera input a texture instead of a scene?
I am using camera.targetTexture to render to a texture, and using that same texture as a material to a cube in my scene.
however, the camera takes its input as the scene view, what I need is a way to make it render a texture to that target texture, and not render the scene.
the main reason for using the camera this way, is that it automatically rescale and workout out of the box nicely
Cameras are objects in scene. If you require it, there isn't much choice.
Else you could blit to convert from texture to render texture but I'm unsure if you'll get what you're wanting.
I tried doing so, but it seems that I can not blit directly to the targetTexture of the camera
var rt = new RenderTexture(640, 640, 32);
Graphics.Blit(tex2d, rt); // the image I want to render to the targetTexture
Graphics.CopyTexture(rt, cam.targetTexture);
I think you would get an error with the above as targetTexture is a property and being used for reading in the above.
expected so, but did not get any warnings or errors
alternatively, (but google did not show much on it)
how do I create and apply a material that is based on a texture?
this will remove the usage of a camera for me.
then I will basically, load the image in code, to a byte array, and just change it as needed.
I'm uncertain but just be aware that constructing a RenderTexture doesn't actually create it - you'll need to Create to create the render texture.
https://docs.unity3d.com/ScriptReference/RenderTexture.Create.html
kind of solved the issue, but I just removed the camera and created a material on the fly
Hey, silly question. Does anyone know how i could decrease the probability of an object spawning when it gets further away from a position? I would like the probability to be 100% when the distance between the object and it's spawn point is 0, and 0% when the distance is 1.
if you have a max distance,
let's say 1000
then
just get the distance, and divide by the max distance,
or you can check if the distance is more than max distance, in this case, just set it to 0
sure, you just need a linear formula for it
though in this case, the probability shoulf simply be 1 - distance
ok ill try it out
Like this?
float chance = position.magnitude / (position.magnitude * maxSpawnDistance);
why multiply it
actually
hang on
are you proposing this?
float chance = position.magnitude / maxSpawnDistance;
I suppose some more info is needed. I'm trying to affect the chance of spawning a star. I want more stars toward the center of the sphere and less toward the edge.
private void GenerateSphericalGalaxy()
{
for (int i = 0; i < spawnTries; i++)
{
//Get random unit position
Vector3 position = Random.insideUnitSphere;
//Calculate spawn chance based on distance from center
float chance = position.magnitude / maxSpawnDistance;
//Squash factor
position.y *= squash;
VirtualTransform vt = new VirtualTransform(position);
virtualTransforms.Add(vt);
}
}
try
float chance = 1f - (position.magnitude / maxSpawnDistance);
Alright. Thanks for the help so far guys. Any idea how I could take that chance variable and use it to decide whether to spawn the star or not?
perhaps ```cs
if (chance > 50f) {
//spawn the star?
}
chance will always be between 0 and 1
simple way
- Round chance to 1 decimal place
- Get Random number between chance and 1f
- round that number to 1 decimal place
if number == chance spawn
you could play around with the rounding to give more variation
dont forget to convert it to an int
you cant reliably use == on floats
better. multiply by 10 then convert to int
sounds good. im gonna work this out. ill let you know how it went. thanks
i believe you can simply if (chance>0.5f)
that will not give linear progression
thats what i had originally
i accidentally typed 50 in chat
@knotty sun is right
I just tried this to no affect. ```cs
float chance = 1f - position.magnitude / maxSpawnDistance;
float rnd = Random.Range(0f, 1f);
if (chance > rnd)
{
VirtualTransform vt = new VirtualTransform(position);
virtualTransforms.Add(vt);
}```
Anyone know how to fix my canvas being bright 😆 https://i.imgur.com/2JvuFAr.png
float chance = 1f - position.magnitude / maxSpawnDistance;
int i = (chance * 10f);
int rnd = Random.Range(i, 11);
if (i == rnd)
Don't cross-post
ok sorry
you cannot access GameStatus using the class name you need to get a reference to the class instance
@knotty sun that also didn't work. thanks though.
why not?
It may work. maybe just not exactly what im going for. I'll mess around with it.
it's definitely working but it's not spawning enough stars. propably just have to multiply chance though
This appears to be bloom, but you probably already knew that. This is why it's best to have a bloom threshold of 1 or greater. What's happening here is that the white background is probably fully white rgb(1.0, 1.0, 1.0). If your bloom threshold is below 1, that white color will always have bloom added to it. To fix this, you have to enable HDR on your camera, so that pixels can be brighter than 1. Then you can make your bloom threshold > 1.
Alternatively, you can also look into changing the order of your UI rendering to come after and on top of post processing.
if you want to increase the chances then add
int k = rnd - i;
if (k < 5) // for example play with this number
{
spawn
}
I have a question, i have a child object which has a collider that works as player collider. But a parent object has a rigidbody. The thing is that when a bullet colides with the player it collides with the parent object. Does the collider have to be in same object as rigidbody?
its pretty standard code that im pretty sure worked in earlier stages
anyone know how to make dotween work when time scale = 0?. i try to use .SetUpdate(true) but it not work
Please configure your !ide first
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.
I didn't know that actually, first time using HDRP. Where do I enable HDR on the camera?
I've noticed that it's because it's screen-space camera and the it's very close to the camera which is making it bright
How do I get rid of DDOL after player dies? I want to load menu but the player stuff comes with it.
I don't know much about HDRP either. You could try asking in #archived-hdrp. This seems like it would be a common issue.
Ah didn't see that topic, thanks
any1?
You'd have to destroy it manually, by getting a reference to the objects and calling Object.Destroy on them.
Sounds like you're not supposed to use DDOL
If you have an object that uses DDOL, it is assumed that this object is never destroyed
In your case it is destroyed when the player dies
So, you can make your own additive scene, call it "player context scene" or something. This contains everything that must exist until the player dies or is removed. When that happens, simply unload that scene.
You might want to make whatever you put in it a singleton, and ensure that its instance reference is removed so that it is fully reclaimed by Unity. Note that you can't set a SerializeField with objects from another scene, hence why this is probably the best you can do. You can then reference that instance when the player exists and do whatever you want to do.
Also, it sounds like you should split player stuff and your menu stuff in general
If there are dependencies between the two, you could make these split objects communicate with a parent object when it comes to retrieving shared data.
I kind of solved it by destroying the objects when player dies
and for the moment it works
That's still a bit of a bandaid
Hello, does anyone know how to replicate this scaling tool (where you can scale it from the corners) in runtime?
Could you not use a grid layout?
Does it work with different sizes?
Image is empty for me. But you can set the cell size
Yeah but all cells have different sizes
public class ChangeRT : MonoBehaviour {
public RectTransform MyRT;
void Start()
{
MyRT.anchorMin = new Vector2(0.f5,0.5f);
MyRT.anchorMax = new Vector2(0.6f,0.6f);
}
}
could this work?
Yeah, but i'm trying to make it function like that tool, which means that you can scale it in runtime from it's edges
Where can I find informative documentation about perlin noise generation that consists of informations and examples for each step of the generation?
From where? Unity.Mathematics?
Or are you just asking about Perlin/Simplex noise in general?
Not sure I understand the problem but it also doesn't seem code related
You are correct, my bad
Are you like interested in the math behind it?
Yes. Well, in the basic level. I'm not too interested in how the smoothing functions work exaclty for example, but I would like to know the fundamentals of noise generation to the point I would be able to generate it on my own.
This page was alright but not informative enough code-wise. Also it didn't explain what "input points" are, nor how many should I use, but jumped right into the vector math
I suppose you can just do some googling then and see what you find
some article or video
Do you know any discord servers made for procedural generation or computer graphics, so I can ask specific questions there?
Because it seems this server is more unity focused
we have plenty of channels, take a look at them
I didn't see #⛰️┃terrain-3d, maybe there will be more relevant. Although I am still not expecting much knowing there's a built-in perlin noise function in unity
I think general programming and algorithm questions are fine in this server too
They might be fine, people might just be less knowledgeable when it comes to programming outside of unity
Hello everyone, do you have some link to search for nfc in unity ? I already did seek Twisprite plugin, but it doesn't launch my unity activity and i would want to understand each step. (Not a frequent user of android studio for .aar)
Ok so hey everyone, I have a very simple question. I'm using the pro builder to make an appropriate map for my game, right now I'm trying to make proper walls to surround the area, but I'm able to just drag the line across the terrain rather than lock it and have it move from block to block (so that I can do it more precisely). Can anyone tell me how to switch it?
Ohh ok thank you
If anyone here knows anything about procedurally drawing lines, i wanna write a script that draws a pixel line from the hook to the fishing rod as the hook moves. Any suggestions?
Is there a way to completely destroy gameObject?
With simple Object.Destroy() unity still saves some of the object data if there is a reference to it.
How can I completely delete object from memory even if there are references to it?
LineRenderer is a good place to start - using a custom material/shader to make it "pixellated"
Unity doesn't save any references to it
The only references that might remain after calling Destroy are references in your own code
what is the problem that you're trying to solve here?
There is no way - in any programming language as far as I'm aware to automatically find and ... what would you even do with existing references? Set them to null? That's very destructive
It is.
I still can call methods of component of destroyed GO.
that's references in your code
