#💻┃code-beginner

1 messages · Page 339 of 1

swift crag
#

Figure out what the actual problem is first!

#

you can use Debug.Log to check which thing is null

polar acorn
#

I'm not sure what angle it could be that is outside of the range of -180 to 180

hasty spire
swift crag
#

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

polar acorn
tame mist
polar acorn
#

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

swift crag
#

you are looking at volumeSlider.value, yes

#

this is not volumeSlider

polar acorn
swift crag
#

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

hasty spire
small mantle
#

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.

hasty spire
#

ok the issue is the volume slider

swift crag
#

distance is not a "direction"

swift crag
small mantle
swift crag
#

Subtract the enemy's position from the player's position.

#

This gives you a vector pointing from the enemy to the player.

wintry quarry
#

B - A gives you the direction from A to B

swift crag
#

because...

C = B - A
A + C = A + (B - A) = A - A + B = B
small mantle
swift crag
#

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

small mantle
final totem
#

So is a scripteable object just a struct?

swift crag
#

No.

eternal needle
swift crag
#

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.

tepid pike
#

will somebody beable to guide me and help me with a gorilla tag fan based game that i have a idea for pls

swift crag
#
[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

final totem
#

Isn't it saved on disk?

swift crag
#

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

swift crag
#

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.

final totem
#

Gotcha, do you know what the static checkbox does in the inspector?

swift crag
#

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.

ionic zephyr
#

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

swift crag
#

You usually just toggle everything at once, from my experience

swift crag
ionic zephyr
swift crag
#

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

ionic zephyr
final totem
#

@swift crag so basically static does not contribute to lighting, does not occlude other stuff?

swift crag
#

occlusion culling lets Unity hide things that are completely behind a solid wall

ionic zephyr
#

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

swift crag
#

to do that, Unity needs to know what's a wall (something that doesn't move)

ionic zephyr
#

but that might be too complex

final totem
#

By default it's "nothing" cheked right?

swift crag
#

Right.

final totem
#

Thanks Fen

ionic zephyr
swift crag
#

sounds fine to me; you'd make a prefab with all of the boosts on it

final totem
swift crag
#

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

ionic zephyr
swift crag
#

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

abstract finch
#

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.

ionic zephyr
swift crag
#

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

ionic zephyr
swift crag
#
whateverMyBoostIs.Activate();
#

you don't care if it's a FireballBoost or a ShieldBoost

ionic zephyr
#

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??

ionic zephyr
swift crag
#

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

ionic zephyr
swift crag
#

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):
}
ionic zephyr
swift crag
#

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

ionic zephyr
#

Why did I choose to do this game hahaha

ionic zephyr
ionic zephyr
scarlet skiff
#

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

polar acorn
#

events are how you actually call the functions

#

events are basically delegate[] but with some syntactic sugar

bitter walrus
#

hi yall

scarlet skiff
polar acorn
#

delegate void SomeFunction(int x) defines the type SomeFunction that can hold anything that returns void and takes an int

final totem
#

What does the avatar field do in the Animator component?

deft grail
hasty tundra
#

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?

polar acorn
hasty tundra
#

would that work with onclick?

polar acorn
#

No, you'll need to use a raycast

slender nymph
#

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

ember tangle
#
#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
deft grail
ember tangle
#

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.

slender nymph
#

well that tells you which one to use then, doesn't it?

ember tangle
#

does using #ifndef instead make more sense?

deft grail
#

why cant you just use what works? why come up with other solutions when you already have a solution

ember tangle
#

im just trying to follow best practices 😅

deft grail
#

you will delete this when building the game anyway so who cares?

slender nymph
#

does ifndef even work in c#?

teal viper
slender nymph
teal viper
#

Hmm... Maybe it's different with C# compiler.🤔

molten dock
#

is there a general procedure for bugfixing bugs that only occur sometimes

#

like finding the cause

polar acorn
#

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

ionic zephyr
#

why cant i get a text gameobject reference attached to my component?

polar acorn
ionic zephyr
#

I cant fill the second gap with any gameobject

polar acorn
ionic zephyr
#

Im adding the TextMeshPro in UI gameobject

polar acorn
#

If you want to use a TextMeshPro object, use TMP_Text

ionic zephyr
#

whats the difference?

polar acorn
teal viper
ionic zephyr
#

Which is used more frequently to represent counters

ionic zephyr
polar acorn
#

