#💻┃code-beginner
1 messages · Page 577 of 1
(unless you have two BattleStateManager components on one object, I guess, but that's very cursed)
It's undocumented and not intended to be used by users, but it's used by Unity's own packages, such as Timeline. Like other internal APIs, it might be removed or change without notice, but since it's being used by multiple packages spread out over multiple teams within Unity, I think it's unlikely that it will be removed.
so it should be playerPrefab = battle.playerPrefab;
oh, I misread your code. I thought you were getting a component from playerPrefab at first
all of those lines are redundant
just write battle.playerPrefab
yeah
You should also change the type of the player prefab from GameObject to whatever component type you'll be using
maybe Player
thanks
Examples of usages:
https://github.com/needle-mirror/com.unity.timeline/blob/3b7168a9f05dbe4338508c99c81a3cbdb612a3a8/Runtime/TimelineAsset.cs#L439
https://github.com/Unity-Technologies/com.unity.probuilder/blob/3b2a761c4e35ddfde58ce088ef4da91c27573a06/Runtime/Core/ProBuilderMeshFunction.cs#L29
https://github.com/Unity-Technologies/UnityCsReference/blob/72356cebf0cfb3551921bc07206d6b9d6508bb60/Editor/Mono/View.cs#L110
Multiple teams would have to coordinate to remove these event methods, which I find unlikely.
do you have any examples of using them by user?
I use it in my project, but it's not open source.
@slender nymph uses it in their Singleton implementation to ensure the instance is set before Awake.
#💻┃code-beginner message
https://github.com/boxfriend/Utils/blob/master/com.boxfriend.utils/Runtime/Utils/SingletonBehaviour.cs
nice, thanks, may be usefull in future
Thought it exist for serialization system purpose, but the purpose is more like tooling for lightweight execution before user scripts.
Can someone help? I am trying to make a car game but i think something is going on and my car is going really slow.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
post your !code using the links provided . . .
Tip #1 is please don't ever make a member variable with a name like "s".
what is s?
strength?
currentStrength?
Please don't comment on code style unless it actually hinders the application
Best is to just help with the issue, then comment on style later to avoid confusion
Well if you want someone else's help, clear naming is pretty crucial.
You can see s is assigned by strengthCoefficient there. It would help more if the code was properly pasted here using a paste site
I admit it's just a pet peeve of mine. Sorry. I'll try to help solve the actual problem.
btw the Time.deltaTime is usless in FixedUpdate, its already equal to Time.fixedDeltaTime so the calculation lose its purpose since its static value.
So is the only real issue is that it’s slower than you expect?
That’s not true. It’s just that they are both equal, but either way you need to scale it to the update rate
Although I guess I see what you mean
You can just inherently scale your values down
may be it get rid of it and check, the calculations including time delta time are usless but still modify the outcome (fixed delta time its equal to 0.02 by default)
It's still much more reasonable than just multiplying by 0.02 :p
it's not useless, it turns the value into 'per second', i.e.:
transform.position += Vector2.right * Time.deltaTime;
would move the object 1 unit to the right every second
especially given that you can change the physics update rate
Especially because you can change the physics tick rate
Beat me to it
how could I turn a float into an angle for a vector3?
that vector3 being a direction
perhaps you want Quaternion.AngleAxis?
thats not the case if its done in fixed update
This is wrong.
dont want to use quaternions here i dont think
Whether you're in Update or in FixedUpdate, this is bogus:
transform.position += velocity;
You must convert that velocity to a displacement by multiplying by a duration.
I guess I don't know what you're actually trying to do then
the whole thing I want to achieve is
shoot a raycast, turn 10 degrees, shoot a raycast, turn 10 degrees
in a for loop
If it's 3d you probably shoukd be using Quaternion
If you want a vector that points in a direction based on an angle, you can do
Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right;
for example
deltaTime in Fixed Update isn't used to make things framerate independent, but it is used to convert values from "per frame" to "per second"
you could also do something like
for (int i = 0; i < 10; ++i) {
float t = Mathf.InverseLerp(0, 10, i);
float angle = Mathf.Lerp(0, 360, t);
Quaternion rot = Quaternion.AngleAxis(angle, Vector3.forward);
Vector3 dir = rot * transform.up;
}
More specifically, per physics tick.
indeed
Right
It's true that your game will behave consistently if you leave out the length of the physics timestep
but it will still be wrong
Debug.DrawRay(transform.position, Quaternion.AngleAxis(degs[i], Vector3.right).eulerAngles * visionLength, debugColor, _timeBetweenScans);
It also bricks if you start changing the physics timestep, which is very common when doing slow-motion
this is an extension method I use to rotate Vectors: https://scriptbin.xyz/zuqaqofaja.cpp
Use Scriptbin to share your code with others quickly and easily.
why is eulerAngles in there?
because I need a vector3 and its a quaternion
well, yes, but that's a completely bogus vector
you're interpreting euler angles as a displacement...
You can multiply a Quaternion by a Vector3 to get a rotated vector
You need a direction Vector. Which EulerAngles is not
what should I multiply it with?
just vector3.one?
a direction you want to rotate
notice what I did here
i do not want to rotate anything
I already have all the rotations
What direction do you want the ray to point in?
Yes you do.
Take some starting direction and multiply it with a rotation
Quaternion rot = Quaternion.AngleAxis(90, transform.up);
Vector3 dir = transform.forward;
Vector3 result = rot * dir;
a 3D example
you said, "turn 10 degrees," which, by definition, is a rotation . . .
This spins your forward direction around your up axis by 90 degrees
I can never remember if that's clockwise or counterclockwise
I have a vector of rotations on the y axis
I want to use those
Okay, so, you want to take a direction, and rotate it by 10 degrees about the Y axis
I keep fucking up the multiplication
Quaternion.AngleAxis(degs[i], Vector3.right) * Vector3.forward
i dont know which one needs to be which
Oh, this is a 3D game, right
You need to rotate around the up axis
Quaternion.AngleAxis(degs[i], Vector3.up) * Vector3.forward
This would be appropriate for a 2D game, where the +Z axis is pointing into the screen:
Quaternion.AngleAxis(degs[i], Vector3.forward) * Vector3.up
Rotating around Vector3.right means that you're spinning around the world X axis
oh yea this is prolly what I did
which will spin out of the XZ plane
something does seem to be wrong though with my Job
public struct PFor : IJobParallelFor{
public float nom;
public NativeArray<float> results;
public void Execute(int i){
results[i] = nom * i;
}
}```
this is literally all I do
and its still not good
presumably nom isn't large enough
if you aren't getting a complete circle
(what on earth is nom)
float nominator = 360 / sightPrecision;
sighPrecision is the amount of lasers I shoot out
FUCK
ur right
forgot to add the f
i swear if it fixes
it does
im so stupid
ty
yes its true but that wasnt the case of the question, simply said it scale down input value by factor to fixed update rate.
He didnt want to scale down his moving value, he wanted to move his object faster, and in this case the fixed update was the culprit since it scales down his input value. I dont like unecessary noise, better to focus on the question instead try to push own agenda like others did here
what?
noise again
you provided an objectively wrong answer and everyone else explained why you were objectively wrong
If you hate useless noise, then why did you bring up an incorrect irrelevant information to the question
If you don't want noise then stop responding ❓
yeah wow its literally not making a single bit of difference, using jobs over normal
I would not expect that to do very much
Hey but at least you learned more about jobs
RaycastCommand might help if you can run all of the raycasts in one huge blob
for thousands of raycasts and for loops? idk.
But it's not a massive upgrade, from my experience
It's faster, but not mind-blowingly faster
I use it for a visibility system in my game. I need to shoot lots of rays between entities, as well as work out the light level at each position (so, more rays fired at lights)
no, I mean theres literally 0 difference
literally just clicked on chat. sorry if i miss something. but, you could probably optimise this by doing an overlapSphere first and then raycasting if there's something nearby. you'd probably only need 1 direct raycast (or you can add a few more, that are spread out, for a little more accuracy)
(also, remove all the debug code when profiling this :p)
Drawing all of the rays is going to be nasty
which debug code?
all those rays you're drawing
oh, those are toggle-able
I wrote a system that collects "light requests" from all over the scene, then executes one big job and passes the results back one frame later
Making this allocation-free was fun
well, true, this is my first time using them
idk why im bothering so much tho
this is just a school project
My bitrate lmao
that is absolutely brutal on the encoder
how fast is Quaternion.Angleaxis actually?
pretty quick . . .
You could punt all of that into Burst and use the Mathematics structs
what I did for the "unoptimized" one is just rotate a gameobject and get it's forward vector
Okay that's going to be way way worse
I did
no difference
I guess it's not too bad if it has no children
literally the same
for some reason
I would insert some profiler markers to measure how long each step takes
like 23 ms
imma send all my code if yall wanna look through it for optimizations
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.
unoptimized one
honestly, im more interested in the profiler than the code
i gotta know what's going to cause more lag first lmao
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.
optimized one
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Oh wait a second
pastebin doesn't have code formatting
update: nvm
huh.
missed it at the bottom
didnt know logging strings would be this bad
nvm x2, that's for commenting 
xD
(Also, this "CheckForPlayerJob" method isn't going to get burst-compiled, I'm pretty sure)
especially because it needs to access managed objects, haha
You'll want to use a profiler marker to measure how long the raycasts take vs. how long the raycast command batch takes
nah, in his case it was usless use of deltaTime, and it was the culprit of making it slow, the only one irrelevant thing was my response to irrelevant coment of some guy who said "its not usless" well it this case it was
It is literally wrong to not factor in the length of the physics timestep. If you want your speed to be larger, then you should use a larger speed value.
interesting, you can see the yellow/orange part increase whenever I turn off jobs
rather than randomly ripping out another part of the calculation
you can shorten this to 1 raycast and an overlap sphere
which you can figure out by using profiler markers, yes...
how exactly?
use Profiler.BeginSample("Foo") and Profiler.EndSample(); to measure a region of code
ohh ok
To be maximally efficient, you can create a marker once and then use it many times
private static ProfilerMarker _perceptionMarker = new("Perceptions");
e.g.
I use this to profile my perception system
I wrap the relevant code with _perceptionMarker.Begin(); and _perceptionMarker.End();
huh.
oh wait I have an idea
could be my Wander script
no
i cant find anything
this makes no sense
wheres the extra 8 ms coming from?
youd think its the timeToLoseSight one
but thats not it
Anything that isn't being attributed to something else (e.g. to "Foo") is counted in the "Self" time of Update
notice that "Self ms" is 7.78 there
a profiler marker includes any time spend between its start and end that isn't part of another profiler marker
also, you've got a mismatched begin/end sample on that "Faa" marker
this is going to confuse the profiler
as physics go down, scripts go up
RaycastCommand isn't causing Raycast calls, and those are what count as Physics time
Instead, you're just waiting on a job handle to complete
hence, script time
Insert more profiler markers to make this more clear.
Uh Oh!
whats causing it tho?
it shouldnt be expensive at all
Profile it!
it uses hashes over string comparations
so it's hashing the string 6000 times per frame
cant be that expensive. im pretty sure its basically hte same as string == string
sounds mildly suspicious
Wrap both if statements in separate markers
This will add some non-trivial cost, but it should at least indicate what's going on
When you do something ten thousand times per frame, even the cheapest of operations can start getting a bit taxing
6000*100 yes
Hits is being measured 60 times per frame, so I presume you have 60 tanks here
shooting 100 rays each
btw I am intentionally making the game perform worse, I can change the amount of times I scan for the player
i-intentionally?
they are benchmarking
I've done similar things in my game, like spawning 100 entities that do literally nothing but look at each other
huh, tagcompare really is bad
no brain. no body. no movement.
bad formatted code will fix
how else can I check if I'm hitting the player?
check their component. see which one is worse . . .
tagcompare seems to be really angry
that sounds 10x worse lmao
I would normally do this by looking for a component.
i'm trying to get the first script here to take information from the second script, but the asterisked "AddCollectible" is throwing up a no argument given error. The suggested fix adds the lower lines to the second script. Why isn't it finding the first AddCollectible class in that script?
{
for(int i = 0; i < collectibleSlot.Length; i++)
{
if(collectibleSlot[i].isFull == false)
{
collectibleSlot[i].*AddCollectible*(collectibleName, collectibleSprite);
return;
}
}
}```
---
``` public void AddCollectible(string collectibleName, string description, Sprite collectibleSprite)
{
this.collectibleName = collectibleName;
this.collectibleSprite = collectibleSprite;
isFull = true;
collectibleImage.enabled = true;
collectibleImage.sprite = collectibleSprite;
}
internal void AddCollectible(string collectibleName, Sprite collectibleSprite)
{
throw new NotImplementedException();
}```
TryGetComponent(out Player player)
You could also filter by layer
If the player is on layer X and the obstacles are on layer Y, that's a very cheap test
let's profile it!
do you use a filter on your raycast??
the raycast needs to hit both obstacles and the player
no, because there are literally only 2 layers
too slow . . .
so there's not much room there
yeah
i dont want the tanks to see through walls
but yes, it would be way more efficient
The layer check would be especially cheap
i have an idea, but check the player component first . . .
damn you Fen. that was it . . .
Can anyone explain to me what a Quaternion is/does?
just check the layer of the hit object. that's just a bit check . . .
its a rotation in 3D space
NonGimbalRotation?
I don't know how quaternion math really works -- and I don't have to!
I do know most of the vector math I do, but I still don't have to think about it
Hello I was wondering about the best way to get real time for time gated events should I be using an API?
system.dateTime?
Thats device time
now for the big reveal. check the layer . . .
I dont want people to be able to change it xD
if you must have the actual time, get it from a remote source
This will deter basic cheating
It concerns me that you say basic cheating is there a more secure way?
...how do I do that again?
the game is running on the player's device, and they could just modify the game to not check the time
I cant find the layer
examine the layer property of the collider you hit
o nvm got it
er
cant just get collider
of the game object of the collider you hit
it's the layer property . . .
its hit.transform.gameObject.layer
I can never remember which things are on GameObject and which things aren't
You can call TryGetComponent on a component, but not AddComponent
It is my issue because it has really slow acceleration, and the top speed based on my calculations should be over 200 kmh but it can only reach up to 105.
Ohh ok I got you, forgive me if im being annoying but say im a big company and im giving you a daily login reward how would I handle it? Server checks?
layers are integers
if I do == 4 or == "Player"?
makes sense. you can't add a component to another component because they only exist on GameObjects . . .
You should compute LayerMask.NameToLayer("Player") once and then reuse that number
sure, but TryGetComponent implies that components can be attacehd to other components :p
note that this is not using GetMask, which gives you a bitmask
if you know the layer, use the int, if not, then convert it using the name of the layer . . .
alternatively, you can compare the bitmask . . .
CompareTag on a component just internally calls gameObject.CompareTag, Component.AddComponent could easily do the same thing. In fact you could just make an extension method for it right now
its like 4% better @cosmic dagger
that works for me. it's what i usually do . . .
what I find extremely weird is: what I free up in physics processing, I lose in script processing when switching to jobs
public static class ComponentExtensions
{
public static T AddComponent<T>(this Component c) => c.gameObject.AddComponent<T>();
}
they really should have just added the method to the component class, but this is at least an easy workaround
im completely confused as to what im losing
summary makes it look ugly in discord . . .
public static bool TryAddComponent<T>(this Component c, out T comp) where T : Component
{
if (c.TryGetComponent<T>(out _))
{
comp = null;
return false;
}
comp = c.gameObject.AddComponent<T>();
return true;
}
https://github.com/Unity-Technologies/UnityCsReference/blob/72356cebf0cfb3551921bc07206d6b9d6508bb60/Runtime/Export/Scripting/Component.bindings.cs#L56
lmao even TryGetComponent just calls gameObject.TryGetComponent
is this still beginner coding...?
Yes, because the raycast command is not being counted as "Physics"
what-
Your script is waiting on a job to complete
you're calling JobHandle.Complete()
this means "wait until the job is done"
so your script is just parked there, doing nothing.
It does not matter exactly which category the profiler puts this into!
probably, extension methods are probably on the beginner side of "intermediate" knowledge about c#. it's some handy stuff to know about tbh
unless you're referring to all the raycast command stuff lol
I could get rid of a jobhandle by doing simple maths
instead of all this bs
just i * nominator
I'm talking about the raycast command.
If you can't wait for a bit before using the results of the command, then it's not going to be that much better than just running the raycasts directly
This should happen entirely on your servers
the player should not be able to say "It's time for my reward!" and just get the reward
How are you figuring that?
oh, MentallyStable posted your implementation of Singleton using internal Awake. i noticed an error in the getter. you forgot to assign _instance before returning it
not sure if it was fixed as this may be old code . . .
so I fiddled around with my optimizational features a bit, turned down precision, increased the time between checks....
those spikes are the comparetags....
Consider smearing out the queries over time
Chop the tanks into ten groups and run one group per frame
That is how I handle vision in my game. I break entities into five groups and round-robin them
don't need to. __internalAwake runs before AddComponent returns so _instance is already assigned by that point
I'm saying to not check all 60 tanks every single frame.
Because i have a different code that makes it able for me to see the speed i am going (it is a really simple speedometer) and the results i get are not the ones that they were supposed to be
what are you testing anyway? the code? raycasts? your pc?
I'm asking you why you think you should be going at 200 km/h
the thing I did there is make it so it only launches all the raycasts every x seconds
Right. You're having every single tank run a query once every x seconds.
Hence the enormous spikes
i dont know how to smear them
a very simple way:
like the problem is that they're synced
they all check for the player at the same time
int val = GetInstanceID() % 10;
if (Time.frameCount % 10 == val)
Whatever();
I need to somehow stop that from happening
whu
I mean I get what it does
but whu
this makes Whatever() execute once every ten frames
and the exact choice of frame depends on your instance ID
can't you use a random seed for each unit?
thats basically what fen does
a bit more efficient maybe
oh, yeah. that's nice . . .
this would also be very reasonable (and I can't remember if instance IDs can be any number or not, actually)
Thankyou for your help! Step one go get some servers I guess
im still pretty sure that the issue is the absurd amount of raycasts
this looks abyssmal
surely you can just optimize that to a single raycast
In practice, yes, you would just fire a few rays directly at the player
btw if all you need is daily rewards , server system functions too . unity already has that covered in the basic free tier via UGS / Unity Cloud
eg https://docs.unity.com/ugs/en-us/solutions/manual/DailyRewards
right now I'm benchmarking with 100 raycasts, normally id only use like 20
and not 20 tanks, but like 5 or 10
not to mention I wouldnt be checking for the player every frame, rather once every second or so
bear in mind, most instanceID's are negative so you probably want to check an Abs into the mix
LMAO I was wondering why my frames skyrocketed, turns out I nuked my raycasts xd
with this many casts you should consider using Raycast command and batch them
doesnt really work
int val = GetInstanceID() % 10;
if (timeBetweenScans > 0f)
timeBetweenScans -= Time.deltaTime;
else if (job)
if(Time.frameCount % 10 == val)
CheckForPlayerJob();
else CheckForPlayer();```
I already am :>
oh lol
ah, yeah, good point -- % is the remainder operator, not the modulus operator, so it spits out negative numbers there
oh
(please just give us the modulus. nobody ever wants a remainder)
yeah, just the ones created during runtime . . .
x -= 1;
x += n;
x %= n;
isnt modulus just absolute value?
Because i have did some testing with the unity standard assets car and the result was for a car that was 2500 kg that was going at 200 kmh, so because my car is 1000 kg and will have around half the power, i suppose it will reach 200 kmh. There is possibility that the wheel colliders are the issue but I am not sure about that
No, it's modulus
No, it's a value y such that x = kn + y
In computing, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another, called the modulus of the operation.
Given two positive numbers a and n, a modulo n (often abbreviated as a mod n) is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.
...
where k is an arbitrary integer
In mathematics, the result of the modulo operation is an equivalence class, and any member of the class may be chosen as representative; however, the usual representative is the least positive residue
this is what I always want
ah right, my bad
in romanian we have the same word but for absolute values
Wow thankyou this is incredible, I was actually trying my hand at daily missions but Im sure I will also add rewards at one point too so this will be very useful
@swift crag i would love to post the result but i think itd get blocked for causing epileptic seizures
sike
also this boosted my fps quite well, tho im not sure if its because of the smearing or because im not running the raycasts every frame
well, yes, the smearing is why you aren't running so many raycasts every frame :p
well no
well ok yes
technically
it matters less when I decrease the check times
it goes from one large spike to multiple smaller ones
it looks good. i like to run any raycasts or distance checks based on x times per second or every x frames. most of the time, you don't need to do it every frame . . .
You can do better than that -- you could spread the raycasts out over all frames
im guessing you mean x times per second
right now, you're only doing tests about half of the time
x times per frame sound insane
thats what im trying actually
oh, i meant every x amount of frames . . . 😅
there we goo
much better
o wait
no
i changed it to % 20
maybe its better
int val = Mathf.Abs(GetInstanceID()) % (int)(1.0f / Time.deltaTime);
ill try something like this
actually this might be a stupid idea
i wanted it to be based on framerate
hi guys
You can use Time.realtimeSinceStartup to get the exact time (rather than the "in-game" time). This could be used to limit how much time is spent on queries per frame
for example, you can limit it to 5ms of work per frame
i... dont understand
im literally just playing firework simulator
70 fps if i turn off gizmos
that was actually a pretty good recommendation tho @swift crag so ty!
it feels like I have vsync on
it just wont go over 60 fps no matter what
even tho I have the targetframerate as -1
and
thx
you want 2 transitions for it to be an or
Could it possibly be an issue with how the wheel colliders are setup and not with the code? I ask because i think the wheel colliders are slipping too much and that could be the reason why the car cannot speed up
Yeah, if the wheels are slipping, then you won't be getting any torque
A slipping wheel does almost nothing
yeah
You have two transitions between "Ground States" and "Air States"
sweet
If either transition succeeds, you'll switch states
so yeah -- many transitions for "or", one transition for "and"
How can I fix that?
instead of having to copy over all the fucking settings
in real life: more weight, more downforce, or more friction between the tires and the road
not sure how many of those translate into Unity physics...
yeah, some basic compound conditions would be nice...
I've done some awful stuff in VRChat
what does that have to do with unity
xD
VRChat is made in unity
VRChat is a Unity game.
I know, I was making a stupid joke
I have tried to change the box collider of the car and made it a little lower and that helped a bit but not enough and i have also changed both the forward and sideways stiffness on the wheel colliders but it didn't really help and it made the car shake a lot when i was going over 50 kmh
more fun than working on my main game for now
but at least I know how I'll be adding pathfinding to my bosses
although the way the movement works for navagents kinda sucks, I hope I can just somehow use the pathing or smth without the movement, maybe make an invisible agent that the boss follows
you dont technically have to use the A* pathing , you can just use the navmesh without
good way to have chars move freely on a floor without dealing with walls
You can make queries directly, yes
also, yeah, why is it that the game has the same fps with 20 tanks as with 200
I guess I'll have to figure that one out later
You can also make the agent not control the position of its object
(you can't stop it from rotating the object, though..)
for this school project it works fine
in the past, I've parented an empty to my character with an Agent on it
but for my game, ill want something better
thats what I thought about too
well, to be more precise: you can turn off the updateRotation property, but the agent still messes with your rotation. IIRC it stops it from tilting up or down
That definitely sounds like an issue if the friction of the wheels is supposed to be the force moving the car like in real life
It’s analogous to wheels spinning in mud — no traction, no velocity
How can I fix that though?
Personally I would not pursue that level of realism and instead would figure out a way to fake it… that level of detail and realism is beyond my understanding of how to use the physics system
Maybe this can help
A detailed look at how we made our custom raycast-based car physics in Unity for our game Very Very Valet - available for Nintendo Switch, PS5, and Steam.
BUY NOW!! https://toyful.games/vvv-buy
~ More from Toyful Games ~
- Physics Based Character Controller in Unity: https://youtu.be/qdskE8PJy6Q
- Instant "Game Feel" Tutorial: https://youtu.be/...
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so ive got a bunch of animations for walking for my character which ive made and it now looks like its walking only thing is now ive got a gun sprite to include in the walking so how would i add that to the walking animations do i have to get the artists to make seperate animations for walking with each gun or am i missing something
just... attach the gun to his hand?
So im trying to get my player to climb a walk and i am using a raycast and i have the raycast position as a empty gameobject on the player so when the player is facing right and then left the empy gamobject follows, the climb works for the right but when player is on the left they dont climb up?
Im confused
So are we without any code
u sure the raycast isnt hitting the player when going to the left?
need code to see how your raycast works . . .
RaycastHit2D hitRight = Physics2D.Raycast(rayCastPos.transform.position, rightRayDirection, 2f, SuctionCupLayer);
RaycastHit2D hitLeft = Physics2D.Raycast(rayCastPos.transform.position, leftRayDirection, 2f, SuctionCupLayer);
anim.SetBool("isClimbing", hitRight);
anim.SetBool("isClimbing", hitLeft);
public GameObject rayCastPos;
public Vector2 rightRayDirection = new Vector2(1, 0);
public LayerMask SuctionCupLayer;
public Vector2 leftRayDirection = new Vector2(-1, 0);
then its just a floating gun near its hand it doesnt look like its holding it
that means that no matter what value hitRight has, isClimbing will always get overwritten by hitLeft due to syntax
i dont get how this is a programming question tho
i can help with figuring out animations but not here
#🏃┃animation and post me some vid and/or screenshots
you should only set isClimbing to right when you're climbing right. the same applies to climbing left . . .
I thought thats what i was doing...
Could you explain a little more on how id do that please
how would i fix that?
Is your raycastPos flipping with your character when looking left?
Yes thats why im confused
right now your code sets isClimbing to hitRight, then it sets it to hitLeft in the very next line. you are overriding it when you are climbing to the right . . .
what you do currently, is set the value of isClimbing to hitRight, which is either true or false, and then immediately set the value of isClimbing to hitLeft, which is also true or false
that means, that if hitRight was true and hitLeft is false, isClimbing will be false
same thing happens vice versa, and inverted. doesnt matter what value hitRight has because hitLeft is the last value that you set it to
you should check which direction you're facing and place the raycast code for that direction in the if statement, and the opposite direction in the else . . .
or just setboolean to hitLeft || hitRight
anim.SetBool("isClimbing", hitLeft || hitRight);
?
how do i get facingdirection?
is there a way to make it so that if my player is holding W and D for example, he doesn't get the speed of that and still continues his speed as if he was holding D only?
normalize the input before mulitplying by the movement speed
or clamp the magnitude if you want to support analog input less than a length of 1
yes, if you want it to be true for one of both, you can just check if either or one is true, if none, its false.
I did that but I don't think it works
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>().normalized;
}
show how you are actually using this, because digital input should already be normalized if you're using the input system and didn't explicitly select the non-normalized Vector2 composite
// Handles player movement velocity
void Move()
{
if (!isDashing)
{
rb.linearVelocity = new Vector2(moveInput.x * playerSpeed, rb.linearVelocity.y);
}
animator.SetBool("isRunning", true);
}
oh wait
this code is confusing
actually nvm
i think its fine
ah, so in that case you don't want to normalize the input if you're only using a single axis
wym by a single axis, just the X in this case?
here's my full code maybe something is wrong
A tool for sharing your source code with the world!
Hey - are there many tutorials / documents that would be helpful for changing/accommodating to unity 6?
yes, you're only using the X axis. this is not a code thing, you need to adjust the input action asset
the input manager? What if I want to keep it later on for usage for my dash (which i want to go diagonally)
no :D
there probably are. but, the changes aren't that big
well they are, but not for the average user
When i did that this happens
basically, just check the change logs if you want to see all the differences. explore and find out while using unity 6, if you're unsure of whats new
also not a code question
Apologies.
not the input manager because that's not even what you are using. i was referring to the input action asset that you are using for input.
of course if you want diagonal movement then you'll need to normalize that, but also why have vertical input only for the dash?
well its like
i want them to be able to dash diagonally
but when you're on the ground i dont want holding diagonally to affect it
the run that is
you maybe should use debug.drawline to show, where you are raycasting against and maybe drawsphere to get the hitpoint
Is the speed value on a rigidbody measured in m/s?
By default, one world-unit is one meter, so yeah
This means that i had my speedometer set wrong. Now that i fixed it i can reach the speed i wanted
The good thing is now i know that my code is working as it should and i can finally start working on stabilizing the car at high speeds and make the tire meshes follow the suspension
i figured it out
idk if this is a good soln but
Hello, when emitting particles through script is there any easy way to set startindex to use on spritesheet? I need to set which sprite to use on any particle.
// Handles player movement velocity
void Move()
{
if (!isDashing)
{
float adjustedMoveInput = isGrounded || isOnRail ? (moveInput.x == 0 ? 0 : (moveInput.x > 0 ? 1 : -1)) : moveInput.x;
// if player is on ground or rail, have holding diagonally affect the same as just horizontally
rb.linearVelocity = new Vector2(adjustedMoveInput * playerSpeed, rb.linearVelocity.y);
}
animator.SetBool("isRunning", true);
}
lol excuse the code haha
if you want to still use the Vector2 input from the input action asset, just get the Mathf.Sign of the x axis instead of nesting ternary operations
AHH okay so they raycast line isnt actually facing the left... doy ou know how i would fix this? or get the players facing direction?
I mean, for your game, it looks like Vector3.left will always be correct, as your world isnt changing, right?
No cause the player can go left or right. Unless im not understanding what your saying
I mean, left for your player will always be left of your world?
yes i believe so
So you could just raycast into Vector3.left and .right
RaycastHit2D hitRight = Physics2D.Raycast(rayCastPos.transform.position, Vector3.right, 2f, SuctionCupLayer);
RaycastHit2D hitLeft = Physics2D.Raycast(rayCastPos.transform.position, Vector3.left, 2f, SuctionCupLayer);
anim.SetBool("isClimbing", hitLeft || hitRight);
So i did this and is still doing same thing in video and the raycast line still isnt switching to the left when player is facing left
hello, still trying to do the unique sprite per particle. One solution I thought of was giving particles a very long lifetime and setting up a curve in the texture sheet animation, but this doesn't seem to work, this is the code:
// There are 17 sprites
particle.remainingLifetime = 9000 + ((i % 17) / 17f) * 1000;
particle.startLifetime = 10000;
I made the curve go from 0 at time 0 to 1 at 0.1, which is 10% of the lifetime, Yet this does not work, all bullets seemingly only depend on the value at zero.
where is the line draw code?
I have this pick up script from a video i followed, and for some reason the hold pos wont move with the character itself
heres the code
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Debug.DrawRay(rayCastPos.transform.position, Vector3.left, Color.black);
Is this correct?
it wouldnt let me it was too large
if only large codeblocks was a listed option 
@astral falcon
this always draws a ray in the world -X direction
you assume people read..
no matter what direction you're facing
yeah thats my bad
how owuld i fix this?
don't do that!
presumably you want to use the same directions you used in the raycasts
RaycastHit2D hitRight = Physics2D.Raycast(rayCastPos.transform.position, Vector3.right, 2f, SuctionCupLayer);
RaycastHit2D hitLeft = Physics2D.Raycast(rayCastPos.transform.position, Vector3.left, 2f, SuctionCupLayer);
but im just useing Vector3.right and Vector3.left..
don't you want to draw a ray in both directions, then?
Remember that DrawRay does not have a "distance" parameter. You'll need to multiply the direction vector by the length
Debug.DrawRay(rayCastPos.transform.position, Vector3.right, Color.black);
Debug.DrawRay(rayCastPos.transform.position, Vector3.left, Color.black);
So this ?
This will draw two rays
If you give them a length of 2, they'll correspond to the raycasts you're doing
can someone explain to me why I need both a tilemap collider 2d and a composite collider 2d?
TilemapCollider2D is used to produce a collider out of your tilemap.
CompositeCollider2D glues multiple colliders together.
got it
I don't see why you'd need one if you only have that single tilemap collider
Although, it may change the precise shape of the collider
i was just wondering what the diff is
i like both because it lets it smooth out
but the issue is
I got this code to do a one way platform
void Update()
{
// checking if holding down, this disables the collision of the platform,
// allowing for the player to drop down
if (moveInput.y < 0)
{
Debug.Log("Holding down...");
if (currentOneWayPlatform)
{
StartCoroutine(DisableCollision());
}
}
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>().normalized;
}
private void OnCollisionEnter2D(Collider2D collider)
{
if (collider.gameObject.CompareTag(ScStrings.railLayer))
{
currentOneWayPlatform = collider.gameObject;
}
}
private void OnCollisionExit2D(Collider2D collider)
{
if (collider.gameObject.CompareTag(ScStrings.railLayer))
{
currentOneWayPlatform = null;
}
}
private IEnumerator DisableCollision()
{
CompositeCollider2D platformCollider = currentOneWayPlatform.GetComponent<CompositeCollider2D>();
TilemapCollider2D tilemapCollider = currentOneWayPlatform.GetComponent<TilemapCollider2D>();
Physics2D.IgnoreCollision(playerCollider, platformCollider);
Physics2D.IgnoreCollision(playerCollider, tilemapCollider);
yield return new WaitForSeconds(2f);
Physics2D.IgnoreCollision(playerCollider, platformCollider, false);
Physics2D.IgnoreCollision(playerCollider, tilemapCollider, false);
}
he can't drop down though
nvm the issue is
the current oen way platform is null
seems OnCollisionEnter2D isnt working
The Three Commandments of OnCollisionEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt be moving via a 2D Rigidbody on at least one of them
- ???
- Profit
is it possible it's not working cause my rigidbody on the platform is static?
Is the other object moving via rigidbody?
its void OnCollisionEnter2D(Collision2D collision) btw, the argument type is wrong
Then condition 3 is not met
oh
Oh, also that
Does the player have a rigidbody
only trigger events have Collider as the arg type
yes
that would produce an error in the console though so if that isn't even appearing then they need to address the other stuff first
Is it an error or a warning?
I haven't run in to it in a while
huh wasn't aware it did but they can fix it up along with the other stuff i guess
the platform has all of this
the player has the stuff in 2nd image
you know, i can't remember either. but it would be something in the console at least
Okay, and are you moving the object via rigidbody
As opposed to transform, for example
yes I'm using rb.linearVelocity
Okay, so that's fine then, fix the parameter and it should be working
I did but still no dice
Show the updated code
have you gone through the link i sent?
i took a look at it
i'll reread it
here's the updated code
public class PlayerOneWayPlatform : MonoBehaviour
{
private GameObject currentOneWayPlatform;
[SerializeField] private CapsuleCollider2D playerCollider;
private Vector2 moveInput;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.Log(currentOneWayPlatform);
// checking if holding down, this disables the collision of the platform,
// allowing for the player to drop down
if (moveInput.y < 0)
{
Debug.Log("Holding down...");
if (currentOneWayPlatform)
{
StartCoroutine(DisableCollision());
}
}
}
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>().normalized;
}
private void OnCollisionEnter2D(Collision2D collider)
{
if (collider.gameObject.CompareTag(ScStrings.railLayer))
{
Debug.Log("here");
currentOneWayPlatform = collider.gameObject;
}
}
private void OnCollisionExit2D(Collision2D collider)
{
if (collider.gameObject.CompareTag(ScStrings.railLayer))
{
currentOneWayPlatform = null;
}
}
private IEnumerator DisableCollision()
{
CompositeCollider2D platformCollider = currentOneWayPlatform.GetComponent<CompositeCollider2D>();
TilemapCollider2D tilemapCollider = currentOneWayPlatform.GetComponent<TilemapCollider2D>();
Physics2D.IgnoreCollision(playerCollider, tilemapCollider);
Physics2D.IgnoreCollision(playerCollider, platformCollider);
yield return new WaitForSeconds(2f);
Physics2D.IgnoreCollision(playerCollider, platformCollider, false);
Physics2D.IgnoreCollision(playerCollider, tilemapCollider, false);
}
}
the player code is pasted above
A tool for sharing your source code with the world!
its a tiny bit outdated but the movement is still the same so
Try logging collider.gameObject.tag before the if
And see what it logs when you hit the platform
in the update method?
oh nvm
im dumb
it logs "Rail"
WAIT
it works
it's just the first time he drops
the collider doesn't trigger for some reason
Okay, and if it doesn't log "here", then that means that ScStrings.railLayer is not "Rail"
As is, whenever you stop colliding with any object with the tag Rail, it gets set to null. Even if you are still in contact with another rail
so it sounds like you just need to pay better attention to the console if changing the method parameter was all you needed to do
the ragdoll creator wants the character in a T pose but idk how to make it do that in the editor
I have a tpose clip and I made it the default state in the animation controller
this is a code channel
I dont see a ragdoll channel
maybe give #🔎┃find-a-channel a read
is there a help channel
maybe give #🔎┃find-a-channel a read
ok so ill go to physics and someone will say this isnt a physics question
have you considered giving #🔎┃find-a-channel a read?
so ill go to animation and someone will say this isnt an animation question
i bet it can tell you where to ask your question
or you could just keep ignoring the suggestion and get bounced around the discord as you keep putting your question(s) in the wrong channels
when I ask in unity talk people say this isnt a help channel
No one has said that
ill just figure it out myself, cant be bothered to navigate the 5 million rules large discords always have
impossible to ever do something in a way that doesn't make a mod angry
okay bye then
what does that mean
Right now, whenever you start colliding with a Rail, you set currentOneWayPlatform. Whenever you stop colliding with a Rail, you un-set currentOneWayPlatform
Now, what do you think happens if you're standing on two different rails, and then step off of one
how can i stand on two diff rails
either keep a list of the ones you are currently in contact with or just use a physics query when you need to know if you are in contact with any
No i meant, when would the case be when I'm standing on two rails
the first option would have you add/remove them in CollisionEnter/Exit, the second is more versatile because you only check if you are in contact with one when you need that information
Well, you can pass through them, so what if there were two on top of each other
And you are passing through one
you may not think you will experience that, but what if you do. design your systems better and you won't have to track down weird bugs that you may introduce due to poor design
but regardless for learning purposes what is a physics query
sure
like a raycast or overlapcircle, they query the current state of the physics engine to check for colliders in different shapes/directions.
I kinda prefer to have OnEnabled run after start?
OnEnabled runs when the behaviour is enabled, not a while later
that would be a bit odd
I prefer to have a salary of million dollars. Sadly, that's not the reality
Sad.
Are you willing to become the EA CEO though?
Then you should stop preferring that
they haven't made enough scummy lootboxes for that job position
Are you offering the position?🤔
Nah, I was wondering how far you'd go for the 1 million salary.
To be the CEO?
but wouldn't you need to enable something in order to start it?
I thought you'd use Start for another step to initialise. And it's only run once.
But I guess I'm fine as long as it doesn't run on frame 0/right after Awake.
you typically would use Start for more setup/initialization but the order of operations is Awake -> OnEnable -> Start, it is possible all of this runs on the first frame, but Start may not be called until the next frame depending on when the object was instantiated
Thinking about it.
What exactly happens if a game object is disabled and reenabled on the same frame?
The object will be disabled, then enabled
if there's no code in-between, nothing
I think I know what you're getting at. As in if you wrote
void Update() {
this.SetActive(false); // this means this game object has disabled itself
this.SetActive(true); // but as it is now inactive, how could it get here to re-activate itself?
Deactivating an object does not return from the current function
i don't think this is the code acting up but who knows.. i get this weird trailing effect, anyone know how to fix it?
camera background is set to unitialized instead of background or solid colour
might be different depending on your RP
i cant find those setting but i did figure it out, Clear Flags was set to Don't clear
thanks for the help though
yes -- Unity has very little power over what code actually runs
you can run methods on disabled behaviours...or even on destroyed objects!
i hate to ask 2 questions in one day but i really wanted to get this to work tonight..how would i go about rotating the top piece? i'm trying to, when Z key is pressed rotate Z axis in increments of 120
but i wanted a cool little visual like if this object was a pyraminx rubik's cube and i was twitsting the top into the next available position
There's no limitation, but you have to pay $10 for each extra question
Share the code.
aye if that was a thing i'd gladly do it
something like this but i want it to stay locked into a location in increments of 120 using UnityEngine;
public class TopZ : MonoBehaviour
{
public float rotationSpeed = 30f;
void Update()
{
Vector3 currentRotation = transform.rotation.eulerAngles;
float newZRotation = currentRotation.z + rotationSpeed * Time.deltaTime;
transform.rotation = Quaternion.Euler(currentRotation.x, currentRotation.y, newZRotation);
}
}
if z was pressed
start coroutine: rotate z```
Nah, I was talking about how it would affect OnEnabled and OnDisable.
still doesnt work i guess i'll try again some other time or skip that
Once a function is called, it only returns on return or function end.
There's no way to stop a function before that.
its a 3d object so i wanted the player to see that the game was 3d instead of it exploding into 120 in a split second haha
they tell you to make a simple game to learn and i made it more complex than it needs to be
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Photon.Pun;
public class Portal : MonoBehaviourPunCallbacks
{
public Transform Destination;
public Transform Player;
public string Tag = "Player";
public float waitTime = 1;
public override void OnConnected()
{
base.OnConnected();
if(PhotonNetwork.IsConnected)
{
GameObject existingPlayer = GameObject.FindGameObjectWithTag(Tag);
if (existingPlayer != null)
{
Player = existingPlayer.transform;
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag(Tag))
{
StartCoroutine(waitTillTeleport());
}
}
IEnumerator waitTillTeleport()
{
yield return new WaitForSeconds(waitTime);
CharacterController controller = Player.GetComponent<CharacterController>();
if (controller != null)
{
controller.enabled = false;
Player.position = Destination.transform.position;
controller.enabled = true;
}
else
{
Player.position = Destination.transform.position;
}
}
}```
shouldnt it have the existingPlayer transform equal the Player transform this is whats confusing for me since i just started using photon pun
i dont know if any of you use it but its probably simple but its confusing for me
Pls format your code
just going to rotate in blender and call animation haha thanks again
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok
how do i make a object make a clone every second or so 100 times or until i tell it to stop i just dont get it i tried using courotines but it doenst work anyone help?
your coroutine did not have any loop in it so it would run a single time then end
but the answer is either use a coroutine with a loop or a timer in update
A coroutine will work fine, or just some logic with a timer in Update and counter
k ill try
but also it shuld of then made atleast one clone but it didnt
then you probably didn't start it correctly
see this is what i did but it doesnt even debug anything nether does it spawn a clone but when i put the INstatiatiate in start it works fine
and i aslo get this eroer
well that would be why the coroutine never starts. exceptions stop execution of the method they occur in
You never assinged that variable
also you definitely don't want to be starting that coroutine in update like that, otherwise you'll end up with way too many instances of it starting
k but how then
what variable
the one you're dereferencing on line 20
like the error says
scoreNewScore
yes the error says the line number and filename
you should give this information a read: https://unity.huh.how/runtime-exceptions/nullreferenceexception
ok
also since you just want this to start after a certain condition is met then continue possibly indefinitely, just use a timer in update. it will be a bit simpler to manage than a coroutine
il try but i am kinda very new with C# and unity making a timer will be hard is there any tutorial u suggest?
a timer is very easy
just google "unity update timer"
something like this:
float timer = 0;
float interval = 1; // 1 second
void Update() {
timer += Time.deltaTime;
if (timer >= interval) {
timer -= interval;
SpawnSomething();
}
}```
it's the amount of time that passed since last frame
that's it
nothing special
by adding that number we're just counting up our timer
that makes a simple timer
timer += the amount of time that has passed
that's all that's happening
oh i understand now it is quite simple
for example if the previous frame was 1/10th of a second ago, Time.deltaTime is 1/10 or 0.1
yep - people overthink it
this might seem like an odd question but does unity gizmos/handles for spheres and discs use signed distance fields to render them or does it generate a mesh
Probably neither - just like GL_LINE_STRIP or something similar
i see because when radii is rather large they are visually very inaccurate
spend the last few hours confused why my geometry math was not matching what i was seeing
Yeah it's definitely an approximation with a set number of subdivisions
i feel like SDF would be perfectly accurate with not much more performance hit
I am having trouble getting my unity editor to recognize my android device when i build.
- Unity installation: 2022.3.47f1
- Android type: Samsung Galaxy Note20 Ultra 5G
So far, I have tried going to the Android environment setup manual entry, but that was really hard for me to understand right now.
other than limits of floats of course
You basically need the android build support installed and development mode enabled on your device. That should be enough.
Also #📱┃mobile
development mode?
how'd i manage to miss that lol
Sorry, "developer mode". This is really not a unity thing:
https://developer.android.com/studio/debug/dev-options
As well toggle debugging over USB(if you plan on connecting via USB).
oooooooo we cooking with gas now
thank you; it is doing it's thing now
just gotta see if my build works at all
THE BUILD WORKS
Can I ask for some Unity support here?
Reset didn't work apparently.
I ended up with this which ended up a bit more manual. Just put this on the respective EventHandler.
private void Automate<T>(bool value, BaseEventData eventData, ExecuteEvents.EventFunction<T> functor) where T : IEventSystemHandler
{
if (value)
{
Transform parent = transform.parent;
while (parent != null)
{
ExecuteEvents.Execute(parent.gameObject, eventData, functor);
parent = parent.parent;
}
}
}
if its beginner coding concepts then sure
Idk if it is lol
well whats the problem?
I added a script for player attacking and made it trigger whenever I click. But now when I click, my player goes invisible and is only visible when I do click. I've tried to find the root of this problem for a few hours now and I know for fact, it's the new attack script.
what does the script do?
does the gameobject get disabled? is it the graphics that go invisible? like a renderer or something?
I'm not sure. All I know is that the entire placeholder sprite that I have goes invisible. I don't think that they stop rendering entirely. Would it be better if I just sent the code for this script?
if the issue didnt begin until after the script was added as i think u said.. then ya the script would be useful !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
sprite invisible
likely too close to the camera
unless its soemthing super simple like that ^
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
private GameObject attackArea = default;
private bool attacking = false;
private float timeToAttack = 0.25f;
private float timer= 0f;
void Start()
{
attackArea = transform.GetChild(0).gameObject;
attackArea.SetActive(false);
}
void Update ()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
Attack();
}
if (attacking)
{
timer += Time.deltaTime;
if(timer >= timeToAttack)
{
timer = 0;
attacking = false;
attackArea.SetActive(attacking);
}
}
}
private void Attack(){
attacking = true;
attackArea.SetActive(attacking);
}
}```
Well its visible when I click, and it was visible before this. Theres no animations as of now. It just spaces an object that I'll put some sprite in later.
What GameObject are you activating and deactivating?
there's nothing in the code you've just shown that would make the sprite on this object turn invisible. show the hierarchy setup and the inspector for this object and the camera
I'm not fully sure since I'm following a tutorial for it. But I believe it's a box collider
Make attackArea a [SerializeField] and assign it from the inspector. Turn that GameObject on and off in the editor. Does your apeite appear and disappear?
I'm not sure what the inspector is.
you should start with the essentials pathway on the unity !learn site
also assuming the component you showed is attached to the Player1 object, the sprite is the first child of that object which is the one you are deactivating
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
You should always learn the fundamentals first, like the windows and how to use the editor . . .
As I thought, you are deactivating the sprite GameObject . . .
I thought that too but I have no idea why or how to fix that
Hello, i know it is generally discourage to have two tiles collide/intersect, but if both of them are non moving tiles, what issues can it actually cause? I am asking because i want to have a removable wall, but i dont want to have to manually edit the tiles of the floor below in script to make it flow right. would it be fine for me to overlap some of the walls tiles in a tilemap ontop the floors, so i could remove the wall all at once while revealing a already made floor below?
Before continuing the tutorial, you need to understand what each line of code does. If you follow along, you can see that your code grabs the first child of the transform and deactivates it
The transform is the "Player 1" GameObject and the first child is the "Gladiator_Player_1" GameObject . . .
use Debug.Log(attackArea.name); in ur script
you'll see which object u after have assigned in the console
I have a bit of intermediate java knowledge so I'm not CLUELESS. It's just my first time dipping into unity and it's for a project
It's returning this in the log. So it's assigning attackArea as that first thing then?
Feel like you need to join a call
This would probably be easier explained that way
Yeah probably. I think I get the problem now. Just need help with a solution
I'm down to help set you on the right track over a call
don't think they have a vc in this server
hi im following a codemonkey tutorial on the new u6 networking stuff and im having issues spawning in a prefab:
the debugs arent even showing on the console
whoops theres a networking channel
Apparently everything i wrote didn't save, and all my work was in vain
Wrote where? If you mean a discord message, it has Ctrl+Z
In monodevelop
- i can't get the c# extension working in ms visual studio
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
I installed it manually
Wow I didn’t know MonoDevelop was still a thing
Why
Haven’t heard that name in like 6 years
Cause my old pc doesn't support unity 6
Or maybe longer…
It doesn't even support 2021,2022,2023
Pretty sure that unity 5 is way too old for C# extension
Or anything
Yea
It is too old
Thats the reason why i am using monodeve
Cause it still has some intellisense
If you know what i mean
What about 2017-2020
Nope
Unity 5.6
Is the latest i can use
I wanted to use bolt ngl
Sadly that too doesn't work
you're not gonna be able to get much help around here for working with a 8yr old release
what's the problem with the later versions?
Is there a way I can do this without tags
Public GameObject[] gameobject;
gameobject.SetActive(true);
Ig i will just need to read the manual
Uhhh yes? You are doing… that… already
Its giving me an error
You can’t SetActive on an array
What is array
You need to get an element out of the array or use a for loop if you want to do it to them all
Ok
Do you just need a single gameobject?
Ok its kinda complex
No, I have mutiple walls I would like to activate
heres the script incase but ill look into the forloop method
Yes you need to use a for loop or a foreach loop
Just use foreach
I’m on mobile so forgive me code format police.
But you need to do:
foreach (var target in Targets)
{
target.SetActive(false);
}
My code says
Logic = Gameobject.findgameobjectwithtag("Logicscript").getcomponent<"Logic"> ();
Sorry i am on mobile too atm
Your Captialization is wrong
You can use google or google translate to find out, it has nothing to do with coding
About capitalization?
And GetComponent
Ohhh
Aight you are just trolling at this point
I am gonna fry my brain with this one
Wdym "what's the difference"
I just started yesterday I don't even know scripting
I just looked up for a tutorial on yt
And found a flappy bird tutorial
I got the bird to jump and pipes to spawn
But the ui of the game is killing me
there are beginner c# courses pinned in this channel that will teach you the basics of the language
thank you, this did work and helped a lot. you have a nice night
Oh thanks a lot
can someone link the setting up visual studio channel on this discord, i cant find it
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
thanks
if you run into trouble then go through this https://unity.huh.how/ide-configuration
For your information, capitalization is important in C#. You must use proper capitalization or you will not find the method (or conveniently use a method with different casing if it were to exist)
Also, I don't understand how this can be an issue. If your editor is properly configured then it would provide the available methods for you.
So I can only assume it's not configured
I did it
The problem is i am using unity 5
I changed the preference to visual studio code
But Still doesn't work
So if you type Get in the code then it suggests the method?
No
Thats why i used monodevelop
It kinda helps complete the code
But it lacks the basic facilities that visual studio code provides
Monodevelop???
Yessir
Isn't that like ancient and no longer developed?
Yes
Why?
I don't see how a different plugin would not work
Also, Unity 2022 LTS still works on Windows 7
C# devkit
It probably doesn't support 32bit
Did you try?
I tried it, it just refused to download
only 64bit according to the system requirements though
Saddd
I might just give up and buy a new pc
But i am waiting for 50 series to drop
That is probably the best thing you can do here
I watched youtube video of someone doing this:
void ProcessEnemies(List<Enemy> enemies) {
for (int i = 0; i < enemies.Count; i++) {
var enemy = enemies[i];
if (enemy.dead) {
enemies.RemoveAt(i--);
}
}
I was confused why enemies.RemoveAt(i--) doesn't give compile time error. I thought i-- meant subtract i with 1 and return nothing, does it also return the value of i-1? Or am I completely misunderstand it?
yes
i-- returns i = i-1
Ohh this hurts my soul, is changing a list mid loop of the list fine in c#?
thats the loop shuld go reversed , yes its normal to do this when reversed
I thought that too. I thought it's gonna skip one enemy, but it might not be
waiit a minute shouldn't it be enemies.RemoveAt(i); i--? The script above would remove the previous entry on the list wouldn't it?
yeah no idea what they're going for here.. its removing the the previous enemy
How is it reversed? It’s not starting at enemies.Count and doing i— every loop
No i meant, you can remove items mid loop but only if reversed
So this is bad? In this case
I have no idea what they're going for tbh. They might be confusing what the function does
This is just all sorts of bad
just cause its not compile error, doesn't mean it does what they think it should
Does c# loop indexes? Like -1 is the last element