#💻┃code-beginner
1 messages · Page 339 of 1
I'm not sure what angle it could be that is outside of the range of -180 to 180
it is audio manager, visual studio says that an if statement for sliderValue is useless because it will always be true
I don't see sliderValue anywhere
Do you mean volumeSlider.value ?
It's true that value can't be null because it's a float -- a value type
volumeSlider absolutely can be null. Slider is not a struct
shouldn't it be between 0 and 360?
Those are the same values
You can't really control which way of expressing an angle unity will choose
so the best way is to just not write code that expects it to be in one form or another
volumeSlider is not a float
these are two different things
The compiler is telling you that a number can never be null
This is true.
But volumeSlider could be null, meaning that volumeSlider.value throws an exception.
If you have a volume slider, you can always get its value property, and the result will never be null
but maybe you don't have one in the first place
right ok i think i understand
I am making a enemy for my 2D game. I am wondering if I can somehow obtain a direction value with Vector2.Distance, or any simple way to do that.
ok the issue is the volume slider
distance is not a "direction"
explain what you are trying to make your game do.
I need this direction. The Player is the Ball, and I want the enemy to update a direction towards it. I want to have the Enemy Follow the Player but need direction to do that.
Subtract the enemy's position from the player's position.
This gives you a vector pointing from the enemy to the player.
B - A gives you the direction from A to B
because...
C = B - A
A + C = A + (B - A) = A - A + B = B
This works, thank you both!
You can also use Vector3.Normalize or the .normalized property to get a vector with a length of 1
this is useful if you only care about the direction and not the length of that vector
rb.velocity = toTarget.normalized * speed;
e.g.
If you did not normalize the vector, you'd move faster at longer distances
I just check if the x Axis is greater than 0 or less than 0.
So is a scripteable object just a struct?
No.
What for? A direction is supposed to be normalized which is different from just checking if something is 0
A ScriptableObject is a way to create your own kinds of unity objects without all of the behaviors (ha) of MonoBehaviour
(they also aren't components, so they aren't attached to game objects)
This is useful because Unity can serialize references to unity objects
and unity objects can be stored as assets
I mostly use ScriptableObjects to store read-only configuration data.
What that means?
will somebody beable to guide me and help me with a gorilla tag fan based game that i have a idea for pls
[SerializeField] GameObject someObject;
When you put this field into a class, you'll see a field named "Some Object" in the inspector.
You can drag a game object into the field.
Unity will serialize that reference: it's saved in the scene or prefab data.
for example: if you create a cube and inspect it, you'll see that the Mesh Renderer has a material on it
Isn't it saved on disk?
Materials are stored as assets in the Project window. You can drag one in to that field toa ssign it.
Right.
You can also create a material with code -- that doesn't exist in your project window
It's just like DefaultHDMaterial here, except that it did not come from an asset.
You can do the exact same thing with custom ScriptableObject types.
You can create assets out of them, and also create them at runtime.
I mostly just use assets, since I want to be able to set them up in advance.
Here's an example of one of my ScriptableObject types.
my "Icon Set" class holds some icon sprites, plus a list of bindings that the icon should be displayed for
coming back to this: if you meant "a bag of data", then that is a pretty common way to use SOs!
oftentimes, I will create a class that just holds some data
then I add methods later
very similar to what I do with prefabs:
- create a component with public fields for things I want to be able to find
- make those fields private and add methods later
public class Bullet : MonoBehaviour {
public Rigidbody rb;
public ParticleSystem explosionParticles;
}
then, down the road...
public class Bullet : MonoBehaviour {
[SerializeField] Rigidbody rb;
[SerializeField] ParticleSystem explosionParticles;
public void Fire() {
rb.velocity = Vector3.left * 10;
}
public void Impact() {
explosionParticles.Play();
}
}
[SerializeField] tells Unity you want to save that field. Normally, only public fields get saved.
in case you were wondering about that.
Gotcha, do you know what the static checkbox does in the inspector?
there are several "static" flags a GameObject can have
the static checkbox toggles all of them at once
in general, "static" means that the object is not moving or changing.
"Contribute GI" means that the object is used for baked lighting.
"Batching Static" promises Unity that you aren't trying to move the object. That lets it glue a bunch of small meshes together into one big mesh.
Im making a game in which two players are given 2 random bonuses at the end of each game and then they fight each other, Street Fighter style, does somebody know how to face the way in which bonuses are given? Im instantiating each of the fighters from prefabs at the start of the round so, how could I make them have a reference to the bonuses, Im really lost, thanks in advance
You usually just toggle everything at once, from my experience
whoever instantiates the prefabs should know about the bonuses
Okay, for example a GameManger, and should those bonuses be a component?
components have to be attached to a game object
You could have a prefab for each kind of bonus, and instantiate a copy to give to the player, I suppose
Yeah, the thing is I dont know how to "give" each player the boosts
@swift crag so basically static does not contribute to lighting, does not occlude other stuff?
the opposute: if you check "Static", then the object is included when doing baked lighting
occlusion culling lets Unity hide things that are completely behind a solid wall
I thought of making each boost a separate component so that all of the fighters have them but the GameManager activates the ones tha have been chosen randomly
to do that, Unity needs to know what's a wall (something that doesn't move)
but that might be too complex
By default it's "nothing" cheked right?
Right.
Thanks Fen
or unnificient
sounds fine to me; you'd make a prefab with all of the boosts on it
but only one?
Then with non static objects we don't do oclussion culling nor baking?
a non-static object can't occlude other objects
unity has to do expensive calculations in advance for things like baked lighting and occlusion
so it only works for stuff that doesn't change
Each of my fighters is a prefab, so should I attach all of the boosts to each one?
you'd have a "boosts" prefab that you attach to each fighter
or even just attach at runtime
Or, perhaps, the game manager is given all of the boosts
if each is on its own game object, it can just Instantiate the boost it wants to give
Is it possible to share a variable between two classes without having either one know each other? In this case its a Vector3. I want it to be unique to each gameobject though. So a monster's shared vector3 is diffferent than another spawned monsters.
But then if one of the boosts is: "gets a fire ball" for example, does that require that the fighter has that method??
i don't know how you're actually implementing this
i remember talking about this a while ago with you
implementing complex abilities you can attach to any character you want (something i'm doing in my own project right now) takes a fair bit of work
on the other hand, if every character knows how to throw a fireball, and they just need a boost that says "Yep, you can use it!", that's easy
or if you can put all of the logic in the fireball boost, so that the character just asks the boost to do something, that's also easy
I think I may follow that path so I dont explode
whateverMyBoostIs.Activate();
you don't care if it's a FireballBoost or a ShieldBoost
I thought of that but the thing is, how do I give each fighter that boost? for example, should I give each fighter the SAME component so the GameManager Activates it when necessary??
A player is given: "water gun and more speed" for example. Should I have in all of the fighters those components in case those are the two habilities that have been randomly chosen??
Do these components need to reference things on the fighter?
if so, then you'd have to put every boost on every fighter
so that you can drag things in to the boost components
Okay, so basically, every boost on every fighter and the GameManager activates depending on the chosen one at the begging of the game right?
If your boosts need lots of per-fighter configuration, yes.
If they don't, you can just instantiate a copy of the boost you want to give to a fighter
and then, I dunno, give the fighter a method like:
public void AddBoost(Boost boost) {
boostList.Add(boost):
}
Can I Instantiate components?
Sure. It will copy the entire game object the component is attached to, though.
You can't have a "naked" component that's by itself, without a game object
Why did I choose to do this game hahaha
I might just make each fighter to have the component, maybe its simpler
but is it messier as well?
Bro i dont understand events, what is the point of having both delegates and event args? if both are used to pass more information, to me it seems they do the same thing
delegates are just variables that can hold a function
events are how you actually call the functions
events are basically delegate[] but with some syntactic sugar
hi yall
what do you mean hold a function
a delegate is a type that specifices a method signature that a variable of that type can hold
delegate void SomeFunction(int x) defines the type SomeFunction that can hold anything that returns void and takes an int
What does the avatar field do in the Animator component?
thats for like a full 3D model body i think something like that
wrong channel for your question anyway though #💻┃unity-talk #🏃┃animation
Im having a small issue with onlick in my game. I need to be able to click a certain object, but there will always be an invisible collider above it (the game is 2d), so the click is blocked (Like the image shown). Is there a way i can bypass this?
Use a raycast that ignores the red object's layer
would that work with onclick?
No, you'll need to use a raycast
or, preferably, use the EventSystem interfaces, like IPointerDownHandler, which allows you to configure the layermask for the Physics Raycaster 2D you put on the camera
#if !UNITY_EDITOR //if not ran through the editor
Cursor.lockState = CursorLockMode.Confined; // lock cursor to monitor. disabled for editor testing.
#endif
Does this make sense? It compiles but I'm not sure if this is correct.
or would it be
#if UNITY_EDITOR == 0
did you try this?
Hmm, I guess not. I saw both used online. I'm not so sure about preprocessor stuff and there are less resources for them. The #if !UNITY_EDITOR compiles while the other one doesnt.
well that tells you which one to use then, doesn't it?
does using #ifndef instead make more sense?
why cant you just use what works? why come up with other solutions when you already have a solution
im just trying to follow best practices 😅
you will delete this when building the game anyway so who cares?
does ifndef even work in c#?
They're mostly doing the same thing afaik. ifndef stands for if not defined. However when not defined keywords are evaluated they result in 0. Which is also the logical false.
because it is definitely not even mentioned on the actual documentation page for conditional compilation https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives#conditional-compilation
Hmm... Maybe it's different with C# compiler.🤔
is there a general procedure for bugfixing bugs that only occur sometimes
like finding the cause
Ensure that whenever it does happen, you collect copious data. Breakpoints, debug logs, hell even writing stuff to disk
Then just try over and over to get it to happen
why cant i get a text gameobject reference attached to my component?
🦧 ✅
You wanna give that sentence another go? I'm not entirely sure what you mean
I cant fill the second gap with any gameobject
Does the GameObject you're dragging in have a legacy Text component on it
Im adding the TextMeshPro in UI gameobject
That field doesn't take a TextMeshPro. It takes a legacy Text
If you want to use a TextMeshPro object, use TMP_Text
whats the difference?
They're completely different components
Basically you try to reproduce it until you can do it 100% of the time. Some bugs are almost impossible reproduce 100% of time. If that's the cas, it's likely related to race condition and multithreading.
Which is used more frequently to represent counters
for example money
You should basically never ever be using legacy UI elements at all
TextMeshPro has completely replaced them
In this case it's a pain in the ass, and the only thing you can do is make assumptions and try to confirm them via logs or debugger.
Okay, thanks a lot
right now when i teleport something to a position abit of the time it just gets teleported to somewhere far to the left
not lookin fo help there just thought id say my current bug
Are you setting the position to something when you should be adding to the position
transform.position to another transform
Then if your object is ending up somewhere you don't expect, that other transform probably isn't the object you expect
how come it would get transported to it most of the time then
because most of the time it is the object you expect it to be
ill check it out
Alternatively, that target object is moved around at some frames.
So when the issue happens it's at that invalid position.
I may be stupid but i really dont get why brackeys here calls it xRotation when its all about the cameras Y rotation
well, it's not about the camear's Y rotation (:
It's rotating the camera around the local X axis
X is right, so it's tilting up and down
i am very confused haha
X - red - right
Y - green - up
Z - blue - forward
Ignore the player body rotation for now.
If you want the camera to look up and down, you need to rotate it around the correct axis.
Rotating it around the Y axis would make it spin side to side.
Rotating it around the Z axis would make it roll over.
to visualize this, try pointing right/up/forward and imagining what happens if you spin yourself around that axis
I do have an error. I'm not sure what this means.
very hard to wrap my head around haha
start by getting a handle on the actual rotation.
so looking right and left is based on the y axis
Correct.
and up and down is based on the x
A very common pattern is to:
- Rotate the player body around the Y axis
- Rotate the camera around the X axis
That's what the code you posted is doing.
Whatever you do, make sure to remove the delta time from the equation. It's framerate independent.
If the axis is mapped to the mouse, the value is different and will not be in the range of -1...1. Instead it'll be the current mouse delta multiplied by the axis sensitivity. Typically a positive value means the mouse is moving right/down and a negative value means the mouse is moving left/up.
This is frame-rate independent; you do not need to be concerned about varying frame-rates when using this value.
Struct fields all need to be initialized. If they are not initialized at declaration, you should implement a constructor that initializes them.
Are struct field initializers even allowed by unity's version of C#?
don't think so
Im coming from Gamemaker lol so this is scrambing my brain
huh, my unity 6 test project isn't complaining
i apprecaiate the help btw thanks
ah, but I think it's not going to compile in unity
yeah
it's just that something is misconfigured in my IDE
Ah, indeed. You can't initialize fields at declaration in C#.
You need C# 10 or higher for struct field initializers.
may aswell ask this while i am here, In the same tutorial he uses Mathf but uhh it doesnt work for me has it changed?
is there a diffrent way to use the clamp thingy
no, Mathf has not changed
IGNORE ME
Describe "doesn't work"
lol did something wrong haha sorry
make sure you have your spelling (particularly the capitalization) correct
i did a fullstop insted of equals
quite hard to understand this but ill get my grips lol
thanks again
If I can't initialize them how can I use structs in my ScriptableObject?
This is what I have atm: ```cs
public class ScriptableObjectTesting : ScriptableObject
{
enum Detectability
{
none,
detectBuildings,
detectBuildingsAndMonsters,
detectAll
}
[System.Serializable]
struct UpgradeData
{
public int upgradeID = 0;
public string upgradeName = "name";
public float scanSpeedMultiplier;
public float scanRangeMultiplier;
public Detectability detectability;
}
public UpgradeData[] upgradeData;
}
Initialize them in a constructor. I don't see how that's gonna prevent you from using them..?
note that it has to be a parameterized ctor, you cannot have an explicit parameterless ctor on a struct in unity's version of c# either
I'm trying to make a struct array on a scriptableobject
Hmm... I guess there's that as well. That being said, upgradID would be initialized as 0 by default anyway. And it doesn't seem like "name" has any functional meaning anyway.
So just don't assign these values.
If you really need "name" assigned, you could loop the array in OnValidate and assign it there to each element.
Wait, why doesnt upgradeID or upgradeName work?
the field initializers do not work. remove those and everything will compile
a field initializer is the initialization of the class level variable on the line it is declared. in other words those = and everything to the right of them are invalid in this version of c#
What I'm trying to do is create a struct array of variables that I can change in the inspector. Like this
But I want it on a scriptable object
yes and none of that info is relevant to the actual issue at hand
Currently the variables are inaccessible in the inspector. This is my code currently: ```cs
public enum Detectability
{
none,
detectBuildings,
detectBuildingsAndMonsters,
detectAll
}
public UpgradeData[] upgradeData;
[System.Serializable]
public struct UpgradeData
{
public float scanSpeedMultiplier;
public float scanRangeMultiplier;
public Detectability detectability;
public UpgradeData(int UpgradeID, string UpgradeName, float scanSpeed, float scanRange, Detectability detect)
{
this.scanSpeedMultiplier = scanSpeed;
this.scanRangeMultiplier = scanRange;
this.detectability = detect;
}
}```
that is not an instance of the scriptable object
Oh wait, I see now
My apologies
Although I do still have another problem. I was planning on accessing the upgradeName variable in another script, so I could display the name floating above an object.
then put the variable back on the struct. there was no need to remove it
Oh wait, I think I understand now.
You mean I can't assign the variables values inside the code, I can only assign it within the inspector.
just not in the field initializers
So I can't do this public string name = "defaultName"; but I can do this public string name;
That makes sense.
Thank you
trying to use a script to make all the parts of this model black but a couple of the model parts dont have a renderer, what should i do in that situation
most of the game objects will not have a renderer at all
unless this is some unusual model with lots of small pieces
either way, if there is no renderer, then there's no visual
its made up of several small pieces
so you can just skip that object
the object that caused the crash is highlighted and clearly its visible
use this:
if (target.TryGetComponent(out Renderer renderer)) {
// do something with the renderer
}
show me the entire inspector for the selected object
I think you're confusing objects.
also, yes, that's not the object that caused the error
there is a Renderer on this object
and the name is wrong
That's part of the armature, it looks like.
which won't have any renderers on it
my friend on laptop cant run my game well
wondering if theres any general project settings things i can mess with to help
profile the game to see where the biggest performance impacts come from
ooo how do i do that
thank you#
Just to be clear, by "can't run my game well" you mean performance drop/lag, right?
yeah
Then, yeah, profiling the game(ideally on the machine with the issue) is the way to go.
the gpu usage has a warning sign so its probably bad
the part thats really bad is the part where a you play on a UI canvas
and there are a bunch of rigibody objects u gotta dodge
Start with CPU usage
Rbs are part of the UI canvas?
yeah
ive heard that moving objects on a parent is bad optimisation
but they gotta be on the canvas to be visible
Having physical objects on a canvas is a terrible ida
Idea
But you should profile properly before deciding on any optimizations
I'm sure that's not true
And if it is, there must be a bigger issue with your setup
Because updating ui and physics is performance heavy. And if there are physical objects on the canvas, they would be affected by changes in UI and the UI would be affected by changes in the physics.
You should really start with some tutorial or the unity learn site if you think everything must be on a canvas
understood
okay if i have the canvas very low on the sorting layer it probably will let me do it right
have the objects infront of it
cuz usually canvas is ui and therefore infront of everything
If it's a screen space canvas, you can't have objects in front of it.
Why would you want to have ui behind your gameplay objects anyway?
because i need the pbjects to dodge to be infront of the canvas but not attatched to it as u said
ur confusing me
what diddnt get answrd
the canvas is the background to the moving objects
its like the undertale fights
dodge a buncha blobs
Why do you have your background as ui?
cause i had the whole game on a ui canvas
if my game is 3D besides that part how can i make that specific part be 2D
but not using a canvas
2d is just a plane/quad mesh. There isn't really "2d" in unity and most other engines.
So you can have a plane/quad mesh behind your other objects and render your background to it.
okay
I made a 16x16 texture for a basic cube but when I try to assign it as a sprite, I get "White Square_0's rect lies (partially) outside of texture. Will not generate Sprite for this slice." Please help me
private bool CanSeePlayer()
{
if (player == null) return false;
Vector3 directionToPlayer = player.position - transform.position;
float distanceToPlayer = Vector3.Distance(transform.position, player.position);
// First, check if the player is within the sight radius.
if (distanceToPlayer < sightRadius && !isDead)
{
RaycastHit hit;
// Then, do a raycast to see if there is a direct line of sight.
if (Physics.Raycast(transform.position, directionToPlayer.normalized, out hit, sightRadius, playerCheck))
{
// Check if the object hit is indeed the player.
return hit.transform == player;
}
}
return false;
}
playerCheck is a Mask for the player object
how do I make it hit the wall properly then
Im new to this so Im still learning this stuff 😅
Did you check that Layermasks as they suggested?
I tried removing the playerCheck mask from the Raycast line but it didnt seem to change the outcome
well shoot. had fingers crossed for an easy fix
me too xD
Show how you defined the layer mask?
// Serialized Fields
[SerializeField] private NavMeshAgent agent;
[SerializeField] private Transform player;
[SerializeField] private LayerMask groundCheck, playerCheck;
[SerializeField] private float health, sightRadius, attackRadius, walkingRadius/*, attackInterval*/;
[SerializeField] private bool isPatrolling = false;
[SerializeField] private Transform[] patrolPoints;
[SerializeField] private Animator animationController;
//public float AttackInterval => attackInterval;
[SerializeField] private AudioSource movingSound;
[SerializeField] private AudioSource idleSound;
[SerializeField] private AudioSource chasingSound;
[SerializeField] private AudioSource deathSound;
// Non-Serialized Fields
private bool isPlayerInSightRadius, isPlayerInAttackRadius;
private Vector3 walkNode;
private bool isWalkNodeSet = false;
private int patrolPointIndex = 0;
private bool isAttacking = false;
public bool Attacking => isAttacking;
private bool isIdle = true;
private bool isDead = false;
private bool CanSeePlayer()
{
if (player == null) return false;
Vector3 directionToPlayer = player.position - transform.position;
float distanceToPlayer = Vector3.Distance(transform.position, player.position);
// First, check if the player is within the sight radius.
if (distanceToPlayer < sightRadius && !isDead)
{
RaycastHit hit;
// Then, do a raycast to see if there is a direct line of sight.
if (Physics.Raycast(transform.position, directionToPlayer.normalized, out hit, sightRadius, playerCheck))
{
// Check if the object hit is indeed the player.
return hit.transform == player;
}
}
return false;
}
I mean show the inspector
That's still only hitting the player layer
Add the wall layer to it
public class EnemyDetection : MonoBehaviour {
public Material invisible;
public Material visible;
private void OnTriggerEnter(Collider c) {
if (c.CompareTag("Enemy")) {
for (int i = 1; i < c.transform.parent.childCount - 1; i++) {
Debug.Log(c.transform.parent.GetChild(i).GetComponent<Renderer>().material);
c.transform.parent.GetChild(i).GetComponent<Renderer>().material = visible;
}
}
}
private void OnTriggerExit(Collider c) {
if (c.CompareTag("Enemy")) {
for (int i = 1; i < c.transform.parent.childCount - 1; i++) {
Debug.Log(c.transform.parent.GetChild(i).GetComponent<Renderer>().material);
c.transform.parent.GetChild(i).GetComponent<Renderer>().material = invisible;
}
}
}
}```
using this code to turn every piece of a model to one material but when it goes through it sets it to default material, whered i go wrong
You didn't change it?
Im confused
Why are you adding a separate wall thing
ohhh
Add the wall layer to the Player Check LayerMask
I gothcu
If you click the player check field you'll see that you can select several layers
Wdym by "default material"?
its a bright pink and when i debug.log it says default material
If it's pink, it means that the shader is broken or incompatible
What did you assign those material fields to?
c.transform.parent.GetChild(i).GetComponent<Renderer>().material
I added the wall layer and nothing changed
Try visualizing your rays with Debug.DrawRay
https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html
what makes something incompatible bc if i manually add the material in the scene editor it works fine
Many things, but if it works manually, then it's probably an issue with your code
can you see any problems with the code then
Not really. Can you pause the game when the issue occurs, switch to scene view, select the pink objects and take a screenshot of the inspector?
alright
Also, check if there are any errors in the console
I wonder if just goes between the ground and the wall..? Can you offset it vertically a bit?
Debug the material that you're assigning.
I see. And the wall has a collider?
yea
Take a screenshot of the wall object inspector with it's layer visible too
Now the same thing at runtime when the debug ray is drawn
Okay, now share the updated code
put breakpoint at c.transform.parent.GetChild(i).GetComponent<Renderer>().material = visible;
Assign the Renderer to a local variable and step through the code again. Check the renderer material after stepping through the assignment.
Doesn't sound like a direct cause, but might be relevant.
var renderer = c.transform.parent.GetChild(i).GetComponent<Renderer>();
renderer.material = visible;```
not sure what i should be looking for
So you're assigning that SomeReflection material?
Ok, so it's assigned correctly at least
it was relevant xD but still not stopping them from seeing me, but it was returning False all the time for some reason 🥴
but now the logic is all in place and they're still seeing me through walls
One thing that bothers me is that it says (instance)
I just changed the logic in the canSeePlayer to compare for the "Player" tag so it can detect any part of the player instead of just the empty object used to define the location
whats that mean
Are you doing it at runtime or in the editor? Can you add. Debug.Break right after the assignment and check the object in the scene? Does it seem to have the correct material assigned and not pink?
at runtime
It means that it's a new instance of the material.
oh
Well, you're yet to share the updated code.
private bool CanSeePlayer()
{
if (player == null || isDead) return false;
Vector3 directionToPlayer = player.position - transform.position;
float distanceToPlayer = Vector3.Distance(transform.position, player.position);
if (distanceToPlayer < sightRadius)
{
RaycastHit hit;
Vector3 rayOrigin = transform.position;
Vector3 rayEnd = transform.position + directionToPlayer.normalized * sightRadius;
// Perform the raycast
if (Physics.Raycast(rayOrigin, directionToPlayer.normalized, out hit, sightRadius, playerCheck))
{
// Visualize the raycast
Debug.DrawLine(rayOrigin, hit.point, Color.red); // Red line to collision point
// Check if the object hit is indeed the player.
return hit.collider.CompareTag("Player");
}
else
{
// Visualize raycast when no collision occurs
Debug.DrawLine(rayOrigin, rayEnd, Color.green); // Green line if no hit
}
}
return false;
}
nope
Which makes sense I guess, since you're assigning it with material property.
havent changed much really
Hmm... What does it look like before that code runs?
You did at the very least add debug ray
Hmm. Share the updated code.
public class EnemyDetection : MonoBehaviour {
public Material invisible;
public Material visible;
private void OnTriggerEnter(Collider c) {
if (c.CompareTag("Enemy")) {
for (int i = 1; i < c.transform.parent.childCount - 1; i++) {
Debug.Log(c.transform.parent.GetChild(i).GetComponent<Renderer>().material);
var renderer = c.transform.parent.GetChild(i).GetComponent<Renderer>();
renderer.material = visible;
Debug.Break();
}
}
}
private void OnTriggerExit(Collider c) {
if (c.CompareTag("Enemy")) {
for (int i = 1; i < c.transform.parent.childCount - 1; i++) {
Debug.Log(c.transform.parent.GetChild(i).GetComponent<Renderer>().material);
c.transform.parent.GetChild(i).GetComponent<Renderer>().material = invisible;
}
}
}
}```
Hmm... Can you take a screenshot of the material you try to assign?
like the inspector?
Yes
Also, try using the sharedMaterial property instead of material.
still didnt work
And if you comment the code our, the issue doesn't happen?
youre asking if i comment the material setting code out the model doesnt turn pink?
Also, do you not have errors in the console when running this code?
no errors
Yes
That's weird. Do all of the children have a Renderer component?
yeah
Can you reference one of the renderers explicitly(in the inspector) and assign a material to it instead of getting the component from collided object?
oh wait a minute i found the issue
invisible and visible material arent set at runtime even though i set them in editor
What do you drag in there?
the materials from assets
From the assets tab?
yeah
Can you take a screenshot of them in the assets tab?
oh oops i was being dumb and set those variables while a game was running so they didnt save when i stopped the game
thanks for the help though i do have another issue
i have this enemy behavior script ```c#
public class EnemySystem : MonoBehaviour {
bool lookat = false;
public GameObject player;
Rigidbody rb;
public EnemyStats enemyStats;
public EnemyStats thisStats;
public PlayerDetection playerDetection;
public Animate animate;
public float hp;
public bool dying = false;
private void Start() {
rb = GetComponent<Rigidbody>();
playerDetection = transform.parent.GetComponentInChildren<PlayerDetection>();
animate = transform.GetComponent<Animate>();
hp = enemyStats.stats[StatNames.MaxHealth];
thisStats = enemyStats;
}
void Update() {
if (hp <= 0 && !dying) {
dying = true;
animate.Die();
}
if (playerDetection.found) {
lookat = true;
}
else lookat = false;
if (lookat) {
Vector3 newtarget = player.transform.position;
newtarget.y = transform.position.y;
transform.LookAt(newtarget);
animate.Chase();
rb.AddForce(thisStats.stats[StatNames.Speed] * Time.deltaTime * transform.forward);
} else if (!animate.anim.GetBool("isDying")){
animate.Reset();
}
}
...
but the enemies are walking through walls somehow
even though i made sure that collisions exist for both the enemy and the walls
You should use add force in fixed update, but I'm not sure that's the cause of this issue
One thing to try is to disable your animator.
what is fixed update
would i move just the addforce to fixedupdate or everything
The add force and anything required by it.
You also don't need to multiply force by delta time.
I would think the entire if-statement
And the if-statement prior could probably be refactored to lookat = playerDetection.found (semantic stuff though)
true
yeah didnt fix it
hello everyone , i have code singleton this :
public abstract class RingSingleton<T> : MonoBehaviour where T : RingSingleton<T>
{
private static T _instance;
public enum ChangeDestroy
{
DontDestroy,
Destroy
}
public ChangeDestroy _changDestroy = ChangeDestroy.Destroy;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
Debug.LogWarning("An instance of " + typeof(T) +
" is needed in the scene, but there is none.");
}
}
return _instance;
}
}
protected virtual void Awake()
{
if (_changDestroy == ChangeDestroy.DontDestroy)
{
DontDestroyOnLoad(gameObject);
}
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
return;
}
_instance = (T)this;
}
}
I use it like this: public class DataManager : RingSingleton<DataManager>
but when I use awake for DataManager and the code is as follows :protected override void Awake()
{
base.Awake();
DataBeforePlayGame.Instance.db = FirebaseFirestore.DefaultInstance;
Debug.LogError("Retrieve data");
Load();
if (!data.removeAdsData.IsRemoveAds())
{
AdsManager.Instance.PopupBanner();
}
}
I have set it to dont destroy on load but why is it displayed every time I switch to the debug scene?
presumably there is one of those objects inside the Debug scene so each time you enter that scene a new one is created which runs that code. and since you only return from the base implementation if you are destroying the object, the rest of the inheriting object's Awake method will run because it isn't destroyed until the end of the frame
just check if instance == this and return if it isn't
disabling the animator seemed to just break it entirely, it doesnt move at all
That would imply that you're not moving the object via physics, but via the animator.
Are you using dynamic(non kinematic) rbs?
no its kinematic
that right ?
Well, kinematic objects are not moved by forces.
i added the addforce and then the animator so itd be weird if it were moving by the animator
no, you need to do it in the derived class, you're already returning there if instance has already been assigned
and you need to return if Instance is not this
Well, I don't know what setup you had before, but now the issue is that you try to move kinematic rbs via force.
i tried removing the kinematics and the enemies just fall through the floor
And also, the animator is probably try to move the objects too. Disable root motion on it.
Do you have colliders on the floor?
I have it different from this , that's not right
ig i only check colliders for the player, maybe thats the reason why i dont fall through the floor and id do so otherwise
Check how? Layermask/collision matrix?
Where?
public class PlayerMovement : MonoBehaviour {
public CharacterController controller;
public PlayerStats playerStats;
public float speed;
public float multiplier = 1f;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
bool isSprinting;
void Start () {
speed = playerStats.stats[StatNames.Speed];
}
// Update is called once per frame
void Update() {
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0) {
velocity.y = -2f;
}```
btw it is against server rules to send an unsolicted DM to another user here
if you want help, i will help you here not in DMs
You wouldn't really need a ground check with dynamic rbs. Physics should handle collisions for you.
You also don't need to change velocity
If you use forces.
It seems like you were mixing all kinds of movement methods that resulted in a mess.
sorry, I didn't know that
How are you moving the player then?
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(multiplier * speed * Time.deltaTime * move);
if(Input.GetButtonDown("Jump") && isGrounded) {
velocity.y = Mathf.Sqrt(playerStats.stats[StatNames.JumpHeight] * -2f * gravity);
}
//gravity
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);```
So it's using a character controller
yeah
Why don't your enemies use a character controller then?
i thought that character controllers are for like voluntary movement
like its controlled by inputs
Both CC and RB are for moving objects. Whether you move them based on input or not is up to you
hey guys, is there any way to open a project using 5.6.4p2 editor version? I try many things but when I open this project, it shows a window and I have to login to confirm my lisense (i'm using free lisense), I logged in successfully and It doesnt happen anything, same crash but dont show working space window. I try to quit then open again but still nothing happened
add new lisence
Perhaps. It kinda feels like there're a lot of issues in your project.
I highly recommend going through the beginner pathways on unity !learn as well as referencing the manual and documentation when you encounter a component of system you've never used before. Also, following some tutorials instead of trying random implementations is also adviced.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
ok ill take a look thanks
I try bro, I create a new one account but not work 😦
but when I open a project in newer version, It still open without requiring lisense
so I think there is sth happen with older version
😩
i want to optimize the code further, i have a script that is used by more than 1000 objects in the game, all of them are tuned to have certain values already
right now i have 3 public fields in this code
public int enFontSize = 60;
public int tcFontSize = 60;
public int scFontSize = 60;```
*remember they already have certain value that is different than 60
if i make them into an array, will those value assigned on inspector lost?
Yes
Could write a script that does it perhaps 🤔
If it's just one script, could add the array and the run an editor function to populate the array with these variables, then save and remove the deprecated variables.
so i have this enemy hierarchy where zombie1 has a character controller but when it moves the viewsphere/attacksphere dont move so it stops seeing things when it moves out of it
so naturally i moved the viewsphere and attacksphere into zombie1 but suddenly the game became really laggy and viewsphere/attacksphere seemed to catch the player when its way out of their radii, dont know how that happened
Why did you need to move it to under the Zombie? Logically thinking, the Enemy is the object that should be moving, not the zombie
Unless Enemy is a container for all enemies in the scene
In which case it should be named Enemies
it is 3 public fields inside one script
thats it
but that script is used by 1000+ objects, thats what makes it annoying lol
Are these objects in the same scene?
enemy just holds all the things below it its just an empty object itself
scattered across 10+ scenes, also in 100+ prefabs that will generate by code during runtime
So it represents all the enemies in the scene?
no its just one enemy
Why do you need it then?
ig i dont need it
What components does it have?
That's gonna be problematic then.
it just has a mesh collider but idt i use it
Then it sounds like a redundant object.
yeah that means i must go thru all the contents in the game, even if i gonna have editor scripts doing it, if i forgot some place it will be disasterous
Btw, you said optimization, but that wouldn't really have any expected impact on performance.
ok removed it but issue persists
oh ok lol i just gonna go to next stuff
no worries
Well, to investigate the performance drop, you'll need to use the profiler. As for the "catching up" issue, I'm not sure I understand it correctly.
basically i use two spheres, one to detect the player to chase after them and another to make sure they can attack within a certain radius
I'm assuming you did not modify those three values for all 1000 items so just having an array initialized default to [60, 60, 60] should suffice.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/arrays
but when i move the spheres into the zombie parent somehow it like detects the player from way farther than it should
Where you'd modify the few specific items that you did change
in the prefab editor
What exactly are these spheres? Are they just visuals?
yeah theyre invisible spheres
What? If they're invisible then what's the point? Are they not visuals?
no theyre only there for collider logic
Ok.
- It might be better to use OverlapSphere instead of colliders.
- Let me guess - your zombie object is scaled?
howd you know
Because that would explain the issue. Parent scale applies to children. If you pause the game and look at the spheres when they're parented, you'll probably see that their gizmos are scaled as well.
oh
well even then the attackspheres are really small so the player shouldnt be in them when the enemies start off pretty far away
Typically, you shouldn't scale objects. If you really need to, only scale the visuals, so that they don't affect the game logic.
Have your game logic separate from visuals.
Then it might be some other issue as well.
What's the scale of the zombie object?
scaled 2x
attacksphere should only have radius of 5 and theyre placed like 50 units away typically
what i really dont understand is why the game suddenly lags so much
How do you know that the spheres detect the player when 50 units away?
For that you'd need to profile it
bc my hp goes down
also have a debug log that triggers when player enters it
That's not very reliable. Where in the code do you detect it?
Share the code
public class AttackDetection : MonoBehaviour {
public EnemyStats enemyStats;
public PlayerStats playerStats;
public GameObject sphere;
public static bool canHit = true;
public Animate animate;
private void Start() {
animate = transform.GetComponentInChildren<Animate>();
float scale = enemyStats.stats[StatNames.AttackRadius];
sphere.transform.localScale = new Vector3(scale, scale, scale);
}
private void OnTriggerEnter(Collider other) {
canHit = true;
}
private void OnTriggerStay(Collider c) {
if (c.name == "First Person Player" && canHit) {
animate.Attack();
StartCoroutine(Waiter());
}
}
private IEnumerator Waiter() {
canHit = false;
playerStats.Damage(enemyStats.stats[StatNames.Attack] - playerStats.stats[StatNames.Defense]);
yield return new WaitForSeconds(enemyStats.stats[StatNames.AttackInterval]);
canHit = true;
}
private void OnTriggerExit(Collider c) {
if (!animate.GetComponent<Animator>().GetBool("isDying")) animate.Reset();
canHit = false;
}
}
code for attack sphere
public class EnemySystem : MonoBehaviour {
public CharacterController controller;
bool lookat = false;
public GameObject player;
public EnemyStats enemyStats;
public EnemyStats thisStats;
public PlayerDetection playerDetection;
public Animate animate;
public float hp;
public bool dying = false;
private void Start() {
playerDetection = transform.GetComponentInChildren<PlayerDetection>();
animate = transform.GetComponent<Animate>();
hp = enemyStats.stats[StatNames.MaxHealth];
thisStats = enemyStats;
}
void Update() {
if (hp <= 0 && !dying) {
dying = true;
animate.Die();
}
lookat = playerDetection.found;
if (lookat) {
Vector3 newtarget = player.transform.position;
newtarget.y = transform.position.y;
transform.LookAt(newtarget);
animate.Chase();
Debug.Log(enemyStats.stats[StatNames.Speed] + " " + transform.forward);
controller.SimpleMove(enemyStats.stats[StatNames.Speed] * transform.forward);
}
else if (!animate.anim.GetBool("isDying")) {
animate.Reset();
}
}```
uses playerDetection which is the script for view sphere
I don't see any debug logs
Related to player detection
its not exactly related but it only logs if player is in the viewsphere (playerDetection.found returns true)
Where is playerDetection.found set to true?
Share the code
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class PlayerDetection : MonoBehaviour {
public EnemyStats enemyStats;
public GameObject sphere;
public bool found = false;
private void Start() {
float scale = enemyStats.stats[StatNames.SightRadius];
sphere.transform.localScale = new Vector3(scale, scale, scale);
}
private void OnTriggerEnter(Collider c) {
if (c.CompareTag("Player")) {
found = true;
}
}
private void OnTriggerExit(Collider c) { found = false; }
}
Debug the colliding object name.
Also add a Debug.Break and inspect the scene when it pauses.
Unless it cannot be triggered by anything other than player, you ought to only set found to false if the collider that triggered the exit callback method was tagged "Player".
And if you've got multiple players, you'll need to check if every player has left - you'd have a list of players and register/unregister them on the trigger events
there's a super obvious reason as to why this cube I've named Ground isn't showing up in game view right...?
Is the layer included in the camera culling mask?
Also, are you sure it's the correct camera? You seem to have 2
Try disabling the UI camera
layer is included, i tried setting the cube to default layer and camera to everything as well
and strangely disabling the UI camera fixes it, not sure why that would be
Your ui camera is marked as main, so it's rendered instead of the actual Main Camera
Wait, none of your cameras are marked as main, so it selects one randomly
i just noticed that myself
set the tag for the mainCam to MainCamera and still same issue
honestly it's how I had it setup on a different project from following some guides, never had any issue like this crop up
Are you testing in edit mode?
You'd typically use a screen space canvas for ui, not a camera.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Mornin' all,
I'm working on a top down controller (similar to Vampire Survivors), but I'm having a weird issue that I can't seem to figure out. Video attached for refrence.
Basically I'm not entirely sure why (probably a logic error) but I can't seem to get the up/down movement to work. I think I know where the error is, but I can't seem to figure out what I'm doing wrong.
https://hastebin.com/share/uzuhaluwon.csharp
Everything works fine, up until this section
if (mainCamera != null)
{
cameraForward = Vector3.Scale(mainCamera.transform.up, new Vector3(1, 0, 1).normalized);
move = moveY * cameraForward + moveX * mainCamera.transform.right;
}
else
{
move = moveY * Vector3.forward + moveX * Vector3.right;
}
Debug.Log("Move X = " + move.x);
Debug.Log("Move Y = " + move.y);
I'm 99% sure that I'm doing something wrong in the logic relating to the assigning of 'cameraForward'
Would anyone have any ideas please? 😕
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
sorry im not familiar with edit mode. if I wanted say, text to appear above an npc's head, when the player walked near it; would world space not be the correct route for that canvas?
Hold on, so what's the issue? Your character is supposed to move up n down, but it doesn't? Haven't had a look on the code yet.
World space canvas, yes. You don't need a second camera for it though.
Yeah, that's exactly it. The left/right works perfectly.
i suppose youre right, figured the reasoning for a second camera was to make it easy to hide all UI elements through disabling of a UI camera instead of going one by one turning them all off
Like I mentioned I'm positive it's something to do with how I'm assigning the value to cameraForward as everything works fine up until that point
You'll have some kind of a UI manager for that.
You multiple the camera's up axis by 0, which results cameraForward.y being 0 too.
cameraForward = Vector3.Scale(mainCamera.transform.up, new Vector3(1, 0, 1).normalized);
(0, 1, 0) * (1, 0, 1) -> (0, 0, 0)
Oh god dammit. lol. Yeah, that makes sense as the camera is pointing down it's relative forward/back would be the Y axis
I don't see why you have to multiply the vectors
Also I haven't heard about this method before and don't see why Unity wouldn't impelement it as Vector3's operator
It's part of making it so that the correct animation plays based on the rotation of the player (character always moves up/down/left/right in world space and not in the direction of travel, so setting the animation 'state' direction makes it go all screwy when rotating in a different direction of travel, if that makes any sense. lol. I'm following a video on doing it, but making a couple of changes to fit my game and preferred way of moving the character.
{
public Character()
{
Level = 1;
Experience = 0;
ExperienceToNextLevel = ServerVariables.CalcExperienceToNextLevel(this);
CurrentHealth = 100;```
What happens when I pass my object to another function while it's still in it's constructor? Does that work?
not to backtrack on bad habits but i did figure out why the UI cam was essentially overriding the Main Camera, forgot to set Clear Flags to depth only on the 2nd Cam
Just multiply the camera's up by your current move direction
Although I don't even see why it should depend on camera
Do you want to move your character in the direction the camera is facing?
I can just see it moving in a specific direction, as the camera's angle isn't changed at all
as i expected the viewsphere should not intersect with the player
Actually yeah, thinking about it, it does seem like an unnecessary step. I could just move the character in World Space (Vector3.forward/vector3.right yes?)
Yes, that's so. Make you know that right is (1, 0, 0) and forward is (0, 0, 1)
can someone help me with this
oh nvm dlich is back
0.5 * 35 = 17.5 radius. More than enough to collide with the player.
I don't even see the gizmos of the collider
but the player is like 30-50 units away
Ah, okay, I see it now.
So do the other things I suggested
Your CalcExperienceToNextLevel is simply going to use the Character without ExperienceToNextLevel and CurrentHealth assigned in the constructor
remind me what those things are again
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i debug.logged and debug.breaked it
Share the updated code with the logs
public class PlayerDetection : MonoBehaviour {
public EnemyStats enemyStats;
public GameObject sphere;
public bool found = false;
private void Start() {
float scale = enemyStats.stats[StatNames.SightRadius];
sphere.transform.localScale = new Vector3(scale, scale, scale);
}
private void OnTriggerEnter(Collider c) {
Debug.Log(c.name);
if (c.CompareTag("Player")) {
found = true;
Debug.Break();
}
}
private void OnTriggerExit(Collider c) {
if (c.CompareTag("Player")) {
found = false;
}
}
}
This short example gives the following output:
Foo constructor started
Bar constructor - foo: field1: 0; field2: ; field3:
Bar method - foo: field1: 0; field2: ; field3:
Bar method - foo: field1: 0; field2: 123; field3:
Foo constructor finished - foo: field1: 0; field2: 123; field3: 1; 10; 100; 123
public async Task<Character> CalculateCharacterStats(Character character)
Is this silly? I can just update the character in the parameter instead of having to return it right?
Right, the Character is a class, reference type, so there is a need to neither return its updated version nor using a ref keyword
So yes, simply change the parameter
should I still use Task? or does it make more sense to use a void?
it's not async either
Well, yeah, I don't see why you would use Task here?
So it seems to be colliding with First Person Player. Is that your player? Take a screenshot of it's hierarchy and inspector.
yeah
still a bit confused as to when I should use Task vs void
I read up on it a bit, but it's not very clear
as far as I remember it doesn't really matter that much
If you need to return something, use a task. Otherwise use a void. The only exception is if you want to have a handle to the async function.
Use tasks if you have any I/O-bound needs (such as requesting data from a network, accessing a database, or reading and writing to a file system)
If it's not the case, there is no need in using it
CalculateCharacterStats, probably, doesn't do it
Do you have any colliders parented to it?
collider is the viewsphere for player
Take a screenshot of it
It could be colliding with this collider
but the collider tag isnt player
It's a composite collider, since it has an rb as a parent.
So it's probably using the tag of the rb object.
Assign a kinematic rb to it and see if it changes anything.
basically same thing happened
in my game I just implemented Object Pooling. So when Player Picks up coin, its meant to deactivate the coin. But I get this following error when i pick it:
Your script should either check if it is null or you should not destroy the object.
ObjectPooler.SpawnFromPool (System.String tag, UnityEngine.Vector2 position) (at Assets/Scripts/ObjectPooler.cs:56)
CoinSpawner+<SpawnCoins>d__13.MoveNext () (at Assets/Scripts/CoinSpawner.cs:55)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <b1fe495152fd4f0180f79e56e3bccacc>:0)
{
if (!poolDictionary.ContainsKey(tag))
{
return null;
}
GameObject objectToSpawn = poolDictionary[tag].Dequeue();
objectToSpawn.transform.position = position;
objectToSpawn.transform.rotation = Quaternion.identity;
objectToSpawn.SetActive(true);
poolDictionary[tag].Enqueue(objectToSpawn);
return objectToSpawn;
}
public void DeactivateGameObject(string tag)
{
if (poolDictionary.ContainsKey(tag))
{
GameObject objectToRemove = poolDictionary[tag].Dequeue();
objectToRemove.SetActive(false);
poolDictionary[tag].Enqueue(objectToRemove);
}
}```
Okay. Going back to this screenshot, what is the view sphere parented to? To the zombie?
yeah
And it had what scale?
35
So both the sphere and the zombie have 35 scale??
Looks like you probably destroyed one of the pooled objects
zombie only has 2 scale
that means you destroy the gameobject somewhere and your pool implementation doesnt tell anything
Ok, then 2 * 35 * 0.5 is definitely big enough to include your player
I said that before, but you should avoid scaling objects involved with game logic
then how do i modify the view distance of enemies
Modify the collider radius instead. Using scaling for that is a terrible idea
And the zombie also shouldn't be scaled
Ooookay, this is annoying me. lol.
Here's my updated code, player now moves properly.....ish.
https://hastebin.com/share/opowasenuy.csharp
And a video for reference.
If you look at the debug on the localMove variable, x works fine (and drives animation properly), but the Y is just the raw movement input value and I'm not sure where I'm going wrong. 😕
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have a problem with the fact that my visual studio code has stopped highlighting words
Stopped? Are you sure you have your !ide configured?
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
• Other/None
What's the player's rotation?
Does not help
Are you sure you have read my 2nd question?
I've debugged the rotation so you can see what's going on. 😕
Your localMove is based on the player's rotation, so it's x and z axes aren't going to be 1 & 1 if your player's y position changes.
If you debug moveDir, you'll see that it's raw
Oh balls, I think I just spotted the mistake and it's idiotic. lol. moveDir is a Vector2, but should be a Vector3 (and I think would make things a lot easier.
ok im modifying scaling and fsr thats fixing the fps significantly but the attack sphere is still screwing up as shown here
clearly the player is not in this area
Consider using a site for huge code blocks, please
I don't think it will change a lot
Yeah maybe not, but tbh, it'll make it easier to 'read' without having to translate y/z all the time. lol.
LMAO. Okay well, funny story. Changing it to a Vector3 completely fixed the issue. lol.
Alright, so are you getting the raw values now?
public void Method1()
{
Debug.Log("Method1 before test");
TestMethod();
Debug.Log("Method1 after test");
}
void TestMethod()
{
Debug.Log("TestMethod");
}```
Hello method1 before test
Method1 after test are printing but test method is not printing even If I am calling the function. Anyone know why?
And I hope you have also fixed these lines. Assigning moveDir is better.
moveDir = move;
playerVelocity = new Vector3(moveDir.x * moveSpeed, 0f, moveDir.y * moveSpeed);
What the best way to check if a spawn position is "valid"? this is that it is a patch of ground that is a plausible point for spawn but that is also not near enough to some randomly generated points that would negate that area as "valid" (such as being to close to the player or another thing generated
Yeah, now it's working, I'm going to go through and clean up some stuff.
Like should I create colliders for valid points of spawn and invalid ones and check with some raycast or something around those lines?
Alright, yeah, forget what I have told you before about the axes depending on the rotation. I have confused it with both keys being pressed simultaneously.
In your code, you don't get 1 on both x and z when moving them together
Anyone?
No worries, seriously thank you for your help, very much appreciated 🙂
And yeah, I noticed only getting 0.71 when going diagonal, don't really understand that if honest. lol.
This is impossible. And use 3 ` to format your multiline code
Ik. But it's not printing for some reason.
Seems like a syntax or compile error somewhere
Recheck that
@maiden grail @modest latch check this
The diagonal vector is split when 2 vectors are applied in different directions. If you, for some reason, want it to always be 1, use Vector3.Normalize
Gotcha, thank you 🙂
I wonder whether you should ping people this way to check out your issue, unless you know them
It's okay. They are my friends and the ones who shared the problem. 
Check whether you have any syntax errors or you haven't updated the code
You might be not running the last version of your code, which makes your method not be called
i have already replaced the code where it was destroying the objects with calling the deactivate function
Sorry for the potentially idiotic question, but with the Vector3.Normalize, where and what would I do that to? (sorry, brain is a bit fried atm. lol.)
Debug the colliding object name.
its FirstPersonPlayer (Controller or whatever it was im away from my comp for a bit)
it happens immediately when i enter the enemy’s viewsphere
oops capsulecollider
Vector3.Normalize returns a Vector3 with the same direction, but a magnitude of 1.
Say, you have 2 Vectors: (5, 10, 2.5) and (50, 100, 25).
You may see that the Vectors have the same directions, but the 2nd one is simply 10 times larger than the 1st one. Applying this Vectors to you player's movement will result in a 10 times larger distance / force in the 2nd case.
Vector3.Normalize will modify these both Vectors and return at least a single axis, which equals to 1. Other axes will be less.
In this case, it will return (0.5, 1, 0.25) for both Vectors.
If you want to implement this kind of logic yourself, you'll have to take the largest axis of the Vector and make it 1, 100%. The other 2 axes should be calculated based on it.
100 - 1 (100%) z = 25 * 1 / 100 = 25 / 100
25 - z z = .25
100 - 1 (100%) x = 50 * 1 / 100 = 50 / 100
50 - x x = .5
Where 100 is the y axis
So it's correct..?
no because the attacksphere is 4 while the viewsphere is 20
Is it parented to the enemy with the rb?
And what's the scale of the object?
You might have missed a spot.
Or you might be reloading the scene
#archived-networking and there are tutorials out there on this exact thing. multiplayer really isnt for beginners
so i have an enemy prefab that uses a rigidbody, and its children include a large sphere collider that serves as a player detector sphere and a small sphere collider that serves as an attack radius, but because rigidbodies integrate the colliders it attacks at the same radius as the player detector sphere, how do i reorder the hierarchy to fix that
Add a kinematic rb to the attack collider and see if anything changes.
And share the latest code on the attack sphere
can someone help so i made a player model and it has like a image on it i made it with blender if i put it in unity the image doesnt show up and if i go to the back of my player model i see white on that image
ok
which object is this script on?
the attacksphere
ok, show the viewsphere code
So you are saying the OnTriggerEnter on the AttackSphere is firing at the same time as the OnTriggerEnter of the ViewSphere ?
yeah
then just test for other.gameObject
didnt work
bc the rigidbody combines the attacksphere and viewsphere into one so attacksphere has the same radius as viewsphere
i think thats how it works at least
but the colliders are on different game objects so other.gameObject should return differently
both children of one rigidbody object though
does not matter other.gameObject is the game object of the collider
evidently the fix doesnt work though
https://gdl.space/ecozayawoh.cpp
it would if you did it right
private void OnTriggerEnter(Collider other) {
Debug.Log(other.gameObject);
if(other.gameObject==gameObject) canHit = true;
}
Sorry, you are right, ignore what I said. Could do it for 2D but not for 3D
@gentle stratus which object is your rigidbody on?
the parent, enemy
ok try this
Enemy
-- Empty with RB
--- The rest of the objects
-- ViewSphere with kinematic RB
-- AttackSphere with kinematic RB
if your Player has a RB then you dont need the kinematic RB's on the Sphereobjects
Hello friends, I am making a 2D Platformer game, but when my character jumps to the corner of the platform above him, I wanted him to continue jumping by sliding from the corner. how do i do this (so corner correction)
You should debug the colliding object in on trigger enter. Also make the debug meaningful so that you can tell that the log is from this script and not from the view sphere or any other script.
private void OnTriggerEnter(Collider other) {
Debug.Log("object entered attack radius: " + other.gameObject.name);
canHit = true;
}
hello! I'm making a endless jumping game with mouse tracking shooting and wanted to add parallax to the bg. I got it to work with perspective camera and layering but now the mouse tracking is working but its really bad and barely is working. It's specifically because of the perspective background because when I switch it back to orthographic it immediately goes back to normal. Any ideas on how to fix this?
Oh sorry! I forgot to paste it.
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
private Camera mainCam;
private Vector3 mousePos;
public GameObject bullet;
public Transform bulletTransform;
public bool canFire;
private float timer;
public float timeBetweenFiring;
AudioSource shootSound;
// Start is called before the first frame update
void Start()
{
shootSound = GetComponent<AudioSource>();
mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
}
// Update is called once per frame
void Update()
{
mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector3 rotation = mousePos - transform.position;
float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
if (GlobalVariables.isFlipped)
{
transform.rotation = Quaternion.Euler(0, 0, rotZ + 180);
}
else
{
transform.rotation = Quaternion.Euler(0, 0, rotZ);
}
if (!canFire)
{
timer += Time.deltaTime;
if (timer > timeBetweenFiring)
{
canFire = true;
timer = 0;
}
}
if (Input.GetMouseButton(0) && canFire)
{
canFire = false;
Instantiate(bullet, bulletTransform.position, Quaternion.identity);
shootSound.Play();
}
}
}
is this ok?
mainCam = Camera.main btw
Sorry, im extremely new to unity and scripting, for the line that has FindGameObjectWithTag?
u can use mainCam.ScreenPointToRay instead.it give a ray direction that your bullet should heading
and you can get the final rotation by Quaternion.LookRotation(ray.direction, Vector3.up)
Yes, this is a better way to access the camera.
I don't think it's better than with tan^(-1)
You have mentioned the mouse tracking is working really badly. The code shouldn't cause you this kind of problems, as the angle is assigned correctly
Excuse me
Can I get a little help ?
Can anyone explain this to me ?
bool isOffset = (x % 2 == 0 && y % 2 != 0) || (x % 2 != 0 && y % 2 == 0);
Could you say how exactly is it not working properly?
@brazen canyon consider asking the full question in a single message, please
What exactly do you want to be explained?
x % 2 gives you either 0 or 1 if the x is odd or event respectively
0, 2, 4, 5, 6 -> 0
1, 3, 5, 7, 9 -> 1
I have never seen this kind of bool assignment before
When is the bool gonna be true, and when false ?
If its ok I send a video, I'm not sure how to verbally explain it
This boolean is going to be true if
xisoddandyiseven, orxisevenandxisodd
Okay ...
And false if both of them are odd or even
Of course, this can be simplified to
bool isOffset = x % 2 != y % 2;
What ??
At first look at this I couldn't understand
Read my previous messages. It returns false if both of them are odd or even
So if x % 2 == y % 2, it returns false
So, basically, x is odd & y is odd / x is even & y is even -> false
Otherwise return true
I haven't worked with the projections yet. It will take a while for me to check this out
The shooting is attached to wherever the arm is aiming so the projectiles arent that important (i think) its just that the arm cant track the mouse, I guessed it was because it was tracking way out where the perspective lines were rather than just in the view but I really dont know much..
I have a pretty basic problem:
My VS doesn't find UnityEngine.InputSystem. I tried several things already, including creating new .csproj-files.
I switched the Input system from "old" to "new" in the project settings as well
Restarted unity obviously.
any other ideas?
Visual Studio Code Editor (package) is in version 1.2.5
UnityEngine.InputSystem namespace cannot be used without Input System package installed
well, that makes sense. thought it would be there right from the start. How can I install it then? Not connected to git, nor sure where on the disk it is
There is pretty sure an easier way to install it, right?
nvm - I'm dumb
Unity Registry ofc
New Input System is not included from the start. Go to Windows -> Package Manager and search for Input System
Alright, I have found it.
The issue is in the method, which converts the mouse position to the world space, Camera.ScreenToWorldPoint(Vector3 position).
When the camera's projection is orthographic, you can simply pass the Input.mousePosition as the parameter.
When the camera's projection is perspective, the z axis of the position parameter is required, and passing the wrong value, 0 in your case, will result in the wrong rotation being calculated when there is some distance between the player and the camera.
The z axis, in the case with perspective camera, should correspond to the distance between the player and the camera. So simply calculating their position difference and making it Input.mousePosition's z axis, rotates the perspective camera correctly, regardless of the player's distance to the camera.
// where transform is the player's
transform.position.z - _mainCamera.transform.position.z
So the full world mouse position can be gotten this way:
Vector2 worldMousePos = _mainCamera.ScreenToWorldPoint(
new(screenMousePos.x, screenMousePos.y,
transform.position.z - _mainCamera.transform.position.z));
The orthographic camera's ScreenToWorldPoint method is not affected by the z axis at all, so calculating it, even with the changed z position, will result in no behavior change at all. The performance is just going to decrease unnoticeably.
The script I used for the reference, in case you need it.
Also make sure you use the feature I've used in the script, check if the current mouse position doesn't equal to the old one.
if (mousePos != _prevMousePos)
In case you wonder whether the rotation is going to mess up, if the distance between the player and the camera is changed, and no rotation is updated, because of the Input.mousePosition not being changed: it doesn't matter, as no rotation will be changed until the new Input.mousePosition is set, so changing the distance will just keep the rotation the same
Thank you so so much for this! I am struggling a lot editing my code with all this because I dont know anything about scripting (this is a assignment for a class) but I will try my best with putting this in!
Simply assigning the z axis, as I have mentioned in my previous resposnse, fixes it.
Implementing the code I have written isn't necessary, but it would make your code much more readable
Hi, I have problem with saving and loading data on android device. On windows everything works fine and it is saving and loading, but on android it's not. I added permissions requests in android manifest xml file, but it's still not working :/ Am I doing something wrong or maybe do I have to configure something more in Unity?]
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unity3d.player"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
<activity android:name="com.unity3d.player.UnityPlayerActivity"
android:theme="@style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
</application>
</manifest>
it worked thank you so much!
It was a pleasure to help, I have learned something new 
me too 🥲 youre a life saver,
What does it mean when the console says the object is active in the hierarchy but it isn't active in the hierarchy?
what are you logging
This means, you're using GameObject.activeSelf instead of GameObject.achiveInHierarchy
an object can be activeself but not active in hierarchy because a parent is inactive
Check [this](#💻┃code-beginner message) out
Consider showing your code
There's a possibility you're simply referencing the wrong object (a prefab instead of the scene object)
This isn't drawing the line between the child objects and I'm not sure where to debug why? public void Highlight() { for (int i = 0; i < PathPoints1.transform.childCount; i++) { if (i == PathPoints1.transform.childCount - 1) { lineRenderer.enabled = false; return; } else { int j = i + 1; lineRenderer.enabled = true; lineRenderer.SetPosition(0, pathPoints1[i].position); lineRenderer.SetPosition(1, pathPoints1[j].position); Debug.Log("I should be highlighting " + i + " & " + j + " ."); } } }
Log the path point object, child count and position count
Like this? Position count is always 2 Debug.Log("I should be highlighting pathpoint > " + pathPoints1[i] + " & pathpoint >" + pathPoints1[j] + " & PosCount is " + lineRenderer.positionCount);
What is it doing instead?
Is the line renderer on local space mode or world space mode?
World space and I can't see it doing anything. Ive tried changing the material, setting a color and increasing the size but I don't see anything other than the debuglog
Isn't your code just always going to disable the renderer?
Due to the if statement in the for loop
You're disabling the renderer every time 🤔🤔🤔
This will also show in the inspector that the renderer is disabled
I disabled that line for testing and it hasn't changed anything
I can see the object on the final part of the loop on the map
Ok but did you look at the inspector for the line renderer at runtime?
I am facing this null error when I pickup coin, I have removed all the code where it destroyed the gameobject but still the same problem. Whats crazy is that the OnTrigger function is working when its script is deactivated. Look below
CoinMove.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/CoinMove.cs:34)```
Code:
``` private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "Player")
{
//Destroy(gameObject);
if(gameObject != null)
{
op.DeactivateGameObject(gameObject.tag);
}
else
{
Debug.Log("NULL COIN", this);
}
}
}```
and which is line 34? op. ?
Yeah, I don't see anything change. With the code commented out, the line still shows at the end
then op is null
okay got it, fixed
I thought the line wasn't showing
I'm confused
Apologies, when I commented out the line to make hiding it; false - now all i see is the line between the final loop.
I don't understand what you mean by "now all I see is the line between the final loop"
Now I have changed the instantiation method to Object Pooling. But now my objects get deactivated with a delay if you can see. The colliders are working but the its working weird. Also If I hit a car of a specific type, all the types of that car will get deactivated. And last but not the least, Im facing fps drops, Please help urgently
The loop is running through a "path" and I'm trying to draw a line between each point so I can show the player which direction everything is going to move in. The loop shows me it's going through all the points in the path, but I don't see anything moving. Once I commented out "linerenderer.enabled = false", I can now see that the linerenderer is only showing on the final calculation.
The loop happens instantly
When are you expecting to see any intermediate part?
The game is not going to render until after the entire loop is finished running, at the end of the frame
Maybe you meant to make this a coroutine?
With a delay between each iteration?
That is exactly what I'm trying to do, then! Thanks very much
I'm running into a bit of a logic issue that I'm not sure how to fix - I want the spikes in my game to move progressively faster over time, but I'd like the distance between the spikes to remain the same, in other words as the spikes get faster, I want them to also spawn faster to account for the faster speed (otherwise you end up with larger and larger gaps), any idea how I could calculate this? Spike spawner: https://gdl.space/ekufukifaq.cs LevelManager (handles the speed scaling): https://gdl.space/oqorelawaw.cs
Hello, how can I access the ItemImage in this hierarchy and change its image?
The method I use seems ridiculous. I want to do this with the GetComponentsInChildren method.
This is my method : bilgiPanel.transform.GetChild(0).GetChild(1).GetChild(1).GetChild(0).GetChild(0).gameObject.GetComponent<Image>().sprite = bilgiitem.itemicon;
Update: tuning my prompt with chatgpt, it actually came up with this solution that fixed the problem:
Now I can alter the "+ 2" bit to adjust the spacing I want and it works perfectly
turn it into a variable and u can dynamic adjust it thru the inspector 😉
which I am actually very confused about because from what I understand, the Mathf.Max only does anything once the wait value gets too small, aside from that its the same as the original code?
well, if you had actually written the code instead of having a GPU generate it, maybe you'd know why it works 😉
I used to do what you said, but I need to do this in 6-7 scripts, not in one script, so I want to do it with GetComponentsInChildren, but I can't.
this is much easier if you have a variable on the script and drag the GameObject into the slot to reference the component . . .
Then drag references in to 6-7 different components.
I do not see the problem.
Mathf.Max is a function used to determine the maximum value among two or more given numbers
I see no reason for this to behave differently, yes, other than that the delay now can't go below 0.1
float a = 5;
float b = 8;
float c = 3;
float max = Mathf.Max(a, b, c);```
max will be 8 (b)
and if this is the same for all 6-7 objects, make it a prefab, drag the correct GameObject and use the prefab for those objects . . .
ok I will do that. My method is a bit lazy.
you can check the unity docs for the Mathf.Max method . . .
code is supposed to be lazy.. ur supposed to be programming "lazy" into ur systems 😉
smart lazy tho.. not dumb lazy
😄
i just did and i was correct no?
Mathf.Max wont do anything until the wait time calculation returns a float below 0.1f, in which case it will change wait time to 0.1f
correct
So you're spawning spikes at fixed locations, and they then move towards the player?
It doesn't look like spikeLeftPos and spikeRightPos are changing
ah, I see it
There is a very important difference between your original code and the new code
rnd + 1 / speed
vs
(rnd + 1) / speed
omg youre right
The original code does not divide rnd by speed, so the speed doesn't affect the random part of the delay
basic maths 😭
i see now, that makes a lot more sense
i cant believe i made that mistake tbh lol
order of operations
yup
who knew that'd come in handy
btw how do you "anchor" sprites/2D objects? so that the layout stays the same on different resolutions
i know how to do it with UI but i have no idea about sprites
You could use a script to set their positions based on screen size.
shift will set the pivot.. and alt will set the position
But this would mean that your gameplay changes as you change the screen size.
Not the best option.
thats only for rect transforms tho no?
I think you should try to adjust the camera to fit the objects
well, you could add a recttransform to your sprite objects
oh wait you can?
it's just a more specific kind of Transform
oh u mean 2d sprites? yea the camera adjustment sounds like it makes the most sense
but i think you want to change the camera
you would not move objects around in a 3D game based on your screen size
is there some sort of tutorial for it? im not sure what to search up
sounds like its time to work on a camera system
Cinemachine lets you target a group of objects and keep them all on screen.
If this is a pixel-art game, you will also want the pixel perfect camera component
so would that allow the game to look exactly the same on different mobile devices?
basically tells the camera to keep a, b, c targets in frame
yea, its camera logic.. it'd run the same on any platform
ive only used cinemachine for following the player before so im confused lol
you should read the documentation. it can do many things.
can be used for soo many different things
It would keep the objects on screen. It would not make things look exactly the same, though.
ya, it wouldn't be 1:1 but it wouldn't be unless the screens are the same
BUT it would follow the same rules..
there is also this tutorial i just found that uses this script, not sure if thats exactly what im looking for tho?
I presume this calculates a world-space position based on a viewport position
could be..
ill try both and test them out
prototyping! yes
theres never a 1 size fits all
so yea, trying them out for ur use-case and seeing what works the best is what u should do
prefab is just a normal gameobject
oh so if i drag the prefab in, it will still work when its instantiated?
u'd just add the gameobject to the script /component after u instantiate it
just as u would if u spawn a bullet and then need to add a force
i tried cinemachine and its working fine, but it does look different with different resolutions
its not a big difference tho so i might be able to work around it
game works the same and thats the main priority
Why don't you have a BulletController for this?
? i was just giving an example.. when I spawn bullets they're self contained.. the code the adds force is on the actual prefab.. just gotta spawn em
pls do check this
but its a usual occurance, when people spawn a prefab and then need to manipulate it somehow.. just gotta cache a reference first and then do it..
was an example of how u'd deal with adding prefabs to a target group.. you'd spawn ur prefab and then add it to the cinemachine targetgroup
Got it
i usually use this anyway
built-in component
I haven't known about its existance
yea, i didn't until recently.. theres a couple of different types
BulletController might also be inherited from it 😉
did someone know why this is locked?
select the gameobject the animation is controlling
im losing my mind. Why does my debug.drawline draws from this point and not its transform.position?
oh thank you so much for the video
transform.up is a direction, not a position
Looks like you want Debug.DrawRay instead
yeah i know, i just did it in reverse in hopes to change anything
and it works fine with this
thanks and fuck me lol
what's causing the infinite loop?
i dont see it causing dead loop
unity stops working when it runs
is this inside of a coroutine?
yes.
the break point isnt reached btw
so its something else causing unity to be stuck i suppose
the yield return null will make your coroutine gives up the cpu, i think you need to show your PlayStage() method
what does the coroutine PlayStage do?
this is the last line that runs
ill send it in a bit
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so is my code waiting for PlayStage to finish before running the rest of the code? beacuse there is a loop in there if the stage that its trying to play is a looped stage
first case in the switch statement
no, you just fire and forget another instance of ienumerator with startcoroutine
okay so why is it that my code stops here?
PlayStage can get stuck in a loop in two places
if s.transitionMarkers is empty or if trackData.audioSources[stageIndex].isPlaying is false
Not the latter one actually because it increments the index
but transitionMarkers can
thanks. fixed it 👍
how does one use the same gameobject (ui) to display different things based on values the client has, currently whenever a player joins, there is a joint healthbar that recieves the lives that should be for that client that just joined only, but also only the host can see the lives, where do i go from here?
script is a networkBehaviour but the lives ui gameobjetc and its canvas are nto network objects
how is it possible for the OnTriggerEnter2D to activate twice here?
same thing happens if I do Destroy(circleCollider)
Destroy runs at the end of the frame.
It's not instant.
disabling the collider will not help; the physics system has already figured out all collision and trigger messages that it needs to send
but even then, it is OnTriggerEnter2D
Consider adding a bool field that makes you ignore any additional messages
and it can only enter once
Perhaps it's hitting two different colliders on the player
or a collider and a trigger
the player has a rigidbody2d and a circlecollider2d could that be it?
but then again it only happens sometimes, like every few coins
maybe im spawning 2 at the same time somehow
no, a rigidbody is not a collider
Why not print the exact collider you're hitting
yup its that
you can check for this manually in the scene view, or you could log your instance ID
ah, there you go
am I wrong for thinking that the if statement can only go through on the last index of the for loop?