TextMeshPro has completely replaced them

teal viper
#

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.

ionic zephyr
molten dock
#

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

polar acorn
molten dock
#

transform.position to another transform

polar acorn
molten dock
#

how come it would get transported to it most of the time then

polar acorn
#

because most of the time it is the object you expect it to be

molten dock
#

ill check it out

teal viper
#

Alternatively, that target object is moved around at some frames.

#

So when the issue happens it's at that invalid position.

cedar prairie
#

I may be stupid but i really dont get why brackeys here calls it xRotation when its all about the cameras Y rotation

swift crag
#

It's rotating the camera around the local X axis

#

X is right, so it's tilting up and down

cedar prairie
#

i am very confused haha

swift crag
#

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

elder osprey
#

I do have an error. I'm not sure what this means.

cedar prairie
#

very hard to wrap my head around haha

swift crag
cedar prairie
#

so looking right and left is based on the y axis

swift crag
#

Correct.

cedar prairie
#

and up and down is based on the x

swift crag
#

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.

ivory bobcat
# cedar prairie I may be stupid but i really dont get why brackeys here calls it xRotation when ...

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.

swift crag
#

The entire body rotates to look side to side

#

The camera rotates to look up and down

teal viper
swift crag
#

Are struct field initializers even allowed by unity's version of C#?

slender nymph
#

don't think so

cedar prairie
#

Im coming from Gamemaker lol so this is scrambing my brain

swift crag
#

huh, my unity 6 test project isn't complaining

cedar prairie
#

i apprecaiate the help btw thanks

swift crag
#

ah, but I think it's not going to compile in unity

#

yeah

#

it's just that something is misconfigured in my IDE

teal viper
#

Ah, indeed. You can't initialize fields at declaration in C#.

swift crag
#

You need C# 10 or higher for struct field initializers.

cedar prairie
#

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

slender nymph
#

no, Mathf has not changed

cedar prairie
#

IGNORE ME

cedar prairie
#

lol did something wrong haha sorry

slender nymph
#

make sure you have your spelling (particularly the capitalization) correct

cedar prairie
#

i did a fullstop insted of equals

#

quite hard to understand this but ill get my grips lol

#

thanks again

elder osprey
#

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;

}

teal viper
slender nymph
#

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

elder osprey
#

I'm trying to make a struct array on a scriptableobject

teal viper
#

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.

elder osprey
#

Wait, why doesnt upgradeID or upgradeName work?

slender nymph
#

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#

elder osprey
#

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

slender nymph
#

yes and none of that info is relevant to the actual issue at hand

