#archived-code-general
1 messages · Page 36 of 1
ok so i'm still very confused
let me elaborate on a few things:
my game isn't exactly a rhythm game but more of a bullet hell game i'd actually say, stuff like lasers appear at certain positions and at certain timings and with certain attributes, so how would i put all of that into something i can then read and build?
Did you try to make a prototype level first to see how the game works?
That's the challenge you need to solve, and it really doesn't matter that it's not a rythm game.
Just imagine a list of instructions:
"at time 1s, spawn a red laser at position xyz facing direction xyz",
"at time 2s, spawn a green bomb at position xyz with a 5 second timer",
... and so on
This is basically something like List<SpawnInstruction> in code. (where SpawnInstruction is a class you make).
Get it?
yup, by uhm... yeah
ok yeah that actually makes sense
oh yeah that makes so much sense
then of course you need to make:
- code that can produce this list from the "level editor"
- code that can read this list in order to "play" the level (this is the actual game code)
it's not trivial, it's a good amount of work, but that's what would go into it
that sounds quite fun
and you need to be able to read/write these instructions to files
If you want to do something like that I would recommand implementing the Command Design Pattern to do the timings
wonder if compiling audio and image files into a file is possible
to have the song and any of the sprites be able to be saved with the level and easily shared
Is using reflection like this a fine thing to do, or the kind of thing you want to avoid if possible?
did you write this
I don't... see what it's actually doing
it's setting the fields to their own values
it's basically just copying a prefab as a component
i got one!
beyond that it doesn't seem to do anything more than AddComponent
it's not copying anything
i'm only hitting 1/3 i think
I would expect a parameter for the thing to be copied in that case
it's a situation where you want to add a component of DerivedClass (generic) and propogate its abstract fields
what is your goal?
Honestly if you really want to copy a component I would do this:
public static void CopyComponent<T>(T source, GameObject targetHost) where T : Component {
T newComponent = targetHost.AddComponent<T>();
string json = JsonUtility.ToJson(source);
JsonUtility.FromJsonOverwrite(json, newComponent);
}```
Well basically I'm applying a status effect by just feeding in an enum StatusType. Then a class fetches the prefab of the appropriate status and adds a component of DerivedType (the particular status), then fills the abstract fields
it's probably not the best architecture, but it should work fine
I don't know anything about reflection though, or if it's used that much
The JSON string is fishy but Unity doesn't give us access to the binary form of its serializer sadly
chatgpt, make a new unity with public binary forms of the serializer
(this'll take a sec)
I am curious to see what I am doing wrong here. Basically, I want to have a raycast that goes up and down at certain timing to see if the cube is at the right place on the map/on the right object.
Does someone have an idea of what is happening here on the coordinate ?
DrawRay expects a position and a direction
you're giving it two positions
maybe use DrawLine instead
which does expect two positions
So what would be a direction in this context?
a direction... is a direction
like Vector3.up
is a direction pointing up
transform.up is a direction that is the object's local idea of "up"
Ho thank you!
so wait can't i just literally have a class with properties like startingPosition, startingRotation, timing etc, put these classes in a list and then have a script that goes over this list and spawns objects with these properties? that sounds quite easy?
yes
it will be tricky when you want to have different types of objects though
but that's the basic idea yah
Yeah, I just deleted that part 😅
probably not a problem since all of my objects are the same thing but with different sprites and collisions
easy then. You could for example just have an enum or number or something that identifies various prefabs and include that as one of the properties of your class
how can i know in code when I just saved something in Visual Studio, and while the Unity game/editor is running I click into it and trigger the "reload scripts" popup?
i've got a UnityUI scroll rect with some inertia but it also responds to scrollwheel input. If you "flick" the rect and it's .. inertia-ing, scrolling with the mouse wheel will click the rect up/down one click, but then keep on moving from the inertia. is there any built-in functionality in this component to prevent that? or do I need to hook OnValueChanged and stop the movement
i think it's called "hot reloading"?
so say I have a compute shader with a #define in it
is there any way to change the #define automatically from script? I want to be able to go between HDRP and Built In without seperate code for both
you'll have to modify the ScrollRect source to kill the inertia :/
cba i think. 😦
it's probably fine.. it's a little clunky but i think either people are gonna use the scrollwheel or click and drag, but not both (for windows)
i'm guessing it's not possible to have dictionaries created in editor mode accessed in play mode. My editor mode populated dict is empty once play starts even though I never empty it in runtime
as far as I know you can? i don't tend to expose dictionaries in the editor
It is, you just have to use a special serializable dictionary implementation
thanks
Anybody here can point to a way to make the player follow along the wall when moving against it ?
What I tried only works if the player is pressing w+a or w+d etc
wanted to know if its possible to only press w and slowly slide right or left depending on the angle
Which one of you is a rigidbody expert?
Just ask the question
Ya know...Instead of saying that, you could say "I might know something, whats up?"
Hmm ok Ill ask there
So you're going to waste the time of everyone who bothers to get to you. What if they don't know?
If you're in a discord, chatting, chances are you have time to waste and I am not going to be rude
Blatantly asking outright is rude
It's not really. I suggest you read that article
well that just shows you didn't bother clicking the link
Anyway, Im gonna go to the other chat. I just need help, not an argument
I get the intention, but this is a text medium. You're not interrupting anyone
knowing about rigidbodies doesn't mean they'll understand or be able to help, but just posting your question and the problem you're having will allow them to check if they can help or not. that's all everyone is trying to say . . .
it takes 3-4 mins to run my game in editor 😦
Hello !
I am currently trying to code a depth first search in Unity to generate a maze
I have the code with me given by my teacher but i am confused in some places and would gladly appreciae some help
- Why do I need a private field to generate random numbers?
he asked that question? (number 1)
what would this block of code do?
why am i shuffling the directions ?
and why is it %4?
To pick a random direction to carve into
why would i need a random direction? because doesnt rhe DFS explore all neighbours
And the modulus would be to get the opposite cell's wall to remove
And you get a random direction so you don't always carve towards the right for example
If you didn't shuffle, it would be biased because it would always start carving towards the same direction, creating weird layouts
Got the logic for the %, it indeed gets the opposite side of the adjacent cell.
+ 2 + | + 2 +
1 3 | 1 3
+ 4 + | + 4 +
Say you carve right, that side is labeled "3". To get the opposite wall on the cell on the right, it does 3 + 2 % 4 which gives out 5 % 4 => 1. That's indeed the wall on the left, of the cell on the right!
what do you mean by modulus?
ohh that makes a lot of sense now!!
The percent operator is "modulus", it's the remainder of a division
5 / 4 => 1, remaining 1
also what do you mean by "you" in "you wont carve into a direction?"
oh right so the remainder
Yep
right
thank you so much for all your help! i truly appreciate your time
And by "you" I meant the algorithm lol
ohh rightt
If it always carves in the same direction you'll get a lot of straight lines, and that's not very maze-ish
That's why it needs to shuffle the directions
It eliminates as most straight lines as possible
Actually yeah your maze will be all straight if there's no shuffling at all, it won't be random aside from the start point
ahh right
thanks !
Hey all, I'm having an odd problem here. I had a script written for a recoil system and had it attached to a firearm, all was fine. Out of nowhere the attached component changed to "Script" and said please fix any compile errors in the script. I hadn't changed anything on that particular script and there's no compile errors in it at all. I can't add the script as a component anymore and I'm going crazy trying to understand why
Make sure the class name matches the file name it's in
A class Recoil must be in a file Recoil.cs
If that's the case already, move the file to another folder within Unity, and back. This will force Unity to do a full compilation, hopefully fixing the issue in the process
Sometimes it doesn't pick up changes made to your code
"there's no compile errors in it"
Does that mean that there are compile errors in other scripts?
Nope, none at all. I can still run it from the editor and no compile errors in any script I have
Please check all the stuff I mentioned below your question
If there's no compile errors, then it must be the file/class name as SPR mentioned.
Just triple checked, the class PhysicsRecoilSystem is in fact PhysicsRecoilSystem.cs so there's no disconnect on the naming
I tried moving the script in folders as well to force a recompile, still not picking it up as a valid component for some reason
Take a screenshot of your console.
Omg, easy fix. Intellisense must have made it an abstract class at some point which wasn't intended
I can't think of anything else as it does wonky things sometimes that need fixing and I definitely didn't do that myself
Yes. Abstract classes can't have instances.
Intellsense doesn't do something like that though.
Mine does lol. It sometimes suggests alternate code when I highlight something and pressing tab instantiates it. I sometimes run back through something and find an incorrect implementation or variable. I've had it suggest names that don't exist yet when declaring variables that sometimes throws me off
Are you using Copilot or something? I don't think the VS2022 ai assistant gives suggestions for editing existing code...
In fact, I don't think copilot does that either.
I recently started with VS2022 as VS2019 was giving me an unusual amount of problems and warnings. Still a list of warnings with VS2022 but my intellisense by default suggests new variables as I'm naming them and sometimes creates its own
It doesn't seem to do it in an established document, but upon making a new script it suggests naming conventions for me
Yeah, that's the ai assisted suggestions. Although I've never had it make changes to existing code.
It usually only does it if I accidentally hit tab to autocomplete though sometimes it does insert code I didn't want, such as [SerializeField] that I need to erase before typing a regular variable declaration
you can turn off the AI assisted stuff
I found it very annoying personally
I do like it to avoid mistyping existing variables but damn... sometimes it does some weird things lol
AI assisted stuff is not the same as regular intellisense (autocomplete etc)
you still get regular intellisense without the AI stuff
I'm about to look it up, if I can keep intellisense without the AI suggestions I'm all about it
I do find it useful. Especially if I have to deal with somewhat repeating code.
did
make intellisense show copilot completions by default?
It's not copilot afaik. It's not pretrained on a large set of code. It gets trained on your project as you develop if I get it right.
Maybe not trained. But it doesn't give any complete code suggestions. Mostly just based on stuff that you already have in your project.
I'm having a very very odd problem. I have a humanoid animated character. I have a capsule collider on it. Whenever I enable the animator, the character like offsets itself
and like raises himself above the capsule collider. Only happens when I enable the animator
root motion is off
presumably the animator is setting the position of the root object
root motion off doesn't mean "don't animate the root object"
it actually kinda means the opposite. It means "allow the root object to be animated while still allowing external motion in the world from other means
Alright thanks
hey,
is it possible to check if objectA and objectB colliding from objectC ? .. meaning the check function is on objectC not on A nor B??
If you want to use the collision callbacks they have to live on one of the objects involved in the collision
alright , thanks 🙂 , i had an empty script i was gonna add the function there but alright 😄
I might have a memory leak or some high memory use in one of my animations, so I'm wondering what the best approach to tween a value in a particle system over time would be? My current approach:
public IEnumerator BrakesCoroutine()
{
const float BrakesAnimationDuration = 6f;
Sequence seq = DOTween.Sequence();
seq.Insert(0, DOVirtual.Float(MovingStarsEmissionRate, 0, BrakesAnimationDuration, (f) => SetMpsEmissionRate(f)));
yield return seq.Play().WaitForCompletion();
ResetMPS(); // Sets back to starting value
}
private void SetMpsEmissionRate(float f)
{
var mpsEmission = MovingParticleSystem.particles[0].emission;
var mpsEmissionROT = mpsEmission.rateOverTime;
mpsEmissionROT.constant = f;
mpsEmission.rateOverTime = mpsEmissionROT;
}
Is this leaky or problematic..?
Not really. At least not by itself. Where do you start the coroutine?@modern creek
It's a little more complex than I can describe in a sentence, but .. basically a singleton is emitting a static event.. I'm just sorta confused by this leak, if it is one
I can't repro it on my machine but one of my coworkers can consistently crash his machine with this area of code
his unity.exe just stops responding and dies - no stack trace, no logging, just.. stops rendering, uses more and more memory, then dies
normal looks like this:
exact same version, workflow, etc
https://pastebin.com/gx1PGJGd At first I thought maybe I was mistakenly emitting an event every frame or something like that, but I've got some logging in place ("Brakes requested") that indicates it's getting called the proper number of times (once)
Does that happen in a build only?
is there a way to make your character move the same speed as navmesh agent when they're set to the same number?
say navmesh agent speed is 5 and the character I control also set the speed to 5, then they will have the same speed
Did you confirm via the logs that the coroutine is only started once? Was that confirmed during the issue?
Yeah.. he's running the same version as I am.. his logs just say "Acceleration requested" and then stop
I'm not entirely sure it's here that's the problem, but .. this is the last line in all his logfiles so it seems like it is? I'm not having much success assessing this one
the "First tap event invoked" line is the singleton emitting the event
Does his game also freeze?
hm, it might be another issue.. I've got this one script that's doing a long running coroutine (30-60 sec) and restarting itself (basically the ship slowly "wobbles" around the center). When you get to a destination though it starts a new set of coroutines (pseduocode below):
public void OnArrivedHandler()
{
StopAllCoroutines();
StartCoroutine(WobbleShipCoroutine()); // <-- does this not work because of the previous call to stop?
}
yes, his game freezes.. sorta.. the music keeps playing, but the update loops don't come anymore (screen goes white, game freezes)
it feels like an infinite loop but.. i'm running the exact same code so i don't understand how
in fact, the codebase is guaranteed identical since the multiplayer server gates connection based on version/build
I'm doing that sort of thing elsewhere - is it possible that those start coroutine calls are ... multiplying? 😛 my early exit clause there isn't returning, but i don't see any of these error messages (w(""))
For starters you could use the memory profiler to find out what's eating the memory. That would probably give a clue on what's going wrong.
yeah i've been playing with it but it's .. not showing me anything obvious.. you're talking about the com.unity.memoryprofiler one? experimental?
Any would do. Obviously, you need to profile when the issue happens.
Yeah.. I think therein lies the rub - can't repro it on my machine .. I hate to be a meme but "it works on my computer" makes it pretty hard to debug this
Ah well, thanks for having a look.
Can't your colleague do it?
nah he's a designer
the lack of any log messages or crash dmp for him to give to me sorta hamper it
if it just straight up crashed, at least I'd have a stack trace to explore
var results = persons.GroupJoin(
phones,
person => person,
phone => phone.Person,
(person, phoneEnum) =>
new {
person.Name,
PhoneNumber = string.Join(',', phoneEnum.Select(x => x.PhoneNumber))
}
);
hey hello! this is an example of linq group join
i dont understand why is the last parameter IEqualityComparer but it isnt implementing a proper comparison method
please help?
(2D) How do I pass in a rotation to a bullet towards the player? I have this right now but it only goes 90 deg to the right no matter where my player is to the enemy.
IEnumerator ShootBullet()
{
Vector2 direction = _player.transform.position - this.transform.position;
Instantiate(_bullet, this.transform.position, Quaternion.LookRotation(_player.transform.position, transform.right));
yield return new WaitForSeconds(reloadSpeed);
_isShooting = false;
}
Try asking what exactly they did that led up to the issue and try reproducing the exact environment of the issue occurrence. It's very unlikely to be an issue with their machine.
IEnumerator ShootBullet()
{
//not used
// Vector2 direction = _player.transform.position - this.transform.position;
Instantiate(_bullet, this.transform.position, Quaternion.FromToRotation(transform.position, _player.transform.position));
yield return new WaitForSeconds(reloadSpeed);
_isShooting = false;
}
?
It could be a consequence of hardware difference in terms of performance. For example the bug could be occuring at certain fps.
last bump (Help pls)
Hm.. Is there anything wonky about how coroutines work and are scheduled? Is it possible that I'm starting a coroutine but it's just getting added to some list for later processing, which doesn't run or is dropped for some reason - and so the later calls (which normally are fine because the first line of the coroutine checks to see if it's already running) just stack up more coroutines starts..?
ie:
void Update()
{
if (!isRunning) StartCoroutine(SomeCR()); // could this fail or add multiples under load..?
}
private IEnumerator SomeCR()
{
isRunning = true;
... do some stuff ...
}
Have any idea why the trajectory is a bit off sometimes?
It could theoretically fail if you set it to false somewhere else.
It would be a better approach to assign the new coroutine instance to a class field and try stopping it before starting a new coroutine.
Suppose I have an animated first person character. When the camera is parented to the head, there's a lot of jarring shaking going on. How is this normally stabilized? Two skinned mesh renderers with one animation on and the other off and just have them overlap each other? With the camera parented to the non animated invisible skin?
Yeah.. I'm always so lazy, if there's only one "thing" going on in a script i just StopAllCoroutines() instead of tracking it and surgically stopping it as appropriate.. but that sounds like a better way here, especially if I'm worried about it being fragile or potentially buggy for some reason
With StopAllCoroutines you should also make sure that you don't start coroutines on a different object, because that wouldn't stop them.
yeah, i never do that
a long time ago I used to make these monolithic "screen" monobehaviours that orchestrated all kinds of nonsense.. coroutines.. tweens.. particle effects, etc. When they started hitting like 2k lines and being super hard to debug I started going hard towards the "one MB for one tiny little thing" approach and it's been much better
But as far as coroutine execution goes, it acts as a normal method at StartCoroutine. When it reaches the yield return, it stops execution and continues it later depending on what was returned.
K.. I wasn't sure if "startcoutine" internally just added the method to a list of delegates for later (in the frame) execution
but that would probably be crazy confusing if you were doing things like
StopAllCoroutines();
StartCoroutine(someCR());
StopAllCoroutines();
private IEnumerator someCR()
{
log("hello"); // never happens in this upsidedown world
}
Yeah, if it was like that there would be numerous issues.
Hey, I have been having issues trying to get only one of the little guys going to each cube, but I can't figure out how to reference each specific cube prefab
so they all just run to the latest cube
how should I go about making it so one goes to each cube?
track them in a list
also they're not prefabs when they're spawned
only the one original in the assets folder is a prefab
oh i see, thank you
Hello. I am new at using C# and I'm following a series on YouTube but unable to continue due to an issue I have faced. Am I able to post it here?
Hey guys, quick good-coding-practise question about how to handle values that get set for x time by multiple sources:
Say I've got a bool that represents whether a player's inputs should be read or not. And this bool can be temporarily set to true by a bunch of different scripts and functions and such. What is the correct way to do this? One issue could be if 2 different coroutines are running, one sets it to true, then another sets it to true just as the first one was about to set it to false. How is it meant to know something else tried to set it to true since it did? I've thought of a couple of different approaches, I just wanted to ask which was the best.
- Create an int buffer that counts up every time that the value is changed, and then each coroutine stores its own local value to compare against, and will break itself if the buffer value is higher than the local one.
- Create a bool for each individual coroutine which a function then checks and essentially does an OR check on every bool.
Or alternatively, please tell me any other approaches that may take advantage of C# features I wasn't aware of. I'm not looking for the most optimised or anything, just the easiest to read and cleanest solution. Thanks for hearing out my question.
- The owner of said bool should make that bool
privateand only allow access to it through public methods which do the right thing in all cases
damn praetor sounds like a pro
How would that prevent the issue I mentioned though?
I don't really understand the issue because you are talking about some stuff from your code without context
you'd still have multiple versions of the one coroutine running simultaneously
okay i can try write up a quick example
what you did mention did give me an idea id never had though
ill keep that in mind for what i write in the future at least
hang on ill write what I mean
What I'd say with the limited info i have here is that the obejct that owns this bool should also be managing these coroutines probably
but yes please do write up your example
hey praetor I have a quick question, what's the easiest way to make the list for the gameobjects spawned from the prefab, and how to reference each one?
I'm a little new to unity
List<GameObject> instances = new();
and when you spawn an instance you do:
GameObject newInstance = Instantiate(thePrefab);
instances.Add(newInstance);```
I've realised 2 wont work for coroutines that might be running multiple instances simultaneously
public class Problem : MonoBehaviour
{
private bool freeze;
public IEnumerator TempFreeze(float time)
{
freeze = true;
yield return new WaitForSeconds(time);
freeze = false;
}
}```
thats the problem
public class Example1 : MonoBehaviour
{
private bool freeze;
private int tempFreezeIndex;
public IEnumerator TempFreeze(float time)
{
tempFreezeIndex++;
int ownIndexBuffer = tempFreezeIndex;
freeze = true;
yield return new WaitForSeconds(time);
if (ownIndexBuffer == tempFreezeIndex)
freeze = false;
}
}```
thats my first solution
its messy
this is definitely overcomplicating it
whats the better way to avoid clashes like that then
well first let me ask you
when someone wants to freeze for x seconds
and there's already a freeze going on
what do you want to happen?
how long should the freeze last
that needs to be variable
let's say there are y seconds left on the existing timer
and they want to freeze for x seconds
do we freeze for x seconds?
Or x + y?
we just want to remain frozen until nothing wants it to be frozen anymore
private bool _isFrozen;
public bool IsFrozen => _isFrozen;
private Coroutine currentCoroutine;
public void Freeze(float time) {
StopCoroutine(currentCoroutine);
currentCoroutine = StartCoroutine(FreezeCor(time));
}
private IEnumerator FreezeCor(float time) {
_isFrozen = true;
yield return new WaitForSeconds(time);
_isFrozen = false;
}```
so this is a very simple way
as I said - this thing should be managing the coroutine(s) and the freeze variable
all internally
only allow access through very specific public things
hang on let me write one more thing real quick
also importantly, this object is starting the coroutines itself.
hey praetor, am I able to reference each specific spawned gameobject? like name them worker1, worker2 etc?
public class Example2 : MonoBehaviour
{
private float m_FreezeTime;
public bool frozen
{
get { return Time.time > m_FreezeTime; }
}
public void SetFrozenTime(float time)
{
m_FreezeTime = Mathf.Max(m_FreezeTime, Time.time + time);
}
}```
is there a reason I shouldn't do it this way instead?
that's not the worst idea.
I generally just shy away from using Time.time in general for floating point precision reasons.
yeah thats also true
though if you use https://docs.unity3d.com/2021.2/Documentation/ScriptReference/Time-timeAsDouble.html it's probably not a concern ever
It becomes a concern with float after about 6-8 hours of gameplay, yeah
How are first person characters generally done? I can't parent the camera to the animated head because then you get really jarring visuals. Is it common to use 2 character models? One invisible without animations and the other visible with animations? And then the camera goes on the invisible non animated model?
depending on how accurate you need it to be
i'd imagine time as a double would get into ludicrous amounts of time though right
yeah timeAsDouble would be fine
😁
no need to run any code every frame
(all coroutines require at least one check every frame
generally there's not much of a player model for first person games, and definitely not an animated head
The point would be to cast shadows
and to see the lower half of your body
I see
I'm trying to visualize the bounds of a sprite by drawing gizmos but this one isn't appearing:
private void OnDrawGizmos(){
Vector3 top_right = new Vector3(_length, 0, 0);
Vector3 bottom_right = new Vector3(_length, _lengthY, 0);
Vector3 bottom_left = new Vector3(0, _lengthY, 0);
Vector3 top_left = Vector3.zero;
Gizmos.color = Color.yellow;
Gizmos.DrawLine(top_right, bottom_right);
Gizmos.DrawLine(bottom_right, bottom_left);
Gizmos.DrawLine(bottom_left, top_left);
Gizmos.DrawLine(top_left, top_right);
}
seems like you are confusing size and position, no?
When I build my project with Addressables, it complains about a bunch of Unityeditor namespace stuff, because it doesn't compile with the UnityEditor namepsace. Is there a define symbol for compilation?
is that your code? or a package or something?
Seems like maybe you're using Editor-only stuff in non-editor code perhaps?
Yeah, I can't put it in an Editor folder because it references classes in my main assembly. and yes thast is my code
you can reference classes from your main assembly from an editor-only assembly
make an assembly for the editor only code and have it reference your main assembly
oh, i see
I realise this solution doesn't accommodate for when it needs to be frozen for an indefinite amount of time, so I've gone and changed the frozen code:
public bool frozen
{
get { return Time.timeAsDouble > m_FreezeTime; }
set { m_FreezeTime = value ? double.MaxValue : 0; }
}```
In my case there aren't a lot of clashes between indefinite-time-freezes, but I think i might add another value to represent indefinite time freezes instead just so indefinite time freezes dont overwrite whatever is happening with how long its frozen for the definite-time freezes
Oh right it should be relative to this.transform
wtf it mean "never assigned to" i literally assign to it
How do I check if a list contains an object, rather than a specific instance of an object?
what do you mean exactly
an object is an instance
if you want a definition of "sameness" besides "literally the same object in memory" you need to make your class or struct implement this interface:
https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1?view=net-7.0
List will respect this equality
Inventory.Contains(item) only seems to return true if the item being checked is the same as the instance of the item stored in the List. Two identical items won't return true and I want it to, if that specific item is contained in the List, regardless of its instance.
yes this #archived-code-general message
Hey praetor, quick question, for the list is there an easy way to say spawnedobject1 do this, spawnobject2 do this etc?
im just having trouble numbering them
myList[0].DoSomething();
myList[1].DoSomething(); etc.
typically you would be doing that in a loop or something though
very rare to hard code numbers like that
yeah idk if im an experienced enough coder to NOT hard code this lol
If you're hardcoding it it kind of defeats the purpose of the list
i want each of the spawned objects to have its starting position on top of each spawned objects from a different list lol
hard to wrap my head around how to do that properly
with a for loop
for (int i = 0; i < differentList.Count; i++) {
thisList[i].transform.position = differentList[i].transform.position;
}``` something like this?
hmmmm
unclear if you're trying to spawn these things in the loop or just position them
this is the code im looking at. essentially for each woodhut placed i want a worker to spawn at it
building.targetpos1 is set to the centerposition of the woodhut, but if there's multiple woodhuts then all the workers spawned get placed at the most recent woodhut
isn't player.buildings[i] the hut in question?
what is Building? And what is targetpos1?
(generally it's a red flag when your variables have numbers like that btw 😉 )
lol yeah, i kinda half followed a tutorial then did my own thing
your variable names are kinda crazy
why is a variable that seems to represent the position called "worker"
that's so confusing 😵💫
how about "workerPosition"?
lol yeah that seems better
'Building' is my first list, where you can place different buildings
but for the specific building 'woodhut', i want a worker to spawn at the center of it
but when there can be more than one woodhut placed, that's when all the workers go to the last placed woodhut
does anyone know why this code doesn't work? all the directories exist
void Shift()
{
Debug.Log("Attempting shift");
AssetDatabase.DeleteAsset(@"C:\Users\Cameron\watchmealways\Assets\Scripts\script.txt");
AssetDatabase.DeleteAsset(@"C:\Users\Cameron\watchmealways\Assets\mp3Files");
AssetDatabase.MoveAsset(@"C:\Users\Cameron\watchmealways\Assets\Scripts\newscript.txt", @"C:\Users\Cameron\watchmealways\Assets\Scripts\script.txt");
AssetDatabase.MoveAsset(@"C:\Users\Cameron\watchmealways\Assets\newMP3s", @"C:\Users\Cameron\watchmealways\Assets\mp3Files");
}
define "doesn't work"?
what happens?
don't think file extensions is needed
nothing
yeah it prints
that's why I put it in
oh I have an idea I'll put one at the end
maybe it just takes a while? idk
nah your paths are wrong
All paths are relative to the project folder, for example: "Assets/MyTextures/hello.png".
https://docs.unity3d.com/ScriptReference/AssetDatabase.MoveAsset.html
Oh AssetDatabase wants file extensions, but Resources class doesn't
wait this is weird, everything works except the renaming the directory
void Shift()
{
Debug.Log("Attempting shift");
AssetDatabase.DeleteAsset(@"Assets\Scripts\script.txt");
AssetDatabase.DeleteAsset(@"Assets\mp3Files");
AssetDatabase.MoveAsset(@"C:Assets\Scripts\newscript.txt", @"Assets\Scripts\script.txt");
AssetDatabase.MoveAsset(@"C:Assets\newMP3s", @"Assets\mp3Files");
Debug.Log("Finished!");
}
wait and renaming the script
but the deleting works fine
I updated my game to unity 2022 and now jsonconvert doesn't exist anymore? 😭 I have the newtonsoft package downloaded and it says it cannot be found
What do I do with AssetDatabase and Handles?
help pls, I'm new to programming, so does anyone know a GOOD tutorial to make the imputs for my 2d fighting game? I've tried to follow a couple of tutorials but most of them do weird things.
the animations are cut off or something like that
guys how to get the device id for admob
systeminfo.deviceUniqueIdentifier is not working
how to define device id for android platform?
If you are working with the "new" input system, I would suggest tutorials from samyam: https://www.youtube.com/watch?v=m5WsmlEOFiA&list=PLKUARkaoYQT2nKuWy0mKwYURe2roBGJdr
However, animations being cutoff may be unrelated to the input system, unless your "cancelling" your input early, that will depend on how you have your project setup
How to use the new input system in Unity! I go over installing the package, the different ways to use the input system, and the recommended way!
📥 Get the Source Code 📥
https://www.patreon.com/posts/55295489
►🤝 Support Me 🤝
Patreon: https://www.patreon.com/samyg
Donate: https://ko-fi.com/samyam
🔗 Relevant Video Links 🔗
ᐅALL of my Input System...
when i build and run only interstitial ad is not working
even with AssetDatabase.Refresh() it doesn't work
void Shift()
{
AssetDatabase.DeleteAsset(@"Assets\Scripts\script.txt");
AssetDatabase.DeleteAsset(@"Assets\mp3Files");
AssetDatabase.MoveAsset(@"C:Assets\Scripts\newscript.txt", @"Assets\Scripts\script.txt");
AssetDatabase.MoveAsset(@"C:Assets\newMP3s", @"Assets\mp3Files");
AssetDatabase.Refresh();
}
thanks mn, I will see the tutorial, and another question,
i know that unity has several input systems (and apparently some of them are malfunctioning or incomplete) so if my goal is to make an input for pc and mobile which system should i choose?
Unity only has 2 input systems, both of them are fully functional, the "old" system that is also default and is used through the Input class, and the "new" system that uses InputActionMaps and is largely event-based (the tutorial playlist I linked covers the "new" input system) - if your trying to support multiple input devices, I would suggest the new input system is far more flexible and adaptable to more scenarios than the default "old" system, personally I would say unless you have a old project your working from, theres little reason not to use the "new" input system outside of maybe quick tests (though you can make the "new" one work for tests too)
is it possible to create Sprite Atlas in runtime?
ok ok, I'll keep it in mind, thx man, you may notice that I'm a newbie in all this
Hi all! I don't know if this is the right channel for this but I'm currently having errors with building my app as a .apk file. The error that shows up is as follows: ```CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Hub\Editor\2021.3.5f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Program Files\Unity\Hub\Editor\2021.3.5f1\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\gradle\lib\gradle-launcher-6.1.1.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"
stderr[
FAILURE: Build failed with an exception.
- What went wrong:
Execution failed for task ':launcher:processReleaseResources'.
A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
I've tried looking up previous solutions to this but to no avail. Before this error, I was getting another error saying thatandroid.r8isenabled = false``` is deprecated but I've already patched that up and now it's this error that shows up. Thanks in advance!
I have the name of a static delegate and I need to subscribe/unsubscribe to the delegate. I've done this to subscribe to an event via EventInfo.AddEventHandler(). The problem is that the delegate isn't an event and FieldInfo doesn't have an AddEventHandler method. Is there a way around this? I'm new to working with reflection, so I apologize if this isn't a productive question.
can i ask abt photon pun related stuff here
`void Move()
{
if (moveDirectionRaw != Vector3.zero && moveDirection != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(moveDirection); //or moveDirectionRaw
targetRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotDegPerSecond * Time.deltaTime);
r.MoveRotation(targetRotation);
}
Vector3 projectedVelocity = Vector3.ProjectOnPlane(moveDirection, normalVector);
r.velocity = projectedVelocity;
Vector3 force = (moveDirection * speed);
Vector3 anotherZeroY = new Vector3(force.x, r.velocity.y, force.z);
r.velocity = projectedVelocity + anotherZeroY;
//Clamping
Vector3 velocityH = new Vector3(r.velocity.x, 0, r.velocity.z);
Vector3 velocityV = new Vector3(0, r.velocity.y, 0);
if (!isFalling && stepsSinceLastJump > 20)
{
//r.velocity = Vector3.ClampMagnitude(velocityH, 5) + Vector3.ClampMagnitude(velocityV, clampYValue);
r.velocity = Vector3.ClampMagnitude(velocityH, clampXZValue) + velocityV;
this.GetComponent<Renderer>().material.color = Color.red;
}
else
{
r.velocity = Vector3.ClampMagnitude(velocityH, clampXZValue) + velocityV;
this.GetComponent<Renderer>().material.color = Color.white;
}
}`
Hi, how can I incorporate ProjectOnPlane into my player's velocity?
I'm trying to make it so that my player's velocity is equal to the angle of the ground beneath his feet, and THEN do the movement force calculations on top of that. But if I use the line r.velocity = projectedVelocity; , then I cannot jump.
how should I use this line of code to slowly decrease the fill amount of an image?
I need it to decrease smoothly and I feel that Time.delta time is needed cause I need it to be consistent for every device and the editor as well.
void Update()
{
waterBar.fillAmount -= 0.1f;
}
are you trying to like walk up slopes or something?
Yeah, that's exactly what's needed.
how exactly should I add Time.delta time there tho?
void Update(){
waterBar.fillAmount -= 0.1f * Time.deltaTime;
You multiply the value you want to make framerate independent with Time.deltaTime as always.
!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
Not sure if this is more relevant to #💻┃code-beginner or this channel so i'll just ask here. Right now i have a class that does some work and uses an async operation to do it's work. In another class i need to wait until the async operation of class 1 is done before i can access the variables. I'm not quite sure what the correct thing to use for this is. I tried having a look at observer patterns but they don't seem like the easiest solution. Is there some easy way i am missing or is it just implementing observer patterns?
Depends on relationship between your Worker and Observer. If Observer controls the worker I'd go like this:
In Worker:
public async Task DoWork() { .... }
in Observer:
await worker.DoWork()
However if Observer merely observes the worker, I'd go with an event.
In Worker:
event Action WorkDone; public async void DoWork() { .... WorkDone?.Invoke(); }
in Observer:
worker.WorkDone += OnWorkDone;
Add an Update method to the other class, get a reference to the async operation, and there should be a field on this operation indicating it is done. You can wait until it equals true
Depending on what the specifics of this operation is, this field will be named differently, of course. When true, continue the Update and invoke some method that needs to happen afterwards.
!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.
This does not work when there are multiple async operations, unless you want to create multiple events
you can use Task.WhenAll
Then you need to apply that to the main async task invoker, which is messy and it would mean that there is always a set number of tasks, instead of it being more dynamic
Just being able to call the task, storing the task in memory, and waiting in a seperate update method until its state is completed, which is what I suggested, does not create any more code than is necessary, and does not force you to wait for multiple tasks.
Well, we don't really know in detail what the OPs situation is, all of these methods might fit
we don't even know if he works with MonoBehs to be able to use Update 🙂
I'm gonna take a wild guess and say that any question in a channel about Unity code, in a Unity server, is about Unity 😉
The question is what type of async operation he is using, hence why I can't give a broad answer on what the operation can return, nor if it is possible to wait for any type of event
well yeah, and as a Unity dev I can tell you that it's been many weeks since I wrote anything in a MonoBehaviour class. But we don't know if OP is a dev or a tech art, if it's the latter then it might indeed be a MonoBeh we're talking about.
sorry was trying to implement the suggestion from dive let me try to give some more information. Right now working with MonoBehaviours currently the "worker" is using
AsyncOperationHandle<StringTable> Localisation = LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale); // create async load of localisation table
``` to get the localization table of unity and then setting up some data the "observer" needs to access
Yes so your monobehaviour defines a nullable variable of type AsyncOperationHandle
Then whatever needs to await it get this, checks if it's not null, and then checks if AsyncOperationHandle has been completed using whatever field defines it in there
If everything passed, you are done waiting and can respond it ot
And all of this happened in the Update method ☝️
i'm currently using
Localisation.Completed += Handle_Completed;
``` to wait until the operation is completed in the localisation class. and after that handle is done i want to invoke tha "observer"
i can't realy observer the async operation as that might mean the data is actually not yet available to access from the observer (as it is doing something with the table)
Works too
Hello, anyone knows a good approach to check object percentage visibility by camera every frame? Like it is for covered by another object and I can see only a part of it and I would like to know how much of it is visible in current state. This would be for the situation where camera moves and rotates as well as the objects are moving and rotating
Hey Guys! Does anyone has experience with encrypting scripts locally to prevent cheat engines?
tbh I'd avoid using update to keep things tidy, are you using something like this?
private async void LoadLocalisation()
{
AsyncOperationHandle<StringTable> Localisation = LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale);
await Localisation.Task;
LocalisationLoaded?.invoke()
}```
Well done, you just made a fire and forget method await an asynchronous method, and your whole application just crashed for some reason
Never, ever use async void. Properly await a Task, and handle on the result, even if it returns nothing.
This is why I used an Update method
Depends on whether or not you want something to await for LoadLocalisation(). If you need you can convert it to async Task
Then it's still a fire and forget method, and any errors are lost since you did not properly await the Task
There is a very specific reason why I suggest an Update method, you know
not sure why this would crash. If you're worried about this you can wrap it in try catch for more explicit logging or switch to UniTask to have this built-in
Adding a try-catch block is going to suppress the error, and you are unable to handle any errors whilst waiting for the task to finish. Once again totally avoidable if you just wait for a result in an Update method.
depends on OPs priorities between catching errors (which may or may not arise) and keeping code tidy. That's what I lope about programming - there is always choice 🙂
There's literally no priority with this. A fire-and-forget method is going to crash your application one way or another if you do not properly await the result of the Task
I'll type it again, this is why I used an Update method. You wait for the result, and you properly retrieve the result, allowing exceptions to be thrown
It's not about whether or not your code looks cleaner if you do it another way, your example will literally crash the application as soon as something go wrong. Not to mention there is a big chance the stacktrace might not be informative
Here are some best practices about the async-await pattern. I think the Async void section is useful for you: https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md
This repository has examples of broken patterns in ASP.NET Core applications - AspNetCoreDiagnosticScenarios/AsyncGuidance.md at master · davidfowl/AspNetCoreDiagnosticScenarios
Note the "It's ALWAYS bad" part.
this can get messy though. if you have to wait for multiple entities your Update method can get bulky really quick. You won't be thanking yourself for this when you have to go back to this code a year or two down the line.
You already gave a solution for this some messages above. You can use Task.WhenAll.
And like I said before, it's not about whether or not your code looks cleaner if you do it another way
Your application will be broken with edge cases if you don't do this
And if I can't convince you what the problem is, so be it. But don't spread misinformation and give some bad solution when it comes to async code. It's a tough subject, and it's very important you handle async code properly, to avoid sync-over-async code/deadlocks/memory issues/crashes/whatever.
I have a material set to Transparent -> Premultiply, How does one fade it out ? I've noticed I have to set emission to zero and colour alpha to 0 for it to be transparent, surely theres a simpler way?
thx I'll take a look, though what stands out to me is that this ting is ASP.NET manual. This worries me because I know that async/await in Unity works quite differently than in regular C#.
I'm not opposed to having more reliability checks per se, but I'm opposed to doing that in an Update. I suspect this is not very scalable and not really universal, since having an update method requires using a monobeh, which is best avoided for the core game code. (sure there are alternatives like implementing ITickable from Zenject, but do we really need to resort to this?)
Tell me how this will break, I'm curious
private async void LoadLocalisation()
{
AsyncOperationHandle<StringTable> Localisation = LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale);
try
{
await Localisation.Task;
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
LocalisationLoaded?.invoke()
}```
You're right, Unity has a different state machine when it compiles a Task, but the way to handle them stays the same. Doing it in an Update is totally fine and scalable since the Update method is guaranteed to run every frame, and you can always delegate it to another method if you think the update method becomes too big.
It doesn't, but you're still supressing the error, and unable to handle it from any class that waits for a result
Now classes are forced to still invoke behaviour when LocalisationLoaded is invoked, even though the task failed, and it is unknown whether or not the localisation truly finished succesfully
Solution: Another event that is invoked should an error happen, but now you have to create yet another method that handles any errors
Alternative solution: You make it a Task again, and use the Task.ContinueWith method: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.continuewith
But now you're working with tasks again, and to avoid another callback hell you might aswell do it with an Update method again
Another problem: What if a class needs to know if localisation was initialized at a later stage? The event might have already been invoked at that point. You can then once again check the Task if it completed using an Update method 🙃 .
Let's goo
event Action<bool> LocalisationLoadingFinished;
private async void LoadLocalisation()
{
AsyncOperationHandle<StringTable> Localisation = LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale);
try
{
await Localisation.Task;
}
catch (Exception e)
{
Debug.LogError(e.Message);
LocalisationLoadingFinished?.Invoke(false);
return
}
LocalisationLoadingFinished?.Invoke(true);
}
Did not fix my problem tough, and what if I want to handle specific errors?
Do I need to do this with every single async method I create? What If I want to ensure they all finish before I invoke my own behaviour?
if we only want to load localisation once and provide to anyone at later stages, this might work.
private event Action<StringTable> LocalisationLoadingFinished;
private StringTable localisationResult;
public void AddLocalisationLoadedHandler(Action<StringTable> handler)
{
if (localisationResult != null)
{
handler(localisationResult);
return;
}
LocalisationLoadingFinished += handler;
}
private async void LoadLocalisation()
{
AsyncOperationHandle<StringTable> Localisation = LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale);
var success = true;
try
{
await Localisation.Task;
}
catch (Exception e)
{
Debug.LogError(e.Message);
success = false;
return
}
if (success)
localisationResult = Localisation.Result;
LocalisationLoadingFinished?.Invoke(localisationResult);
LocalisationLoadingFinished = null;
}
you know what, I think we have devolved into whataboutism at this point 🙂 Let's not forget that all code is written for specific requirements. If we want to try to account for all the infinite possibilities, we'll never come up with a solution. Or your code will be so convoluted your team will hate you for it
See where this is going? More and more edge cases to handle, even though this method has one simple task: loading localisation.
// Inside your service
private Task _localisationTask;
public LocalisationTask => this._localisationTask ??= LocalizationSettings.StringDatabase.GetTableAsync(TableName, LocalizationSettings.SelectedLocale);
// In your monobehaviour
[SerializeField] private whatever _localisationService;
private bool _localisationBehaviourFinished;
void Update()
{
if (this._localisationBehaviourFinished || this._localisationService.LocalisationTask.IsCompleted)
{
return;
}
this._localisationBehaviourFinished = true;
// Localisation was loaded.
}
And all of that because you're actively trying to avoid just using a Task and the Update method as a listener
If we want to try to account for all the infinite possibilities, we'll never come up with a solution.
Except that we can totally do that just fine. The Task class was made with specific requirements in mind. You're reinventing the wheel at this point, even though Tasks can perfectly do all the edge cases you're trying to work with.
So just stick with the wheel that was made for you. Don't cut corners because you think the code does not need it. It's a perfect recipe for disaster and you will most definitely shoot yourself in the foot later on.
hmm you know, if you replaced the SerializeField with a method or constructor DI and converted update to an alternative plain class method like ITickable from Zenject I'd actually be fine with this 🙂
Why would ITickable be any better than an Update method?
And why would I need to download a whole package for something Unity already has?
And why are you suddenly agreeing with my method? 
I don't see how this can be tested at the moment, nor can it be used in unit tests for any other entity. This thing does not need to be a monobehaviour.
So your point is that Zenject allows regular classes to have a method that is invoked every tick, or something?
because I'm not the kind of a bigoted person who can never be convinced. In fact, when somebody makes me change my mind I appreciate that, because it means I'm learning 🙂 It has helped a lot through my career as unity dev
That's good to hear, call it very surprising to see the switch this sudden 🙃
well, you clearly wrote a code that is shorter than mine which does the same thing as reliably.
As long as this class does not do much else I'd say this is good.
yes, you can have a method called every tick but your class won't be carrying all the baggage associated with being a monobehaviour.
It will also allow you to write unit tests more easily, including making mocks with NSubstitute and such
monobehaviour is just generally a BIG freaking entity on it's own, even if you did not add anything to it. It has it's own lifecycle, it can't be spawned with new() (well, it can, but it's best avoided) etc.. As someone who was once tasked with covering a legacy project with unit tests let me tell you: this is NOT fun.
Better keep your entities as simple as possible. If this thing aint need to be a monobeh - don't make it one
unless you're participating in a game jam or the whole scope of your project is like 1 month - then you can do whatever you want 😄
Anyone have any thoughts on whether this is an alright way to call mouse collider events on another object which lacks a collider? is sending generic messages risky in any way?
If you are unsure about unexpected behaviour you could put a custom monobehaviour on all of those objects and call a custom function that does what you want it to do, if you want different ones and need a list of them create a common interface and implement that on each
need help figuring why my camera position changes if I change bethewn these two types of code:
code that generates the left
if(Physics.Raycast(ray,out raycastHit, 999f,aimColliderMask)){
aimTransform.position=raycastHit.point;
code that generates the right :
aimTransform.position=ray.direction*100f;
dont understand why this happens, can any one help? the acamera gest angled on the right
For the specific situation im completely sure its fine, this just seemed a good generic script solution to add to my toolbox(never really ran into the specific problem of wanting to call unity events on generic components before), but messages also seemd like a system where you could run into uninteneded behavour, so I figured I ask around a bit
Is the camera childed to the aim in any way or something like that?
could you post a picture of a bigger snippet of the code?
Maybe when you gnerate the ray?
'cs
void ManageCamera(){
screenCenterPoint = new Vector2(Screen.width/2f, Screen.height/2f);
Ray ray = Camera.main.ScreenPointToRay(screenCenterPoint);
////seccond option aimTransform.position=ray.direction*100f;
/////first option
if(Physics.Raycast(ray,out raycastHit, 999f,aimColliderMask)){
aimTransform.position=raycastHit.point;
}
////////
rotatePlayerToAim();
if(starterAssetsInputs.sprint)return;
if(starterAssetsInputs.aim){
aimVirtualCamera.gameObject.SetActive(true);
mouseControls.SetSensitivity(aimSensitivity);
return;
}
aimVirtualCamera.gameObject.SetActive(false);
mouseControls.SetSensitivity(normalSensitivity);
}
void rotatePlayerToAim(){
Vector3 worldAimTarget = aimTransform.position;
worldAimTarget.y =mouseControls.mouseTransform.position.y;
Vector3 aimDirection = (worldAimTarget - mouseControls.mouseTransform.position).normalized;
mouseControls.mouseTransform.forward=Vector3.Lerp(mouseControls.mouseTransform.forward,aimDirection,Time.deltaTime*20f);
}
'
what is the aimcollider placed on?
the player and the aimtranform are child of a root parent
the player is the "ratplayer" the aim transform is the "aimlookattransformPosition"
maybe start by trying to make both rays the same distance
ok
so either 999f or 100f.
Its hard to tell without having the whole thing in my hands(though I might be missing something, pretty hung over^^)
dont worrie thanks
ok I made it 999f and it got corrected the angle
ok I think I understand why
as the camera is tilted from the player, for the angle to "disapear" it neets to be far enought for it to not be unoticable
so I guess a better way to resolve this is not to use the camera as the starting point but the character
but no, the camera is the player view
ok but its corecter either way thanks man
well
its not corrected
xD the shot still misses the aim point a bit
try changing the distance to 'Mathf.Infinity'
I am gona try to use a emty transform that is faraway from the camera
and use it as the aim
but then will do infinit
if it does not work
ah no I need those transforms because there will be multiple multipleyrs rats and I need each ones controll each mouse
ok gona use that
Mathf.Infinity works man
but I gett allot of these
'transform.position assign attempt for 'AimLookAtTransformPosition' is not valid. Input position is { -Infinity, Infinity, -Infinity }.'
ah its because I am trying to get the transform, and not just use it as math prob
What is normally used / more recommended ? Using a character controller and calling the move function and allowing it to handle collision etc, or using transform.position to move your character and handle collision using raycasts ?
use a rigidbody and call MoveTo, this will automatically calculate physics
MoveTo?
MovePosition ignores physics same as Rigidbody.position, but it's visually smoother due to interpolation
Uh if i'm not mistaken it takes physics into account
like you cant MovePosition through a wall
I'd recommend to use charactercontroller unless you need something specific that you can't do with it
Though it doesn't have much in the way of physics, I believe it uses a rigidbody internally for accurate collisions
Something you'd have to put in extra work into if you made the controller manually
Thanks, can you give some examples of limitations the character controller would have ? I assume it works perfectly for something like a FPS controller like half life or cs go but now I'm wondering what kind of things it would struggle with
If the character needs to interact with physics in a realistic way, a fully Rigidbody based system is likely better
From what I understand the CharacterController does not do rotation or non-capsule colliders
Which means that it may be less suited for non-humanoid characters or games where gravity direction can change
public event Action<Collectible> OnPickup;
so the "type" of the action is just all the arguements that the OnPickup needs to have and anything that += the event needs also?
public event Action<string, string, string> OnPickup;
so I would just need to pass in 3 strings when invoking OnPickup here and the += needs to take 3 strings?
Yes
thanks!
In fact if you ctrl+click the Action you'll see its declaration
sweet thanks!
delegate void Action<T>(T arg1); -- accepts methods that return void and take an argument of type T
is it better to do something like this typically?
GameManager.instance.playerInventory.Equip(tmpStore.item, isBaseHero);
or create an event with the 2 types that Equip has and have the playerInventory sub to event?
not sure when to call functions in other classes vs use events
Use events when the target of the call is not known beforehand
gotcha thanks...do you have an example of how that might be?
The player died
Alright, but who can "reference" that? It's not known beforehand. You would use an event here
that makes sense thanks!
wont I need to know who can reference it since I will need to put in a sub to the event?
An enemy would subscribe to it, so it cheers your death. Or not.
The UI could subscribe to that to display a death screen. Or not.
etc.
You only need to know where the event is
It's like reversed
The sender notifies, and receivers are free to read it or not
so if I have a bunch of different places that I can equip armor to player, they should just call the "player.redoStats()" instead of make events
since I already know only the player needs to know it
Yeah just a simple method call will do here.
private void OnCollisionEnter2D(Collision2D collision)
{
var tag = collision.gameObject.tag;
}```
should I be using .gameObject or .transform here?
I guess .gameObject is a bit more of a direct path if your goal is to grab the tag
sweet thanks
for some reason when using OnTriggerEnter2D you can just do collision.tag...not sure why its different for OnCollisionEnter2D
¯_(ツ)_/¯
think about it
look at the parameter type
look up that type in the documentation
think about what it is
don't both of them take in the same type...Collision2D though?
no
they don't
that's why I'm saying, pay attention to the parameter type
look at the docs like they mentioned and you'll see . . .
I copied my Collision2d code and renamed it to trigger2d and it didn't get mad when it was taking a collision2d arguement which was my confusion :/
bc it's seen as a method overload. your IDE can't tell if you're trying to write the signature for the unity method or your own . . .
Made use of a nested ternary for the first time lol
// Set color to white when mouse over, otherwise show selected or default color
nameText.color = isMouseOver ? Color.white : isSelected ? tabGroup.ButtonColorSelected : tabGroup.ButtonColorDefault;
The actual code lerps the color but this is the condensed version
eww . . .
not really a fan of evaluating the same expression multiple times with if/else and did this since the script is very short and easy to read
intermediate local variables are the answer to that multiple evaluation thing
protected override void Start()
{
base.Start();
hpText = GetComponentInChildren<TextMeshProUGUI>();
maxJumps = 2;
Shoot();
}
NullReferenceException: Object reference not set to an instance of an object
Its saying my hpText is null
Im not sure why as it was working earlier and afaik I haven't touched this part of code
you should show the line number for this error
because that line with hpText = GetComponentInChildren cannot throw this error
NullReferenceException: Object reference not set to an instance of an object
Player.HpGUI () (at Assets/Scripts/sprites/Player.cs:108)
Fighter.Start () (at Assets/Scripts/sprites/Fighter.cs:76)
Player.Start () (at Assets/Scripts/sprites/Player.cs:23)
so what is Player.cs line 108?
{
base.HpGUI();
if (hpText == null)
{
Debug.Log("hptext is null");
}
hpText.text = hitpoint.ToString(); //line 108
}```
which line?
oh sorry missed that
all good lol
the debug.log is printing
so ik hpText is null
but I don't know how its null
well based on the stack trace
this is happening Start
is HPGui running inside base.Start?
because that's being called BEFORE you assign hpText
yeah, fighter has this in start()
protected virtual void Start()
{
character.Animator.SetInteger("WeaponType", (int)WeaponType.Melee1H);
_rb = GetComponent<Rigidbody2D>();
myCollider = GetComponent<Collider2D>();
hpSlider = transform.GetComponentInChildren<Slider>();
stats = new();
target = FindTarget();
pauseShooting = true;
HpGUI();
}
protected virtual void HpGUI()
{
hpSlider.value = (float)hitpoint / maxHitpoint;
}
I can throw a
hpText = GetComponentInChildren<TextMeshProUGUI>();
as a conditional inside of the override HPGUI()?
feels like bad coding to have to do it that way however
oh, I just had to call my hpText = GetComponentInChildren<TextMeshProUGUI>(); before base.start()...thanks @leaden ice 🙂
does anybody use odin in their studio?
i'm looking at pricing, and the enterprise package is on the pricy side, but i noticed that it includes support and access to devs. if i don't care about that, can i get the asset store inspector/validator? or do i need an enterprise license
not a code question but it's a coding tool. feel free to tell me if i need to move it
I use naughtyattributes and its worked good so far
According to https://odininspector.com/pricing the pricing is based on your studio's revenue
over 200K means you need enterprise
I would suggest you try it out as its free
@leaden ice right i saw their pricing but it also includes superfluous things (to me)
that's a discussion you would need to have with their sales team
whereas i can just buy this
You could but you'd probably be in violation of their license agreement
¯_(ツ)_/¯
whether you are worried about that is up to you
oh i see the asset store pricing is simply their personal license
I have a weird situation
I have old text to speech mp3s for a scene and new ones get cycled in once the scene ends
right now I just delete the mp3files folder and rename newMP3s to mp3files
but for some reason every time it does that unity does this
]
is there any way to override this message?
other than that all the assets end up in the right place
looks like you're deleting/moving files without properly handling the meta files
I'd guess this happens if you're using the System.IO stuff directly instead of handling things properly with AssetDatabase
oh I'm using an external python script for it
for some reason assetDatabase doesn't work at all
yeah - you'll have to handle the meta files yourself or use AssetDatabase
weird I thought the .meta files would be unnaffected since I'm just renamaing the newMP3s folder
oh maybe they don't have time to generate at all
my script just checks if the mp3s are all generated and then immediately changes the folder name
oh I just ported it to use assetDatabase but for some reason it does nothing
void Shift()
{
//for folders
AssetDatabase.DeleteAsset(@"C:\Users\Cameron\watchmealways\Assets\mp3Files");
AssetDatabase.MoveAsset(@"C:\Users\Cameron\watchmealways\Assets\newMP3s", @"C:\Users\Cameron\watchmealways\Assets\mp3Files");
AssetDatabase.Refresh();
//does the script, commented out for testing
//System.Diagnostics.Process.Start("CMD.exe", "/C py \"C:\\Users\\Cameron\\watchmealways\\Assets\\Scripts\\shift.py\"");
//debug: py "C:\Users\Cameron\watchmealways\Assets\Scripts\shift.py"
}
your paths are wrong
https://docs.unity3d.com/ScriptReference/AssetDatabase.MoveAsset.html
All paths are relative to the project folder, for example: "Assets/MyTextures/hello.png".
oh right sorry
yeah I just remembered lmao
I even remember Cameron
jesus I've been working on this thing for way too long
forgetting the most basic shit
take a break Cameron
at least it generates new breaking bad episodes +text to speech completely automatically now
plus the rate controller works
yeah I should haha
void Shift()
{
//for folders
AssetDatabase.DeleteAsset(@"Assets\mp3Files");
AssetDatabase.MoveAsset(@"Assets\newMP3s", @"Assets\mp3Files");
AssetDatabase.Refresh();
//for the script
System.Diagnostics.Process.Start("CMD.exe", "/C py \"C:\\Users\\Cameron\\watchmealways\\Assets\\Scripts\\shift.py\"");
//debug: py "C:\Users\Cameron\watchmealways\Assets\Scripts\shift.py"
}
I fixed it and everything works except for moveAsset()?
idk why
this is the last thing I have to fix and then the project should be fully functional
doesn't even throw an error, it just doesn't rename the folder
So I'm making a game and I just started with networking
I have world generation, and I am worried that if the player enters a world he will see clients in other worlds instead of the same world he's in.
I am using the Netcode package & Multiplayer Tools package
How would I go about making it so I could only see people in the same world??
well, I ran into an issue where my jump works how I want it to work on flat ground, but once I am on an upward slope while moving forward the jump turns into basically nothing
i theorize that it's because i'm running into the slope instead of along with it so my upwards force of the jump gets 'canceled'
but i am not sure how to edit the code to make it respect the angle of a slope beneath character's feet while moving forward and jumping
hello, well I want my character to hold the weapon ( even when switching to a new one etc like in cs go), how should I do it? should I use animation rigging etc?
i could help u out but im a little too busy right now fixing my own problem, u should repost it imo
void Start()
{
foreach (SpawnInstruction instruction in spawnInstructions)
{
GameObject spawnedObject = Instantiate(basicObject, instruction.startPosition, Quaternion.Euler(instruction.startRotation));
spawnedObject.transform.localScale = instruction.startScale;
SpriteRenderer renderer = spawnedObject.GetComponent<SpriteRenderer>();
renderer.sprite = instruction.sprite;
renderer.color = instruction.color;
AppearTimed timedScript = spawnedObject.AddComponent<AppearTimed>();
timedScript.appearTime = instruction.appearTime;
timedScript.disappearTime = instruction.lifeTime;
timedScript.telegraphStart = instruction.telegraphAppearStart;
timedScript.telegraphEnd = instruction.telegraphAppearEnd;
timedScript.telegraphAlpha = instruction.telegraphAlpha;
Rotating rotating = spawnedObject.AddComponent<Rotating>();
rotating.rotationSpeed = instruction.rotationSpeed;
rotating.rotationAcceleration = instruction.rotationAcceleration;
FollowPlayer followPlayer = spawnedObject.AddComponent<FollowPlayer>();
followPlayer.followPlayer = instruction.followPlayer;
followPlayer.minOffset = instruction.minOffset;
followPlayer.maxOffset = instruction.maxOffset;
followPlayer.maxRandomRotation = instruction.maxRandomRotation;
}
}
this isn't a good way to do this right
this is supposed to be done to >50 objects at the start of the scene
Excuse the mess but I have upgraded my Unity 2D project from normal rendering to URP pipeline and need help with changing my post processing code to work with the URP
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.
https://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html
Is there a version of Raycast that returns a list of items in hit in the order it hit them?
this is the closest I've found
is the best thing to just sort anytime if I need to do that?
What are the risks of a dynamic-get, dynamic-set property if you're handling all of the compatible types and refusing incompatible types? [This is not in game-ready code, it's for an editor window (and some static classes for the future)]
can you... show an example of what you're talking about?
are you talking about the dynamic keyword?
doens't look like you're doing anything really dynamic here though?
Isn't this just a SerializedProperty ?
and couldn't you just use object and casting?
Can't use an object and casting
can't genericize (the typical way)
I'm filtering all of the serializedproperty types (for a generic wrapper) and creating a simplified accessor for the serialized property's property type.
I'm already aware of what that entails if I were to not restrict the value types accepted* at all (toolkit users will find crashes and instability from incompatible types)
im struggling to find tutorials that allow jumping in a top down 2d game; all of them are either for gamemaker, don't have exactly what i need or don't actually tell me how to do it when if they have the perfect thing for me. Does anyone know how i could implement this into my game, if so thanks, because this would really boost my motivation to continue with this game
you'd have to explain exactly what "jumping" does in your particular game
jumping in a top down game seems weird
yeah it's like platforming
if you've ever seen or played the game crosscode, you'd understand what i want
i get that it's uncommon
you'd have to have some concept of "depth"
Praetor, do you have any advice around the keyword dynamic
yeah a lot of the tutorials say that but the only unity tutorial i found isn't for platforming
it's a very oddly documented one where people are either "never use it" or "only use it with specific libraries"
not really, seems like you thought through it way more than I have. Generally dynamic is not used in Unity because it is not supported by IL2CPP
Yeah that's a big issue
I also just avoid it like the plague because the whole point of having a nice statically typed language is static types. dynamic gives me nam flashbacks from my dayjob where I have to write Python
I'm using it right now as part of a framework I'm working on for Unity Editor Windows that works like a simplified overlay so other programmers in my university and course can get into the UIElements toolkit without a lot of the hassle of long (and sometimes hard to read) lines for accessing helpful powerful elements.
But, yeah, it's hard to say if it's viable. I've tested it and it's working fine - just would feel comfortable knowing all the risks.
It should not (and should never) compile with the rest of the Unity game* code because it's in a folder in assets labelled Editor, so I don't believe IL2CPP or Mono would have to compile it
the camera shape is based on the game resolution shape
change your game resolution (game view) and it will change the camera shape
because it's rendering to a render texture, right?
That camera's shape is based on the render texture's shape
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnParticleSystemStopped.html
is there a way to check if the particlesystems and there children's systems have ended?
struggling to find it..but need to figure out how to do it for pooling
in unknown territory here, so please point out if im heading in the right direction. I'm trying to detect how lit the player is, like with the old Thief games. my fps player 'model' is a upside down cone with a 2nd ortho camera called LightCheck just above his head, looking down, with basically just the model in shot. He is this shape so the camera can detect light sources affecting the player from all around. This camera outputs to a render texture of 1x1, and i getpixel color of this to find the overall color of the player, taking in light sources. That's where Im at so far, i figure i can use this color to check if the player is in shadow
field of view is a property on the camera
actually you're using orthographic
so you'd change the camera's Size to zoom in/out
subscribe to when the effect and children end would be best so I'm not checking every frame if its over
Say I want to assign a component to a variable and edit the component through the variable, I've noticed setting it to a component variable, it doesn't let me edit it, is there anyway I could do this?
are you talking about Component?
could you elaborate more
show some code?
So say I have a component Jim right, like a script
like as asked above are you using Component as the variable type?
This is hypothetical because I've tried it before, and it didn't seem to work so I don't use it as such I don't have any code
But yes
public class JimComponentMono : Monobehaviour
{
public void DoThingJim()
}
//In other class
Component JimComponent;
private void DoThing()
{
//This wont work no
JimComponent.DoThingJim();
}
Anyway, I have Jim attached to say the camera gameobject, and in another script I use Component JimScript = MainCamera.GetComponent(Jim);
Ok
you'd either have to cast it (since JimComponentMono is derived from Monobehaviour which is derived from Component)
public class JimComponentMono : Monobehaviour
{
public void DoThingJim()
}
//In other class
Component jimComponent;
private void DoThing()
{
var jimComponentMono = jimComponent as JimComponentMono;
//This works
jimComponentMono.DoThingJim();
}
or use the actual type (preferred way, also lets you set the Monobehaviour in the inspector if serialized)
public class JimComponentMono : Monobehaviour
{
public void DoThingJim()
}
//In other class
JimComponentMono jimComponent;
private void DoThing()
{
//This works
jimComponent.DoThingJim();
}
ok so I could have Jim JimVariable;
yeah, that is the way to do it
I see I've done that before, ig it just never clicked in my brain
Thanks for the help
does anyone know how in odin i could have say, a boxgroup with a checkbox inside the title that if checked will expand the content of the boxgroup? sec i have an image tha'ts close
i'd like the checkbox to be inline with the word "position" though, preferably IN the boxgroup title
[BoxGroup("Position")]
[HideLabel]
[HorizontalGroup("Pos")]
[SerializeField]
private bool _tweenPosition;
[BoxGroup("Position")]
[HideLabel]
[HorizontalGroup("Pos")]
[ShowIf("$_tweenPosition")]
[SerializeField]
private FromToPair<Vector3> _position;
oh togglegroup. thanks chat
could I get the gameobject through addlistener?
what GameObject through AddListener on what?
wdym "get the gameobject"? Which gameobject do you want to get and where?
Im gonna have multiple buttons and don't want to have to add this script to each one, so I'd prefer to have it go through a list of the buttons and add a listener to each one and if one is clicked it gets which button it was that was clicked
Is there any event that is called when an object or its parent is set active?
Something like
void OnActivate(){}```
And if not, is there an easy way to do the same idea manually?
The only idea I can think of is storing Time.time in a float every update and if X seconds has passed since the time was last stored then call OnActivate()
Anything better?
Performance is really important here
OnEnable()
Oh yeah thanks, should have thought of that lol
Is there any way to make this more performant?
GameObject tile = Instantiate(preset.TileGO, point, Quaternion.identity);
Tile tileScript = tile.GetComponent<Tile>();
...```
I have to instantiate a lot of gameobjects and its causing lag spikes whenever a new chunk is generated so I'm looking for ways to fix that
don't use GameObject references
use direct Tile references
but in general, your problem runs deeper than that - use the profiler to see what's slow about spawning your chunks
you might need to reduce or eliminate Awake/OnEnable/Start code in those chunks, or make smaller chunks for example
Are you saying to do something like this?
Tile tile = Instantiate(preset.TileGO, point, Quaternion.identity);```
I get an error, or are you just saying to cut out the assignment to tile?
I'm saying preset should have a filed called tilePrefab
not TileGO
and the type of that field should be Tile
not GameObject
Then you can write:
Tile tile = Instantiate(preset.tilePrefab, point, Quaternion.identity);
Alright that worked thanks. Not sure how all the information about the prefab is being stored in a Component variable though that's interesting
I'll see if I can cut out any Starts, Awakes, etc
don't do that until you run the profiler
to make sure that's actually an issue
Hey guys im having an issue in unity currently where i have a fishing level with a fishinging spawner that spawns fishes at the start but then i have a button in the corner to go to next scene which is the shop. Once I entered the shop and then come back to the fishing level i want the script to replay again so another batch of fish spawn since currently when i go to the shop, and come back to the fishing level there's no fish. Here's fish spawner script https://gdl.space/kihayakepu.cs.
Sounds like a situation where I would simply load the shop scene additively
then unload the shop scene when I'm done
wdym?
and the normal fishing scene will still be there, waiting, with all the fish unchanged
you can load scenes additively
no idont want the fish unchaged
i.e. load a new scene and keep the old one around
you shouldn't make this thing a DDOL singleton then
private void Awake()
{
if(instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}```
Get rid of everything in here except for the `instance = this;`
You need to do this somewhere else besides Start then:
void Start()
{
for (int i = 0; i < FishesToSpawn; i++)
{
SpawnFishes();
}
}```
you should instead make a function like:
public void InitializeFish()
{
for (int i = 0; i < FishesToSpawn; i++)
{
SpawnFishes();
}
}```
then have another regular scirpt in the scene that does like:
void OnEnable() {
FishSpawner.Instance.InitializeFish();
}```
o ok
thanks
and wait
how can icheck if the scene is loaded so it only plays once
Where do i go if im looking to help someone with a project
what kinda help
Like art or music
another discord 😄
you don't have to
I thought you want it to play every time the scene loads
why would you want to do this
that was the whole point of your question
So here's what I'm looking at in my profiler:
(Separated into the levels)
TileMap.Update() = 92.75ms
Transform.SetParent = 12.82ms
Instantiate = 72.2ms accumulated time
GameObject.Deactivate = 4ms accumulated time
Transform.SetHierarchyCapacity = 10.66ms
Instantiate.Copy = 31.75ms accumulated time
Instantiate.Produce = 24.35 accumulated time
Instantiate.Awake = 15.66ms acccumulated time
The rest seems pretty miniscule
This all happens over a single frame and then goes back to normal
Which of these do I need to focus on?
The biggest ones first basically
Ok I think I solved it by turning the GenerateMap() method into a coroutine and now it only generates 1 tile per frame
Since the chunks are generated just outside the camera this works perfectly!
(Unless I realise something in a few days and have to change all this back lol)
Asked this a while ago and didn't really get an answer so here we go again:
I'm basically looking to grab a bunch of data out of an animator. Things like current animations playing, blend ratios, etc.
After I get that data, I need to be able to send it over a network, and recreate that pose exactly on a separate machine
is this at all possible? I've googled so much and I just can't find anything about doing this
It seems that I'm able to get the animator state info and the blend weights and such, I just can't find anything on actually reconstructing it
why do you need to do this?
is there a command for the xy problem yet
!xy
Asking about your attempted solution rather than your actual problem
try to explain the problem you're trying to solve, not the hiccup you hit in your attempted solution, might make things more clear
So that I can reconstruct client states on the server for hit detection
pretty important
this should be handled on the server side regardless - so the clients shouldnt need to know the exact state the animator is in from the server. Try to separate what is UI from what is logic, and you'll make it a lot easier on yourself.
you know you've used unity for too many years when you shrug off domain reload crash 😅
Wrong. Client tells the server which snapshot states he's looking at, as well as the interpolation alpha. Server can reconstruct the client's view solely based on that. However not the animations (since the server doesn't run those in the first place) and since they're heavily decoupled from the simulation
Client must tell the server somehow what animations he's seeing other players at, at the time of his bullet shot (or whatever)
Well, seems like you're very familiar with what you want to be doing. All I will say is what you are trying to do with the animator is a huge pain, if not flat out impossible. If I were in your shoes, I would be looking for a different approach entirely, and maybe not be allowing the client to tell the server whether or not their animation has seen a hitbox connect (or whatever you're implying by "what animations he's seeing other players at, at the time of his bullet shot")
Client doesn't call the shots, he only tells the server what server-confirmed states he's looking at
I'm no networking expert, just know enough about the animator to know as soon as you're treading in state info land, a new approach is needed
I've been looking for a solution so long and the animator docs are just so poorly written on this topic
Idk what other channel I would put this in but hey y’all I’m having an issue regarding the Animation Rigging package. I’m setting up an IK fps character but when I build the rig and move an object containing the gun and the arm IK targets inside, the arms don’t move with the targets.
The only way I can get it to work is by having the arm joints inside the moving part too
So instead of it being real where the hands will jolt back from recoil and the shoulders stay put, either I have to put the entire arm structure inside the gun so the entire arm and shoulders move with the gun (which is ugly and defeats the purpose of IK) or the arms don’t move even tho their IK targets are moving
How would I fix this?
Btw the arms move with the targets if you move the targets themselves directly but if you move the parent of those targets, they wont move
and if I scale the parent the position is wrong but they line up
nvm just had to match the pivot with the offset of the hitbox
im slow
public class MonitorScreen : MonoBehaviour
{
public Camera MonitorCamera;
public GameObject Screen;
private RenderTexture ScreenInput;
private Material ScreenOutput;
private Material ScreenOff;
void Start()
{
MonitorCamera.enabled = true;
ScreenOff = Screen.GetComponent<Renderer>().material;
Screen.GetComponent<Renderer>().material = new Material(Shader.Find("Standard"));
ScreenInput = new RenderTexture(1600, 900, 0, RenderTextureFormat.Default);
ScreenInput.Create();
MonitorCamera.targetTexture = ScreenInput;
Screen.GetComponent<Renderer>().material.mainTexture = ScreenInput;
}
}
This is my script for rendering a cameras output onto a plane but when it is rendered, it appears flipped vertically, how do I fix this?
Are you sure that it isnt just your plane being flipped?
fixed it, the screen was imported from blender so it must have been messed up, using a unity plane worked.
so, im making a 2d platformer and my player movement is constantly fighting against the rigidbody2d ill send code
lemme open up my unity again
im slightly new to coding and im still doing someme learning and dont know exactly how to use if () statements which im assuming i would have to use but here just take a look
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
//variables to control movement
{ public float horizontalInput;
public float speed = 10.0f;
//vertical allignment
public GameObject Player;
//jump variables
public float verticalInput;
public float jumpPower = 100.0f;
void Start()
{
`` }
void Update()
{
{//movement script
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector2.right * Time.deltaTime * horizontalInput * speed);
//player allignment
Player.transform.eulerAngles = new Vector3(Player.transform.eulerAngles.x, Player.transform.eulerAngles.y, 0f);
}
{//jump script
verticalInput = Input.GetAxis("Vertical");
transform.Translate(Vector2.up * Time.deltaTime * verticalInput * jumpPower);
}
}
}``
also have no idea how to make it to where i can jump w/ my spacebar
now that i think of it i should've put this in beginner coding help
@here
Is nobody able to help me?
Not many people are accustomed with the animation rigging package. Maybe you have better chances asking in #🏃┃animation
I'm trying to make some code that I can use to adjust the values of the suspension spring force and damping force from a published build.
I can read the values for spring force and damping force but I cannot set them.
Does anyone know how I can set the values?
The coding hover menu thing suggests that the wheelcollider.suspension.spring is capable of both {get ;set; }
I never knew CubeMaps could be so annoying in script
what does the error say?
This is probably the dumbest error, I'm using CubeMap.Apply() but it keeps saying my boolean is an error no matter what I do. I even checked the Script reference and bool is at the bottom so I really don't understand
first error is CS1955: Non-invocable member 'Join.Spring.spring' cannot be used like a method
Second and third errors are CS1612: Cannot modify the return value of 'WheelCollider.suspensionSpring' because it is not a variable
the first one makes sense, but i’m trying to find in the documentation what the it returns
You need to actually show your code for anyone to be able to help.
is it possible to have 5 inch diameter circle sprite on any resolution or device
Thank you
i’m assuming L1w is a wheel collider right?
My dude, If I needed to show my code, I would. Someone who has used CubeMap.Apply() will understand what Im doing. I even linked the Documentation so they could see the Declaration...Its not rocket science to use a void (everyone does) and write CubeMap.Apply(bool)
OBVIOUSLY Im using a bool set to true.
and vehicle controller is the script that controls the torque and rotational angle of the wheel colliders (as well as other thinigs)
i’m really confused, since it definitely should be modifiable https://docs.unity3d.com/ScriptReference/JointSpring.html
I'm going to remind you once that you've been muted before for being difficult like this "my dude". If you're not going to post your code for people to review and see how it might be wrong, then don't bother using this discord.
Any comment following this that isn't that, is going to be another mute.
and wheel collider should return a joint spring https://docs.unity3d.com/ScriptReference/WheelCollider-suspensionSpring.html
could it be that it is modifying the spring value 2 scripts over? (using the harvesters script to reference the wheel colliders instead of modifying the wheel colliders directly from a wheel collider object inside of this script)
for fd are you able to modify it or can you only read it?
yeah, fd is a public float declared inside this script
no i mean the fd in the image
yeah, fd is local to this script
Thats it, thats literally what it is
Like I don't need to give people my code if you know what you're doing
Well for starters, nobody would have guessed what errors your code clearly has, without you showing it.
**it keeps saying my boolean is an error no matter what I do. ** - Whats not to understand?
You're passing in a bool type, not your actual bool called name. These should be highlighted as errors in your IDE if you're using.
Don't be so insufferable. That means nothing without seeing the code, it's not that hard to understand.
Again, if you're going to continue being difficult in this discord, you will be removed. I won't say it again.
There's asbolutely not need to be argumentative. Show your code, get help. That simple, everyone does this without issue.
What are you doing? bool is keyword not variable or value
You're saying I actually have to write (bool name = true/false)
Instead of just setting the bool to true and passing the name?
What is condition here, is that a random pseudo code?
Condition is the condition in the if statement
You didn't pass any variable by name
Is there any way using a render texture, to render a cameras view from a separate scene?
I mean, there's other issues too:
- You can't have two same named variables
- You have nothing called
condition - You have nothing called
CubeMapto call apply on
Is this not your actual code? Or is it pseudocode
I passed the name of the bool, when it gives an error, it writes CubeMap.Apply(bool)
Is this copy/pasted from your code, or are you summarizing? 🤔
is bool a name of a variable? Because you sure don't define it anywhere.
It should work considering it used to unless unity updated something in C# and now that doesn't work
Bring code that compiles.
@whole parrot Is this your code exactly as it's in your script , or did you summarize it with pseudocode?
That code wouldn't work in any C# version.
Aight... That pseudocode doesn't make any sense then.
!mute 402958234371227648 1w Once again, you are refusing to share your actually code (for some reason). Nobody can help if they can't see your work, and you continue to waste people's time by dancing around that fact. As mentioned before, if you weren't going to share your actual code, you will be muted. This is your second and last one. I suggest when you return, you actually participate in receiving help the normal way, by showing your work and letting people assist you that way.
UnicornKitty#3889 was muted
Share your actual code and a screenshot of the error, or no help for you.
We'll try again in a week. Goodnight. 
Guess not then. 😄
Is there any way using a render texture, to render a cameras view from a separate scene?
👋 Hey, I keep getting this warning, I know why I keep getting it, and don't intend to fix it since it's basically irrelevant, But the warnings are clogging up my console, I know you can suppress it if you have the warning ID, but how do I get the ID?
private void HandleWalk()
{
if (!CanMove) return; // if you have walk disabled return
if (characterController.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical")); // Calculate the movement direction
moveDirection *= WalkSpeed;
if (Input.GetButton("Jump"))
{
if (!CanJump) return; // if you have jump disabled return
moveDirection.y = JumpHeight; // Make the character jump
}
}
moveDirection.y -= gravity * Time.deltaTime; // Apply gravity forces
characterController.Move(moveDirection * Time.deltaTime); // Move the character controller
}
Can someone help, does anyone know how to move the player move forwards in the direction of the camera? I've done this before but I forgot how and the scripts are on my broken hardrive.
Likely do so before applying jump or gravity.
ive already fixed it
I want to create a magnifying glass script that magnifies the canvas based game objects which are in screen space overlay I didn't found much references for this problem
In this video I show you how to make a simple magnifying glass feature for your 2D game In Unity software.
TO BLAST! - My New Fun Relaxing Puzzle Game Available On Google Play Store
https://play.google.com/store/apps/details?id=com.ZoGames.ToBlast
Guess The Movie Is Available On Play Market For Free For Android devices
Here is the link
https:/...
isn't this what you want?
why are you using that font
does anyone know if there is anyway to add top down platforimg and jumping in a 2d game, like cross code or alundra, I've also herad that some old zelda games had thua feature as well, but I'm struggling to find tutorials that help with this, as all of them are using either gamemaker or godot, can anyone help me with this?
got a picture reference?
of what you mean by.. top down platforming and jumping
ok I'll show you
65 hours later... I haven't fallen this hard for a game in a long time. That game is called CrossCode. A game modeled after the puzzle/aRPG combat genre you know and love from games like Zelda A Link to the Past, Secret of Mana/Evermore, Terranigma, Bastion.. even more recent entries like Hyperlight Drifter in a way.
Traversing incredibly wel...
it shows it in about 10 seconds
that's what im aiming for but with a manual jump button instead of automatic
logic is the same for any 2d movement. it's just the art that affects the perspective
try looking at any top down 2d movement tutorial
ok
and if you're getting results for other engines, why not just add "unity" to your search
i did but still there were no tutorials
YouTube
on google there were no examples of code
and there wont be tutorials of EXACTLY what you want. that's game dev. you need to figure things out yourself sometimes
if you're really new to coding and Unity, you should start with the basics
!learn
Unity Learn has some starting projects you can learn from
🧑🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/
as well as the beginner scripting course
ill try and relook online to see if i can understand it better, because it's just a new concept to me
yooo
need help'
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
Rigidbody2D rb;
public float speed = 6;
public float rotSpeed = 0.2f;
Vector2 mousePosition;
public float dashTime;
private float dashTimeCounter;
public Slider dashBar;
public float dashSpeed;
public float dashFillSpeed = 0.5f;
public bool dashfilled;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
dashBar.maxValue = dashTime;
}
private void Update()
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
dashBar.value = dashTimeCounter;
Dash();
Move();
}
private void Move()
{
Vector2 dir = mousePosition - rb.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
rb.rotation = Mathf.LerpAngle(rb.rotation, angle, rotSpeed * Time.unscaledDeltaTime);
rb.velocity = transform.up * speed * Time.unscaledDeltaTime;
}
void Dash()
{
if(dashTimeCounter >= dashTime)
{
dashfilled = true;
}
else if(dashTimeCounter <= 0)
{
dashfilled = false;
}
if (dashfilled == true)
{
dashTimeCounter -= dashSpeed * Time.unscaledDeltaTime;
Time.timeScale = 0.2f;
}
else if (dashfilled == false)
{
dashTimeCounter += dashFillSpeed * Time.unscaledDeltaTime;
Time.timeScale = 1;
}
}
}```
even tho im multiplying by time.unscaleddeltatime it still slows down the player
only the enemy should be shlowed
slowed*
help
This looks wrong:
rb.velocity = transform.up * speed * Time.unscaledDeltaTime;```
You shouldn't multiply a velocity with a delta time value anyway.
I suggest you try dividing it with ``Time.timeScale`` instead
my whole life was a lie, lmao
I also suggest calling Move from FixedUpdate instead of Update, to avoid weirdness due to physics loop vs. rendering loop
And use rb.MoveRotation instead of rb.rotation if you want the rotation to look a bit smoother (you need to enable interpolation on the rigidbody)
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90;
rb.rotation = Mathf.LerpAngle(rb.rotation, angle, rotSpeed / Time.timeScale );
rb.velocity = transform.up * speed / Time.timeScale;```
now it is jittery and not smooth
The jitters will likely disappear if you rework the physics methods into the physics update loop and remove the deltatime multiplications that conflict with it
I can see in the inspector that the rb is still not interpolated
The engine doesn't calculate physics in the render loop, so you shouldn't be inserting 'time since last render frame' into any variables
that did the trick
thanks you both
and i also had to interpolate just like @hexed pecan suggested
It will help you to read what the FixedUpdate is and how it should be used
ye i should give it a read, i havnt revised it since my second ever game so yea
TYSM everyone
how much more ressources does it need for unity to call a method from one script to another if this first script has a cached reference to the other one ? if this method is called in the update function is it really performance impacting?
not sure what you mean exactly, but caching and using a reference will be faster than using GetComponent by a lot. Especially in Update
I think he means like calling a method from within the class vs. calling a method from another script?
Which should be negligible
sure probably is slower, but there's nothing you can really do about it
such a micro optimisation to worry about
Yep
yeah that's for sure, but lets say you have monobehavior_1 with a method Add1(int number) that just adds one to number and returns that number, and you have Monobehavior_2 with the same method, now if the MonoBehavior_2 is cached in MonoBehavior_1 and you call the add1 function from the cached monobehavior, is it slower then calling it on the first function, or is it exactly the same
Almost exactly the same, and almost as performant
It just has to say "hey load where the other MonoBehaviour is in memory" for the second one, which is extremely negligible
the development gains from better organised code for such a negligible performance impact is always worth it
and you'll always find other places to refactor for better performance before thinking about moving methods around just for any slight increase
this bulletSpawnTransform.position should give me its world position right ?
yes
so why when i shoot at two different positions i get this
this is the ingame transform of the bulletSpawn object
its debugging the local coordinates
not the world ones for some reason
is it a child?
yes
No it's logging the world position. What shows in the Inspector is the local pos
yeah but the position its debugging is the rounded one of the local position
Then the object has no parent
im getting the debug message "Look rotation viewing vector is zero". Should i be worried and how can i make sure it wont appear. Im following Codemonkeys 10 hour tutorial
Or the parent is at world origin
Sure you're looking at the right object? In the Hierarchy it's disabled, but the Inspector shows it enabled
Try logging the localPosition then, because what you're logging is definitely the world position
It might be referring to a whole another object, log its name also
and if none of that seems to show why, then try looking at the positions of the parents and see if you are accidently moving them incorrectly
i've made a script that i think will work the way i want it to, what do you think
public class HeightManager : MonoBehaviour
{
public float playerHeight;
public List<Collider2D> level0;
public List<Collider2D> level1;
public List<Collider2D> level2;
public List<Collider2D> level3;
public List<List<Collider2D>> levels;
public void Start()
{
DisableAllLevels();
}
public void Update()
{
EnableCorrectLevel();
}
public void DisableLevel(List<Collider2D> level)
{
for (int i = 0; i < level.Count; i ++)
{
level[i].enabled = false;
}
}
public void EnableLevel(List<Collider2D> level)
{
for (int i = 0; i < level.Count; i ++)
{
level[i].enabled = true;
}
}
public void DisableAllLevels()
{
for(int i = 0; i < levels.Count; i ++)
{
for(int j = 0; j < levels[i].Count; j++)
{
levels[i][j].enabled = false;
}
}
}
public void EnableCorrectLevel()
{
if(playerHeight >= 0 && playerHeight < 1 )
{
DisableAllLevels();
EnableLevel(level0);
}
else if(playerHeight >= 1 && playerHeight < 2 )
{
DisableAllLevels();
EnableLevel(level1);
}
else if(playerHeight >= 2 && playerHeight < 3 )
{
DisableAllLevels();
EnableLevel(level2);
}
else if(playerHeight >= 3 && playerHeight < 4 )
{
DisableAllLevels();
EnableLevel(level3);
}
}
}
for people who haven't seen the previous messages, im trying to make a top down platformer
var parent = transform.parent;
while(parent != null)
{
Debug.Log($"{parent.name} wp: {parent.position}, lp: {parent.localPosition}");
parent = parent.parent;
}
now its just debugging nothing ...
what the heck
its probably a event subscription error again that messes everything up
oh wait nvm
this is the output
weird, so the hierarchy doesnt detect parents
well that isnt parented then
show the hierarchy fully open in playmode