elder osprey
#

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;
}

}```

slender nymph
#

that is not an instance of the scriptable object

elder osprey
#

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.

slender nymph
#

then put the variable back on the struct. there was no need to remove it

elder osprey
#

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.

slender nymph
#

just not in the field initializers

elder osprey
#

So I can't do this public string name = "defaultName"; but I can do this public string name;

#

That makes sense.

#

Thank you

gentle stratus
#

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

swift crag
#

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

gentle stratus
#

its made up of several small pieces

swift crag
#

so you can just skip that object

gentle stratus
#

the object that caused the crash is highlighted and clearly its visible

swift crag
#

use this:

if (target.TryGetComponent(out Renderer renderer)) {
  // do something with the renderer
}
swift crag
gentle stratus
#

hm ok

teal viper
swift crag
#

that's the hierarchy

#

i need to see the inspector

gentle stratus
#

oh my bad

swift crag
#

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

gentle stratus
#

oh i read it wrong

#

thanks

molten dock
#

my friend on laptop cant run my game well

#

wondering if theres any general project settings things i can mess with to help

slender nymph
#

profile the game to see where the biggest performance impacts come from

molten dock
#

ooo how do i do that

slender nymph
molten dock
#

thank you#

teal viper
molten dock
#

yeah

teal viper
#

Then, yeah, profiling the game(ideally on the machine with the issue) is the way to go.

molten dock
#

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

teal viper
teal viper
molten dock
#

yeah

#

ive heard that moving objects on a parent is bad optimisation

#

but they gotta be on the canvas to be visible

teal viper
#

Having physical objects on a canvas is a terrible ida

#

Idea

#

But you should profile properly before deciding on any optimizations

teal viper
#

And if it is, there must be a bigger issue with your setup

molten dock
#

its true

#

afaik

#

wait why is it bad

#

is it bc of what i said

teal viper
#

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.

eternal needle
#

You should really start with some tutorial or the unity learn site if you think everything must be on a canvas

molten dock
#

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

teal viper
#

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?

molten dock
#

because i need the pbjects to dodge to be infront of the canvas but not attatched to it as u said

teal viper
#

That doesn't answer my question

#

Why do you need ui behind other objects?

molten dock
#

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

teal viper
#

Why do you have your background as ui?

molten dock
#

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

teal viper
#

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.

molten dock
#

okay

latent iris
#

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

stiff peak
#
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 😅

near wadi
#

Did you check that Layermasks as they suggested?

stiff peak
#

I tried removing the playerCheck mask from the Raycast line but it didnt seem to change the outcome

near wadi
#

well shoot. had fingers crossed for an easy fix

stiff peak
#

me too xD

wintry quarry
#

Show how you defined the layer mask?

stiff peak
#
 // 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;
 }
wintry quarry
#

I mean show the inspector

#

That's still only hitting the player layer

#

Add the wall layer to it

stiff peak
gentle stratus
#
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
wintry quarry
stiff peak
#

Im confused

wintry quarry
#

Why are you adding a separate wall thing

stiff peak
#

ohhh

wintry quarry
#

Add the wall layer to the Player Check LayerMask

stiff peak
#

I gothcu

teal viper
# stiff peak

If you click the player check field you'll see that you can select several layers

stiff peak
wintry quarry
gentle stratus
#

its a bright pink and when i debug.log it says default material

teal viper
wintry quarry
gentle stratus
#

c.transform.parent.GetChild(i).GetComponent<Renderer>().material

stiff peak
#

I added the wall layer and nothing changed

teal viper
gentle stratus
teal viper
gentle stratus
stiff peak
#

Ive been spotted

teal viper
gentle stratus
#

alright

teal viper
#

Also, check if there are any errors in the console

gentle stratus
#

no errors in console

#

ig somehow its not setting material

teal viper
# stiff peak

I wonder if just goes between the ground and the wall..? Can you offset it vertically a bit?

stiff peak
#

well

#

it aint that

teal viper
teal viper
stiff peak
#

yea

teal viper
#

Take a screenshot of the wall object inspector with it's layer visible too

stiff peak
teal viper
#

Now the same thing at runtime when the debug ray is drawn

stiff peak
teal viper
gentle stratus
teal viper
#

Assign the Renderer to a local variable and step through the code again. Check the renderer material after stepping through the assignment.

stiff peak
#

wait

#

I think I know my issue

#

i might be really dumb

teal viper
#

Doesn't sound like a direct cause, but might be relevant.

gentle stratus
#

not sure what i should be looking for

teal viper
gentle stratus
#

oh oops i forgot to step after it executed

teal viper
#

Ok, so it's assigned correctly at least

stiff peak
#

but now the logic is all in place and they're still seeing me through walls

teal viper
stiff peak
#

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

gentle stratus
#

whats that mean

teal viper
# gentle stratus

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?

gentle stratus
#

at runtime

teal viper
gentle stratus
#

oh

teal viper
stiff peak
#
    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;
    }
teal viper
stiff peak
#

havent changed much really

teal viper
teal viper
gentle stratus
#

something like this

#

somereflection was added in editor

teal viper
gentle stratus
#
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;
            }
        }
    }
}```
teal viper
gentle stratus
#

like the inspector?

teal viper
#

Yes

gentle stratus
teal viper
#

Also, try using the sharedMaterial property instead of material.

gentle stratus
#

still didnt work

teal viper
gentle stratus
#

youre asking if i comment the material setting code out the model doesnt turn pink?

teal viper
gentle stratus
#

no errors

gentle stratus
#

ok lemme try

#

no models turned pink

teal viper
gentle stratus
#

yeah

teal viper
#

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?

gentle stratus
#

oh wait a minute i found the issue

#

invisible and visible material arent set at runtime even though i set them in editor

teal viper
#

What do you drag in there?

gentle stratus
#

the materials from assets

teal viper
#

From the assets tab?

gentle stratus
#

yeah

teal viper
#

Can you take a screenshot of them in the assets tab?

gentle stratus
#

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

teal viper
#

One thing to try is to disable your animator.

gentle stratus
#

what is fixed update

gentle stratus
#

would i move just the addforce to fixedupdate or everything

teal viper
#

The add force and anything required by it.

#

You also don't need to multiply force by delta time.

ivory bobcat
#

I would think the entire if-statement

#

And the if-statement prior could probably be refactored to lookat = playerDetection.found (semantic stuff though)

gentle stratus
#

true

teal viper
ionic galleon
#

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?

slender nymph
#

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

gentle stratus
teal viper
#

Are you using dynamic(non kinematic) rbs?

gentle stratus
#

no its kinematic

teal viper
#

Well, kinematic objects are not moved by forces.

gentle stratus
#

i added the addforce and then the animator so itd be weird if it were moving by the animator

slender nymph
#

and you need to return if Instance is not this

teal viper
gentle stratus
#

i tried removing the kinematics and the enemies just fall through the floor

teal viper
#

And also, the animator is probably try to move the objects too. Disable root motion on it.

teal viper
ionic galleon
gentle stratus
teal viper
gentle stratus
#

yeah

#

layermask

teal viper
#

Where?

gentle stratus
#
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;
        }```
slender nymph
#

if you want help, i will help you here not in DMs

teal viper
#

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.

gentle stratus
#

well player works fine

#

its only the enemy adding force that screws up

ionic galleon
teal viper
gentle stratus
#
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);```
teal viper
#

So it's using a character controller

gentle stratus
#

yeah

teal viper
#

Why don't your enemies use a character controller then?

gentle stratus
#

i thought that character controllers are for like voluntary movement

#

like its controlled by inputs

teal viper
#

Both CC and RB are for moving objects. Whether you move them based on input or not is up to you

gentle stratus
#

oh ok

#

would cc possibly fix the walking through walls thing then

mighty yew
#

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

teal viper
# gentle stratus would cc possibly fix the walking through walls thing then

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.

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

gentle stratus
#

ok ill take a look thanks

mighty yew
#

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

#

😩

nimble apex
#

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?
nimble apex
#

ok i gonna give up doing that ty lol

#

no way i gonna remap 3000 values

teal viper
#

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.

gentle stratus
#

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

teal viper
#

Unless Enemy is a container for all enemies in the scene

#

In which case it should be named Enemies

nimble apex
#

thats it

#

but that script is used by 1000+ objects, thats what makes it annoying lol

teal viper
gentle stratus
#

enemy just holds all the things below it its just an empty object itself

nimble apex
teal viper
gentle stratus
#

no its just one enemy

teal viper
gentle stratus
#

ig i dont need it

teal viper
#

What components does it have?

teal viper
gentle stratus
#

it just has a mesh collider but idt i use it

teal viper
nimble apex
teal viper
gentle stratus
nimble apex
#

no worries

teal viper
gentle stratus
#

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

ivory bobcat
gentle stratus
#

but when i move the spheres into the zombie parent somehow it like detects the player from way farther than it should

ivory bobcat
#

Where you'd modify the few specific items that you did change

gentle stratus
#

in the prefab editor

teal viper
gentle stratus
#

yeah theyre invisible spheres

teal viper
gentle stratus
#

no theyre only there for collider logic

teal viper
#

Ok.

  1. It might be better to use OverlapSphere instead of colliders.
  2. Let me guess - your zombie object is scaled?
gentle stratus
#

howd you know

teal viper
#

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.

gentle stratus
#

oh

#

well even then the attackspheres are really small so the player shouldnt be in them when the enemies start off pretty far away

teal viper
#

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.

teal viper
#

What's the scale of the zombie object?

gentle stratus
#

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

teal viper
#

How do you know that the spheres detect the player when 50 units away?

teal viper
gentle stratus
#

also have a debug log that triggers when player enters it

teal viper
gentle stratus
#
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
teal viper
#

Related to player detection

gentle stratus
#

its not exactly related but it only logs if player is in the viewsphere (playerDetection.found returns true)

teal viper
#

Share the code

gentle stratus
#
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; }
}
teal viper
#

Also add a Debug.Break and inspect the scene when it pauses.

ivory bobcat
#

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

frail whale
#

there's a super obvious reason as to why this cube I've named Ground isn't showing up in game view right...?

teal viper
#

Also, are you sure it's the correct camera? You seem to have 2

#

Try disabling the UI camera

frail whale
#

and strangely disabling the UI camera fixes it, not sure why that would be

teal viper
#

Wait, none of your cameras are marked as main, so it selects one randomly

frail whale
#

i just noticed that myself

#

set the tag for the mainCam to MainCamera and still same issue

teal viper
#

Why would need 2 cameras anyway?

#

You shouldn't need a separate camera for ui

frail whale
#

honestly it's how I had it setup on a different project from following some guides, never had any issue like this crop up

teal viper
teal viper
ruby python
#

!code

eternal falconBOT
ruby python
#

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://streamable.com/i7rssa

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? 😕

Watch "2024-05-10 06-41-22" on Streamable.

▶ Play video
frail whale
willow scroll
teal viper
ruby python
frail whale
ruby python
teal viper
willow scroll
ruby python
willow scroll
#

Also I haven't heard about this method before and don't see why Unity wouldn't impelement it as Vector3's operator

ruby python
# willow scroll I don't see why you have to multiply the vectors

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.

topaz mortar
#
     {
        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?
frail whale
willow scroll
#

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

gentle stratus
ruby python
willow scroll
gentle stratus
#

oh nvm dlich is back

teal viper
#

I don't even see the gizmos of the collider

gentle stratus
#

but the player is like 30-50 units away

teal viper
#

Ah, okay, I see it now.

teal viper
willow scroll
topaz mortar
#

perfect

#

wouldn't want any weird NullReferenceErrors

gentle stratus
willow scroll
#

!code

eternal falconBOT
gentle stratus
#

i debug.logged and debug.breaked it

teal viper
gentle stratus
#
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;
        }
    }
}
willow scroll
topaz mortar
#

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?

willow scroll
#

So yes, simply change the parameter

topaz mortar
#

should I still use Task? or does it make more sense to use a void?

#

it's not async either

willow scroll
teal viper
gentle stratus
#

yeah

topaz mortar
#

as far as I remember it doesn't really matter that much

gentle stratus
teal viper
willow scroll
#

CalculateCharacterStats, probably, doesn't do it

teal viper
gentle stratus
#

collider is the viewsphere for player

teal viper
gentle stratus
teal viper
gentle stratus
#

but the collider tag isnt player

teal viper
#

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.

gentle stratus
#

basically same thing happened

slate haven
#

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);

        }


    }```
teal viper
gentle stratus
#

yeah

teal viper
gentle stratus
#

35

teal viper
#

So both the sphere and the zombie have 35 scale??

wintry quarry
gentle stratus
#

zombie only has 2 scale

gaunt ice
teal viper
#

I said that before, but you should avoid scaling objects involved with game logic

gentle stratus
#

then how do i modify the view distance of enemies

teal viper
#

Modify the collider radius instead. Using scaling for that is a terrible idea

#

And the zombie also shouldn't be scaled

ruby python
#

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.

https://streamable.com/82r9mg

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. 😕

Watch "2024-05-10 07-30-44" on Streamable.

▶ Play video
white iron
#

I have a problem with the fact that my visual studio code has stopped highlighting words

willow scroll
eternal falconBOT
willow scroll
white iron
willow scroll
ruby python
willow scroll
#

If you debug moveDir, you'll see that it's raw

ruby python
gentle stratus
#

clearly the player is not in this area

willow scroll
willow scroll
ruby python
ruby python
willow scroll
patent compass
#
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?
willow scroll
frigid sequoia
#

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

ruby python
frigid sequoia
#

Like should I create colliders for valid points of spawn and invalid ones and check with some raycast or something around those lines?

willow scroll
#

In your code, you don't get 1 on both x and z when moving them together

ruby python
willow scroll
patent compass
frigid sequoia
#

Recheck that

patent compass
#

@maiden grail @modest latch check this

willow scroll
willow scroll
patent compass
willow scroll
#

You might be not running the last version of your code, which makes your method not be called

slate haven
ruby python
gentle stratus
#

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

willow scroll
# ruby python Sorry for the potentially idiotic question, but with the Vector3.Normalize, wher...

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

teal viper
gentle stratus
#

no because the attacksphere is 4 while the viewsphere is 20

teal viper
#

And what's the scale of the object?

gentle stratus
#

scale is 1

#

and yeah its parent has an rb

wintry quarry
eternal needle
#

#archived-networking and there are tutorials out there on this exact thing. multiplayer really isnt for beginners

gentle stratus
#

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

teal viper
#

And share the latest code on the attack sphere

gentle stratus
#

rb didnt fix it

queen adder
#

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

queen adder
#

ok

languid spire
gentle stratus
#

the attacksphere

languid spire
#

ok, show the viewsphere code

gentle stratus
languid spire
#

So you are saying the OnTriggerEnter on the AttackSphere is firing at the same time as the OnTriggerEnter of the ViewSphere ?

gentle stratus
#

yeah

languid spire
#

then just test for other.gameObject

gentle stratus
#

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

languid spire
#

but the colliders are on different game objects so other.gameObject should return differently

gentle stratus
#

both children of one rigidbody object though

languid spire
#

does not matter other.gameObject is the game object of the collider

gentle stratus
languid spire
#

it would if you did it right

#
private void OnTriggerEnter(Collider other) {
        Debug.Log(other.gameObject);
        if(other.gameObject==gameObject) canHit = true;
    }
gentle stratus
#

now they never attack

#

because they keep comparing themselves to the player

languid spire
#

@gentle stratus which object is your rigidbody on?

languid spire
#

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

swift vessel
#

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)

teal viper
#
private void OnTriggerEnter(Collider other) {
        Debug.Log("object entered attack radius: " + other.gameObject.name);
canHit = true;
}
dusty salmon
#

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?

rare basin
#

maybe share the code so we can actually see it

#

how can we tell whats wrong ;p

dusty salmon
#

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?

rare basin
#

mainCam = Camera.main btw

dusty salmon
#

Sorry, im extremely new to unity and scripting, for the line that has FindGameObjectWithTag?

harsh shale
#

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)

willow scroll
willow scroll
willow scroll
brazen canyon
#

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);

willow scroll
#

@brazen canyon consider asking the full question in a single message, please

willow scroll
#

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
brazen canyon
dusty salmon
willow scroll
willow scroll
#

And false if both of them are odd or even

willow scroll
brazen canyon
willow scroll
#

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

willow scroll
dusty salmon
#

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..

civic cradle
#

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

willow scroll
civic cradle
#

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

willow scroll
willow scroll
# dusty salmon The shooting is attached to wherever the arm is aiming so the projectiles arent ...

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

dusty salmon
#

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!

willow scroll
#

Implementing the code I have written isn't necessary, but it would make your code much more readable

desert ferry
#

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>
willow scroll
dusty salmon
topaz eagle
#

What does it mean when the console says the object is active in the hierarchy but it isn't active in the hierarchy?

willow scroll
languid spire
ivory bobcat
#

Consider showing your code

#

There's a possibility you're simply referencing the wrong object (a prefab instead of the scene object)

karmic kindle
#

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 + " ."); } } }

ivory bobcat
#

Log the path point object, child count and position count

karmic kindle
wintry quarry
karmic kindle
wintry quarry
#

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

karmic kindle
wintry quarry
#

Did you look at the inspector?

#

Is the renderer enabled

karmic kindle
#

I can see the object on the final part of the loop on the map

wintry quarry
#

Ok but did you look at the inspector for the line renderer at runtime?

slate haven
#

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);
            }
            
        }
    }```
languid spire
#

and which is line 34? op. ?

karmic kindle
slate haven
#

op

languid spire
#

then op is null

slate haven
#

okay got it, fixed

wintry quarry
#

I'm confused

karmic kindle
wintry quarry
slate haven
#

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

karmic kindle
wintry quarry
#

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?

karmic kindle
#

That is exactly what I'm trying to do, then! Thanks very much

rancid tinsel
#

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

atomic yew
#

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;

rancid tinsel
#

Now I can alter the "+ 2" bit to adjust the spacing I want and it works perfectly

rocky canyon
#

turn it into a variable and u can dynamic adjust it thru the inspector 😉

rancid tinsel
#

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?

swift crag
#

well, if you had actually written the code instead of having a GPU generate it, maybe you'd know why it works 😉

atomic yew
cosmic dagger
swift crag
#

I do not see the problem.

rocky canyon
swift crag
rocky canyon
#
float a = 5;
float b = 8;
float c = 3;
float max = Mathf.Max(a, b, c);```
max will be 8 (b)
cosmic dagger
atomic yew
cosmic dagger
rocky canyon
#

code is supposed to be lazy.. ur supposed to be programming "lazy" into ur systems 😉

#

smart lazy tho.. not dumb lazy

rancid tinsel
#

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

swift crag
#

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
rancid tinsel
swift crag
#

The original code does not divide rnd by speed, so the speed doesn't affect the random part of the delay

rancid tinsel
#

basic maths 😭

#

i see now, that makes a lot more sense

#

i cant believe i made that mistake tbh lol

rocky canyon
#

order of operations

rancid tinsel
#

yup

rocky canyon
#

who knew that'd come in handy

rancid tinsel
#

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

rocky canyon
swift crag
#

You could use a script to set their positions based on screen size.

rocky canyon
#

shift will set the pivot.. and alt will set the position

swift crag
#

But this would mean that your gameplay changes as you change the screen size.

#

Not the best option.

rancid tinsel
swift crag
#

I think you should try to adjust the camera to fit the objects

#

well, you could add a recttransform to your sprite objects

rancid tinsel
#

oh wait you can?

swift crag
#

it's just a more specific kind of Transform

rocky canyon
swift crag
#

but i think you want to change the camera

#

you would not move objects around in a 3D game based on your screen size

rancid tinsel
rocky canyon
#

sounds like its time to work on a camera system

swift crag
#

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

rancid tinsel
rocky canyon
#

basically tells the camera to keep a, b, c targets in frame

#

yea, its camera logic.. it'd run the same on any platform

rancid tinsel
#

ive only used cinemachine for following the player before so im confused lol

swift crag
#

you should read the documentation. it can do many things.

rocky canyon
#

can be used for soo many different things

swift crag
rocky canyon
#

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..

rancid tinsel
#

there is also this tutorial i just found that uses this script, not sure if thats exactly what im looking for tho?

swift crag
#

I presume this calculates a world-space position based on a viewport position

rocky canyon
#

could be..

rancid tinsel
#

ill try both and test them out

rocky canyon
#

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

rancid tinsel
#

would the cinemachine method work for prefabs?

#

since you have to reference it

rocky canyon
#

prefab is just a normal gameobject

rancid tinsel
#

oh so if i drag the prefab in, it will still work when its instantiated?

rocky canyon
#

u'd just add the gameobject to the script /component after u instantiate it

rancid tinsel
#

ah after

#

got it

rocky canyon
#

just as u would if u spawn a bullet and then need to add a force

rancid tinsel
#

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

willow scroll
rocky canyon
#

? 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

rocky canyon
#

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

willow scroll
#

Got it

rocky canyon
#

built-in component

willow scroll
rocky canyon
#

yea, i didn't until recently.. theres a couple of different types

willow scroll
#

BulletController might also be inherited from it 😉

timid hinge
#

did someone know why this is locked?

rocky canyon
muted cradle
#

im losing my mind. Why does my debug.drawline draws from this point and not its transform.position?

timid hinge
#

oh thank you so much for the video

zenith cypress
#

transform.up is a direction, not a position

#

Looks like you want Debug.DrawRay instead

muted cradle
muted cradle
#

thanks and fuck me lol

vast vessel
#

what's causing the infinite loop?

gaunt ice
#

i dont see it causing dead loop

vast vessel
#

unity stops working when it runs

cosmic dagger
#

is this inside of a coroutine?

vast vessel
#

the break point isnt reached btw

#

so its something else causing unity to be stuck i suppose

gaunt ice
#

the yield return null will make your coroutine gives up the cpu, i think you need to show your PlayStage() method

cosmic dagger
#

what does the coroutine PlayStage do?

vast vessel
#

this is the last line that runs

vast vessel
cosmic dagger
#

!code

eternal falconBOT
vast vessel
#

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

vast vessel
gaunt ice
#

no, you just fire and forget another instance of ienumerator with startcoroutine

vast vessel
keen dew
#

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

vast vessel
scarlet skiff
#

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

rancid tinsel
#

how is it possible for the OnTriggerEnter2D to activate twice here?

#

same thing happens if I do Destroy(circleCollider)

swift crag
#

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

rancid tinsel
#

but even then, it is OnTriggerEnter2D

swift crag
#

Consider adding a bool field that makes you ignore any additional messages

rancid tinsel
#

and it can only enter once

swift crag
#

Perhaps it's hitting two different colliders on the player

#

or a collider and a trigger

rancid tinsel
#

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

swift crag
#

no, a rigidbody is not a collider

wintry quarry
rancid tinsel
swift crag
#

ah, there you go

rancid tinsel
#

am I wrong for thinking that the if statement can only go through on the last index of the for loop?

swift crag
#

looks valid to me

#

it also requires rndCoin == 1, of course