#💻┃code-beginner
1 messages · Page 280 of 1
yeah happens to the other sprites i use
i changed format to the best one but after changing it to automatic and changing compression nothing changes anyway
hi i dont know what this errors means
Do you have a script called ItemPlacementData?
What is an ItemPlacementData?
If so, is it in a namespace?
no, that is the proplem
forget it, thanks btw
what would be the cause where the TMP_Text i assigned at the editor is suddenly missing when i instantiated the gameobject which is a prefab?
Do you reassign it in code
Show !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 only assign the text that should be changed
Show the code
is the prefab referencing a TMP element thats inside hte prefab? or is it in the scene?
https://hatebin.com/fkoqzwjcqi - This script is directly attached to the gameobject
https://hatebin.com/evsnfittql - This script runs a method to the first one which tries to update the contents of the TMP_Text
its inside the prefab
I tried reassigning it in the prefab view
Okay, what field is missing when you instantiate it?
All TMP_Text
On which script?
The first one
The parent GameObject appears but the childs it was supposed to come with are missing
Your Confirm function overwrites DebName and TeamName, are you sure the values you're passing in are valid?
Debate Manager?
ohh ic
Also, why is debDataHolderPrefab of type GameObject if literally the first thing you do is a GetComponent? Just make the variable of type DebaterHolder
ill change it. I applied it in later script but havnt applied it to other older parts
The values are valid
i can see the instantiated gameobject with both variables appearing with the inputed text
Can you open up the prefab and show a screenshot of the inspector of it
Okay, so, RoundXArea is set to itself, and the first thing you do in that function is destroy all children of RoundXArea
Ohh
So the reason it says all of those text components are missing is because they're missing
I have this code from a package that i modfied:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.VR;
using TMPro;
public class ColorScript : MonoBehaviour
{
public TextMeshPro ColorText;
public float Red;
public float Blue;
public float Green;
float TrueRed;
float TrueBlue;
float TrueGreen;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
ColorText.text = string(Vector3(Red,Blue,Green));
TrueRed = Red / 10;
TrueBlue = Blue / 10;
TrueGreen = Green / 10;
Color myColour = new Color(TrueRed, TrueBlue, TrueGreen);
PhotonVRManager.SetColour(myColour);
}
}
But ColorText doesn't show in the inspector(idk how yall call it in unity
)
Change TextMeshPro to TMP_Text?
use TMP_Text not TextMestPro
Do you have any compile errors and does this class name match the file name?
not at all sure where this syntax comes from
ColorText.text = string(Vector3(Red,Blue,Green));
yeah definitely looks like some compile errors
Uh ? but i saw TextMeshPro in a script
then it was wrong
TextMeshPro is the 3D text component. But - you're not seeing it in the inspector because you have compile errors
TMP_Text is definitely better to use btw
Ye i tried to do it the python way
And you figured that would work?
Sounds logic to me string(Vector3(x,y,z)) returns a string as "x,y,z"
except that's not C# syntax
I mean how do you convert stuff to strings then ?
.ToString()
Instead of 'just trying the python way' try 'just reading the C# documentation'
Hello, these errors appear after installing game creator asset how to fix them?
but also you can't construct things without new in C#
You can't just do Vector3(x, y, z)
you have to do new Vector3(x, y, z) or just new(x, y, z) if the type can be implied @stable moth
var hehe = (1, 2);

that's a literal 🙂
for this particular example IDK why they want to use Vector3 though
Good to know
it's 'the python way'. i.e. bloody stupid
thx it's working now !
Trust me I know, I use Python in my dayjob unfortunately
I really hope you practice good library hygiene
Bump. Still having this issue, i'm going crazy. It seems like all the obstacles(cubes) are spawning on the inspector's position. If i debug the obstacles spawn position tho are all differents, but still spawning all on the same spot
@wintry quarry is the new syntax for arrays a literal too? The var array = [1, 2, 3]; thing, never really thought about it. Is it just if you make an object without the new? I assume not because of constants or anything.
Idk who am I Bill Gates? 😉
? @summer stump
Answer and do the things suggested in those messages
done that already
Oh, where is the object pooler script? Must have missed it
The object you're spawning wouldn't happen to have a CharacterController component on it, would it?
it was a bug
no it doesn't have a character controller, just a simple 3d cube with a rigidbody and box collider
here it is
so when i made a bullet shooting mechnaic and the spawn point i get weird duplication after shooting another bullet and I would like it to just be 1 click 1 bullet if that makes sense ```using UnityEngine;
public class BulletShooter : MonoBehaviour
{
public GameObject bulletPrefab; // Reference to the bullet prefab
public float bulletSpeed = 10f; // Speed of the bullet
public Vector3 spawnPointOffset = new Vector3(1, 0, 1); // Offset from the player position
private void Update()
{
// Check if the left mouse button is clicked
if (Input.GetMouseButtonDown(0))
{
ShootBullet();
}
}
private void ShootBullet()
{
// Calculate the bullet spawn position based on the player's position and rotation
// Adjust the spawnPointOffset to move the spawn position to the right of the player and slightly forward (like holding a gun)
Vector3 spawnPosition = transform.position + transform.right * spawnPointOffset.x + transform.forward * spawnPointOffset.z + transform.up * spawnPointOffset.y;
// The rotation should match the player's rotation
Quaternion spawnRotation = transform.rotation;
// Instantiate a new bullet instance at the calculated spawn position and rotation
// Instantiate a new bullet instance at the calculated spawn position and rotation
GameObject bulletInstance = Instantiate(bulletPrefab, spawnPosition, spawnRotation);
// Add this line at the end of ShootBullet() method
Destroy(bulletInstance, 5f); // Destroys bullet after 5 seconds
// Get the bullet's rigidbody component
Rigidbody bulletRb = bulletInstance.GetComponent<Rigidbody>();
// Log the instance ID of the bullet
Debug.Log("Bullet Instance ID: " + bulletInstance.GetInstanceID());
// Add force to the bullet in the direction of the spawn position's forward vector
bulletRb.AddForce(transform.forward * bulletSpeed, ForceMode.Impulse);
// Log the instance ID of the rigidbody to which the force was applied
Debug.Log("Rigidbody Instance ID: " + bulletRb.GetInstanceID());
}
}
using UnityEngine;
public class Bullet : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
// Destroy only the bullet instance, not the prefab
Destroy(gameObject);
}
}``` I cant figure it out im gonna pull my hair out lol
How can i fix Vector3 showing things with 2 extra zeros ?
Hm... try setting the position/rotation before activating it? It's possible the rigidbody is conflicting, but it's not as temperamental as CharacterController
Hmm, ok, that took me a bit because the comments make it really hard to read. But it does look fine. You may want to set the RIGIDBODYs position instead of transform.position
Also, doubt this is even relevant, but in your random ranges, you don't need a + to make that value positive
ye ik, it was just to differentiate
can you explain how should i do it in the code?
Change bulletPrefab to a [SerializeField] private GameObject isntead of public. This will prevent external code from modifying what object that prefab points to.
Instead of putting the position setting after activating it, put it before that instead
awesome let me try 🙂
Anyone ?
you mean before the "for loop"? because then i'm only gonna get one position.
Unanswerable as asked
Show code
Looks like three vector3s to me
i need different positions for each one of the cubes
I mean literally right before you set active
Just take the lines that are after the set active
and put them before it instead
Reply to me don't put ur message to the void lol
I did reply to you...
What?
ohh i was looking the wrong script @polar acorn sry
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.VR;
using TMPro;
public class ColorScript : MonoBehaviour
{
public TextMeshPro ColorText;
public float Red;
public float Blue;
public float Green;
float TrueRed;
float TrueBlue;
float TrueGreen;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
ColorText.text = new Vector3(Red,Blue,Green).ToString();
TrueRed = Red / 10;
TrueBlue = Blue / 10;
TrueGreen = Green / 10;
Color myColour = new Color(TrueRed, TrueBlue, TrueGreen);
PhotonVRManager.SetColour(myColour);
}
}
You would do .ToString("F0");
thank you
@polar acorn sheee, it's working bro, tysm, that object pooler always worked with other types of game (2d) and it never game me problems
I'm guessing that upon activation, the Rigidbody hasn't "woken up" yet, and therefore isn't responding to any attempts to move it. Setting before activating means the rigidbody sees it's "origin" as the given position instead of what it used to be at
seems to stil be duplicating or making a copy after i shot again
That was just a quick sanity check, to make sure there aren't any other scripts modifying this prefab. Can you share the !code on a bin site (can't ctrl+f in discord)
📃 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.
ye i get it ty mate
!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.
📃 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.
!code ```using UnityEngine;
public class BulletShooter : MonoBehaviour
{
[SerializeField] private GameObject bulletPrefab; // Reference to the bullet prefab, set in the editor
public float bulletSpeed = 10f; // Speed of the bullet
public Vector3 spawnPointOffset = new Vector3(1, 0, 1); // Offset from the player position
private void Update()
{
// Check if the left mouse button is clicked
if (Input.GetMouseButtonDown(0))
{
ShootBullet();
}
}
private void ShootBullet()
{
// Calculate the bullet spawn position based on the player's position and rotation
Vector3 spawnPosition = transform.position + transform.right * spawnPointOffset.x + transform.forward * spawnPointOffset.z + transform.up * spawnPointOffset.y;
// The rotation should match the player's rotation
Quaternion spawnRotation = transform.rotation;
// Instantiate a new bullet instance at the calculated spawn position and rotation
GameObject bulletInstance = Instantiate(bulletPrefab, spawnPosition, spawnRotation);
// Get the bullet's rigidbody component and add force
Rigidbody bulletRb = bulletInstance.GetComponent<Rigidbody>();
bulletRb.AddForce(transform.forward * bulletSpeed, ForceMode.Impulse);
}
}
📃 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.
{
public void LoadLevel(Loader.Scene scene)
{
Loader.Load(scene);
}
}
``` ```public static class Loader
{
public enum Scene{
MainMenuScene,
Level01,
Level02,
Level03,
Level04,
Level05,
Level06,
Level07,
LoadingScene
}
public static Scene targetScene;
public static void Load(Scene targetScene)
{
Loader.targetScene = targetScene;
SceneManager.LoadScene(Scene.LoadingScene.ToString());
}```
LoadLevel does not appear in On Click, why?
Because it takes an unsupported parameter type
so, enums are not supported you mean?
I recommend this way:
public class LevelSelectionUI : MonoBehaviour
{
public Loader.Scene sceneToLoad; // assign this in the inspector
public void LoadLevel()
{
Loader.Load(sceneToLoad);
}
}```
Yes enums are not supported in UnityEvent UI
Hm, can you show the inspector for BulletShooter
wanna make it appear on the button tho
No, the inspector for the actual instance
Sorry what do you mean aha?
this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PlayerUI : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI promptText;
// Start is called before the first frame update
void Start()
{
}
public void UpdateText(string promptMessage)
{
promptText.text = promptMessage;
}
}
``` I dont know why this throws me a null reference exception. I am calling this update text to update the prompt message on raycast interaction. When I look at my door to see the text on my screen. I get null reference exception.
promptText.text = promptMessage; this line is whats causing the problem
The inspector for the instance of BulletShooter in the scene
PromptText is null
I wrote some stuff on the inspector though since its serialized no?
im sorry still kinda new this?
Okay, yes, that. While playing, does that BulletPrefab field change?
The error indicates you have at least one instance of PlayerUI which does not have promptText set
oh my god you're right.
Thanks digiholic
doesnt seem like it
It will appear if you write it the way I wrote
Okay, and as you keep firing bullets and you start to get (clone)(clone) it doesn't change?
It appears on the parent object with script attached to it only
so it seems to be doing better but what i dont like is see how that bullet gets duplicated in transit?
I don't think it's getting duplicated, I think its position is updating the frame before it's destroyed somewhere
so like further down the road I wont see issues with like it hitting a monster and doing double damage?
guess ill find out huh? hahahah
Hmm. https://hatebin.com/ There is something wrong with raycast here. I have another script that handles prompt messages. in OnFocus and OnLoseFocus. When I move my mouse to and away from the interactable object. The raycast seem to be working. But when I move sideways for example while looking at the interactable object. The prompt message does not go away. It is as if im still looking at the interactable object. What may be causing it?
This here is what I am talking about if its any help
No script attached, no video attached. Looks good to me
I move to left while looking at the door. Text does not go away for some reason.
ah my bad my bad
oh it does not work wait
!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 log the OnLoseFocus. It does not work until I shake my camera around a bit.
I can give the Interactable script as well but it just inherits from an abstract Interactable class. and has OnFocus, OnLoseFocus and OnInteract thats all.
Well okay I fixed it. Thanks.
I'm assuming line 198 is where it's supposed to lose focus when you move out of the way?
But if some object is blocking the raycast before the door it will not go in else block
Nvm then, what was the solution btw?
I was not checking the interactable layer
I just added a && hit.collider.gameObject.layer == 7 in the first if statement on HandleInteractionCheck
It works perfecto now
Ah yes this would only work if you had one copy of the script per button
that's what I expected you to have
Hey, guys! I want to make a Game Mechanic for my game which is a flappy bird. So, I want to increase the speed gradually in order to make it difficult for the player. Can someone help me implementing that?
I don't know where to start and how to start basically
Never done that before
speed += Time.deltaTime * speedIncreaseFactor
The factor should probably be something low like .01
Plug that in update
hmm let me try.
Unless you want to increase it at checkpoints, which would be a bit different
Alright! I actually made that Game Mechanic but now the problem is that I can't actually synchronize the speed of each game objects I am spawning. I am spawning my game objects so my pipes actually with spawn rate using Enumerator. I got confused on that something happening and I can't sync their speeds. It only happening for my pipes which I have 3 different pipes as prefabs, I am also giving speed to my background and ground layers so they are fine.
I see my objects instances to spawn on different positions
When I am using enumerator and I have a fixed speed rate then it is fine
i cant move mi script in this folder why ?
Can you please take a screenshot and give us more information?
Which folder?
he has two folders higlighted.. and the circle and slash hovering over the Scripts folder.. im assuming thats the folder he means
is this inside of a MonoBehaviour in a non-static method?
Well I this is inside a script which inherited from another class which didn't inherit from Mono
Anyone that can help with that?
that will be why
well that's why. StartCoroutine is an instance method on the MonoBehaviour class. if you do not inherit from MonoBehaviour then you do not inherit that method
so either inherit from MonoBehaviour if this should be a component, or call StartCoroutine on some MonoBehaviour reference
myMonobehaviorReference.StartCoroutine(whatever
what does it inherit from?
you need to inherit from MonoBehaviour in any case
if it does not need to be attached to a gameobject as a component then it is not necessary to inherit from monobehaviour
Lots of methods that "feel" like magic globals are actually just UnityEngine.Object or UnityEngine.MonoBehaviour methods
Okay, What the acual f***
not really code related but check logs
#💻┃unity-talk and check the logs
scipt folder where my cursor is on
thats a very old version. I would change it before downloading if I were you
no, that's the latest 2021 LTS
it's a major version number behind the current LTS, yes, but it's still actively maintained
it's also the only version that has access to those microgame templates
LTS versions are given, well, long-term support
You cant drag script in the scripts folder? is that what ur saying
Putting the year in the version number definitely makes older LTS's seem "outdated"
but fen that version was released three weeks ago. that's practically a million years ago in software terms
i need my unity experience to be disrupted and innovated
[project explode]
unity 2023 ! thats OLD af we're in 2024 wtf
rookie numbers, unity 6000 is out now
hi, just a quick question about the use of readonly. What's the point of this property, is it used just for variable we don't want to modify in inspector ? thx
unity 6k sounds futuristic
no its nothing to do with Unity at all
the readonly modifier prevents a variable from being assigned to outside of the object's constructor or field initializer
readonly is runtime version of const which is compile-time
so it's for when you want to keep the same instance of that object and never assign to again it within the containing object's lifetime
oooh ok ! very clear thank you very much
readonly int num;
void SomeMethod()
{
num = 1;
num = 2; // error and won't assign
}
that is incorrect; the only rule is that you cannot assign to it outside of a constructor or field initializer
you cannot assign to it in any other method
in this case, both lines would be errors
The constructor is unique in that it's guaranteed to run at most once at a very specific point in the object's lifecycle
along with field initializers
Nothing else has those guarantees.
so... would const work?
so i use readonly only if i'm sure to use my variable just once ?
no, you use readonly if you want to prevent assigning to the variable outside of the field initializer or constructor
readonly if it's, well, read-only
If you never intend to change it
just read the value
const is assigned only in the Initializer (its only compile time)
not even constructor
you can use that variable as much as you want, you just cannot assign to it outside of those two places
readonly doesnt work that well with monos beyond anything you can initialize in the member scope space
there is some interfaces that can help with dynamic instantiations though
i pretty commonly use readonly for lists or other collections that i don't need to assign in the inspector but don't want new instances created for, pretty handy for things like buffers used for non allocating physics queries
I use it because the linter tells me to
usually VS tells me , only usually happens on newer .NET apps I work on , never gotten it in unity 
until you do and then it yells at you to remove it
we love intellisense
Can I put multiple layers on one object? I want something to have a layer that marks at as an obstacle that blocks raycasts, but also something that gets picked up by a sphere overlap, but I’ve only been able to put one layer on an object
you cannot put multiple layers on one object but you can put different layers on children
that's not a bad idea otherwise make an interface of tags
K, so would you just put empty game objects on the child of some mesh and put layers on those?
yes, exactly
Alrighty, sounds like that would do the trick
Although why can’t you put multiple layers on when tags work just fine?
Ask Unity
Unity tags stink
I’ve not used them in a while
even if you search by tag you still need to do a component search to grab the exact object (also you can only have 1 tag??)
use Interfaces
In what way
If Unity used a LayerMask at GameObject level instead of Layer then multiple layers could be a thing and it would make RayCasting a lot simpler
Cause this is just to physically block a raycast but also allow another raycast through
I usually combine Layers and then specific objects further, through components
tbh as Layer is just an int there is nothing to stop you making it a LayerMask and using it as such
I’ll try out the child objects idea and see what happens
yeah
guys how do I fix this, as you can see my character barely falls down when I try to move in air.
hey guys I have 2 objects, one object shoots an arrow toward the other.
How to I make the arrow faces toward the target ?
Do I take the Vector3 of the target and minus it to the object that's shooting ?
Like Vector3(target.x,target.x,target.x) - Vector3(shooter.x,shooter.x,shooter.x) ?
thatPosition - thisPosition = direction
And then Instantiate(Bla Bla Bla, Quaternion.Euler(result));
If anyone's new you can dm me and we can learn together
Hi all, say I have a bunch of objects that use the same material, is it possible with code to change the colour on an object by object basis as opposed to changing the material across all objects?
nm, was being dense. lol.
I was just discussing this in #archived-code-general :p
oopsy. lol. Sokay, I got it, I was being stoopid. lol.
Target position - The one who shoots position ?
Hey all! I'm still very new to Unity and I have two main questions if someone could please help me out!
1: How can I get my player to move in the direction my camera is facing?
2: How can I stop this horrible camera jitter when moving my camera?
Player Movement Script : https://gdl.space/ihidomiruh.cpp
Camera Control Script : https://gdl.space/vaxisiwixi.cpp
Camera Movement Script: https://gdl.space/usuyelibed.cpp
Clip :
There's like a handful of ways to move in unity
Remove deltaTime from the Camera Control script
but at minimum you want some forward direction for either your camera or player, and then change units by a speed in that direction
Put that code in CameraMovement to LateUpdate
despite the quality of the video everything that moves does so smoothly but the bees look very blurred when they move. even when the camera moves the background stays clear unlike the bee, what can i do?
How is the bee moving?
What's different from what you're doing with the trees vs bees
using UnityEngine;
public class EnemyAutoMove : MonoBehaviour
{
private Rigidbody rb;
public int enemySpeed = 14;
private float amplitude;
private float frequency;
void Start()
{
rb = GetComponent<Rigidbody>();
frequency = Random.Range(1f, 12f);
amplitude = Random.Range(1f, 2f);
}
void FixedUpdate()
{
float x = amplitude * Mathf.Sin(frequency * Time.time);
float y = amplitude * Mathf.Cos(frequency * Time.time);
Vector2 waveMotion = new Vector2(x, y);
// Use SmoothDamp for velocity smoothing
Vector3 targetVelocity = new Vector3(-enemySpeed, waveMotion.x + waveMotion.y, 0);
Vector3 smoothDampVelocity = Vector3.zero; // Create a separate variable for SmoothDamp
rb.velocity = Vector3.SmoothDamp(rb.velocity, targetVelocity, ref smoothDampVelocity, 0.1f);
}
}
```#
Did you turn on interpolation for the bees Rigidbody? @gray crest
its on none rn
Well then that's your issue
You're seeing non interpolated physics motion
Which is at 50hz by default, not matching your framerate
okay so I change it and they are still burry and now do this weird thing where they slow down
i have changed it to interpolate and it seems to slow down when it goes into the players hitbox collider
Interpolation shouldn't actually change anything, it's purely visual
I presume that's a result of your code
as you can see they are still blurry, also in the future i plan to speed them up to make the game harder so they will be even harder to se
I think your Smoothdamp call is a little sus
For the moment I would simplify the movement code to a constant velocity to sort these issues out
Then start introducing the weird smoothdamp and sin wave stuff
okay let me try
so ive done this, ```using System.Collections;
using UnityEngine;
public class EnemyAutoMove : MonoBehaviour
{
private Rigidbody rb;
public int enemySpeed = 14;
private float amplitude;
private float frequency;
void Start()
{
rb = GetComponent<Rigidbody>();
frequency = Random.Range(1f, 12f);
amplitude = Random.Range(1f, 2f);
}
void FixedUpdate()
{
float x = amplitude * Mathf.Sin(frequency * Time.time);
float y = amplitude * Mathf.Cos(frequency * Time.time);
Vector2 waveMotion = new Vector2(x, y);
// Calculate the target velocity
Vector3 targetVelocity = new Vector3(-enemySpeed, 0, 0);
// Assign the target velocity directly to the rigidbody
rb.velocity = targetVelocity;
}
}
My colliders ain't colliding with each other.
I have a Circle collider on my mouse and a circle collider on my sprite. They are both on the same Z. But My OnTriggerEnter2D isn't triggering but I can see the circle collider on top of the other collider.
I'm working with Collider2d's
Depends on how you move your objects with the collider attached. if you just move them by transform.position, it will ignore physics. and besides that, are you sure, you did set the correct collider to trigger?
" it will ignore physics" ? Wdym by this? I'm moving the game object that has a collider attached to it. Is this wrong?
How are you moving it
Transform.position with the game object that has the collider
ye, transform.position is like teleporting the position. Not moving with physics check happening.
Yeah that's teleportation. It's not going to use physics
You'll need to move it via rigidbody to actually have proper collision checking
At least one of them must have a rigidbody
My script is this:
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("collision happened!");
//if (other.CompareTag("Anvil"))
//{
// Debug.Log("Anvil!");
//}
}
The Three Commandments of OnTriggerEnter2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 2D Rigidbody on at least one of them
hmm okay thank you
the blur is honestly probably from ghosting on your monitor
unless you have postprocessing motion blur enabled
It's a little strange to have a rigid body on something that doesn't need to use physics,But it worked!
But it does need to use physics. Collisions are physics. Triggers are physics. Knowing when two objects are in contact are physics
can someone text me in dm to help me with 2d movement
OK how to fix this then? my character falls very slowly if I move left or right while in air, I want it to fall normal.
I'm guessing you're setting the entire velocity every time you move. You want to keep the Y velocity the same
^ this, ur setting velocity to Vector2.right * speed;
public void kretnja()
{
if (Input.GetKey(KeyCode.RightArrow) == true)
{
igrac.velocity = Vector2.right * speed;
}
if (Input.GetKey(KeyCode.LeftArrow) == true)
{
igrac.velocity = Vector2.left * speed;
}
if (Input.GetKeyDown(KeyCode.UpArrow) == true && Grounded)
{
igrac.velocity = Vector2.up * JumpStrength;
that means ur setting ur Y velocity to 0 each frame.. stopping it from falling
how can I change it then?
in ur vector use the rigidbody's y velocity as the Y value
Instead of setting the whole velocity, set the X velocity to your input and Y velocity to whatever it already was
new vector2 is my custom vector2 right?
yes yes I get it
guys i have 2 objects one has a player layer and another one that has the projectile layer as as you can here i disabled their collision with each other but they can still collide with each other
thanks, it works like I want now. can you explain what (speed, igrac.velocity.y) means is igrac.velocity.y the direction of moving, and speed the multiplier, it kinda doesnt make sense, I think it should be (speed * igrac.velocity.y) can you elaborate @rocky canyon @polar acorn
A vector2 has two things in it
There are two collision matrixes 2d, and 3d
Make sure you used the right one
oh.... thanks that was silly from me
how do i specifically set the x value of a transform function
Transform isn't a function
Transform doesn't have an X value either
so speed(x) is telling y how much to move in y direction?
why would the X component of the velocity be telling you how much to move in the Y direction
but how does the script then know how much to move in y direction
hold up lemme make this clearer
Transform has a position. Position is a vector3. Vector3 has an x component
say I want it to move less, how to do it?
Because your vector also has a Y component
so i want to set the position of a transform, but only change the x value
So set the position to a new vector, putting in whatever X you want, but keeping the Y and Z the same
ok figured this out
only thing is
is there a version of quaternion.identity for vectors?
Now pass in the Y and Z
Vector3.zero
hi i have an animation for my 2d object that is supposed to only be played when i tell it too, instead it plays as soon as the game starts and i dont know how to make it not
Hey I am trying to make a simple 2D game but I have never developed a 2d game only 3d also it has been a while since I have used Unity anyway what would be the best way to have a sprite move up and down with gravity ex press button sprite goes up release it goes down
Is it the entry state of your animator controller
yeah it goes from entry to the animation, i understand that would start on start but idk how to make it so it only starts when i want it to
do i have to make a seperate animation that does nothing
Correct. The entry state is entered the moment the animator starts working.
It's the default state.
thanks
Hi there, I have built a 3D map. I like to make some region and countries on it, which could be selectable and then player could edit it. But I couldn't figure out how it can be possible. I'm new into development.
Anyone?
The same way you would with 3D, use forces on a rigidbody. Nothing changes in that regard.
To add a scene to the build settings use the menu File->Build Settings...
UnityEngine.SceneManagement.SceneManager:LoadScene (string)
Movement:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/Scripts/MC/Movement.cs:103)```
Don't know how to fix it 😦
To add a scene to the build settings use the menu File->Build Settings...
Literally
To add a scene to the build settings use the menu File->Build Settings...
tysm to both of you @polar acorn @rich adder
hi, how should i recreate a ray for another game object so that it doesnt interfere with other rays? should i use a public layermask?
What do you mean "interfere with other rays"?
i have the player ray, and im trying to add a ray to another object "enemie in my game" but it pulls the camera ray of the player and puts it on the new ray from a diferent script
"pulls the camera ray"?
the camera goes to the other object
This does not make any sense.
What is a "ray" here?
It does not sound like a "ray" I'm familiar with.
raycasts don't really interact with each other, and "ray" is a math concept
red is from the player raycast and withe is from the object ray cast, the player camera gets stuck to the new ray location
So don't move the camera when the white ray hits something?
so you're passing that transform somehow
The rays don't do anything, they just check if they hit something
If this white ray is moving the camera, it's because your code that casts the white ray tells the camera to move
this especially doesn't do anything
Okay, so this ray seems to just draw a debug line. It doesn't actually do anything ever
player.transform.position = transform.psotiion ?
they probably put = instead of -
ah, that'll do it
this has nothing to do with the ray, you're just setting three things equal to each other
good eye
that coloring is awful is this iDE even configured
yup my bad, thanks for the help everyone
i dont know, and thanks for the help
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Hi. Are there any good articles for when to use scripts? From an engineering standpoint
What do you mean by "when" to use scripts?
You use scripts when you need to script something
that's pretty vague, yes
From an engineering standpoint, how much functionality should an individual script have, any suggestions on relationship between scripts, stuff like that
the platonic ideal of a component is to do a specific job very well
Are you familiar with SOLID programming?
Yep. Also OOP. Which seems to be a applied differently here, since scripts act as compsoition most of the time
you often create components that form an inheritance tree
and then combine them via composition
that's how my game works
every "thing" in my game that can meaningful act is an Entity. Entities have Modules, which provide specific features:
- being visible
- offering interactions to other entities
- being able to hear things
It may be better to discuss examples.
Like Enemy and Player scripts. They are both "characters". But inheritance doesn't seem to be the obvious route there in most Unity projects
you can still have classes that inherit from others
so you could have an abstract class that is subclassed by Player and Enemy, if there is common behavior between them
I have been leaning towards designs that are very heavily composition-based, hence this setup
This was a rewrite from my original design, where I had some ... very large classes for "Player" and "Enemy"
an Entity has a Brain that controls it and a Locomotion that lets it move around based on the desires of the Brain
I previously had really janky code in the Player class so that it could be an AI or a human-controlled thing
Need help trying to figure out how to play a higher pitch sound for each collectible in my game. Like as you pick them up they get higher pitch. This is my code currently for the collectible
Configure your !ide before asking for help
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
Instead of randomizing the pitch, increase the pitch based on how many coins you've gotten
yeah thats what id like to do
Hello friends. Is there a inbuilt mechanism to handle drag/drop a gameobject in 3d Mobile touch game ?
So, do that. You'll need some way to know how many coins you've collected in this script
As for seperating logic, is it ideal to do it per script? So "health", for example (really general and quite vague example) is a self contained script?
Also thanks this was helpful
My design is almost the same, so at least me and you are on the same page
I don't think so 
I've been slowly drifting towards this design over time
I was working on a "quick" game recently
and boy was I fighting every instinct to generalize everything
it feels so weird to have to manually write code for every item that appears in the settings screen
i'm so used to just giving it a list of settings definitions
Like a game jam or something?
Not a jam, but just something I promised myself I wouldn't spend forever on (:
I do need to participate in more jams again
They're great.
Anyone know of any how-to's on letting players upload an image to set as a background , or even take images to set as backgrounds?
hmm, I'm not sure if there's a texture equivalent to https://docs.unity3d.com/ScriptReference/AudioClip.Create.html
you would need a library that can read image files and give you pixel data, which you'd then store into a Texture2D
or even take images to set as backgrounds?
This would be possible through a camera on the player's device
ah!
https://docs.unity3d.com/ScriptReference/ImageConversion.LoadImage.html this might be relevant
It can undersatnd JPEG and PNG data.
You'd just read the file as a byte array, then use ImageConversion.LoadImage
Ok , I'll dive into these and see what comes up
i dont, but when i play it on mobile and have the same blur issue
How do I make a 2D sprite move up and down(preferably with velocity)
Set the Y velocity to the amount you want it to move up or down by
Can you show a code snippet. also I need a rigid body 2D right?
how can I make a line renderer dotted
give it a dotted material
The line renderer just creates a mesh that follows a path, yeah
hey, i made (followed a youtube tutorial) a car controller script thing. it works until i try making the wheels visuals work.
the part of the script used is
void FixedUpdate{
// the rest of the script that makes stuff work
UpdateWheel(frontLeft, frontLeftTrans);
UpdateWheel(frontRight, frontRightTrans);
UpdateWheel(backLeft, backLeftTrans);
UpdateWheel(backRight, backRightTrans);
}
void UpdateWheel(WheelCollider col, Transform trans) {
Vector3 pos;
Quaternion rot;
col.GetWorldPose(out pos, out rot);
trans.position = pos;
trans.rotation = rot;
}
the car flips horribly when the wheel turning part is added. does anyone know why it does this?
thanks!
How do you set the color of a line renderer via script ?
do i add Set at the begining ?
can set them when ever you want to change the color via code
where can i find that
searched but couldn't find one
also I placed my UI's into an empty gameobject and now they are not appearing
find a dotted image? set it as material , play around with settings. Also not really code question here
line.SetstartColor(PhotonVRManager.Colour);
line.SetendColor(PhotonVRManager.Colour);```
This is the portion of code
because UI elements need to be in a canvas
ohh thanks
there are no such methods on the LineRenderer
was wondering what that was
its just properties line.startColor = wantedColor
but it only hapepns when i add the updatewheel to make the wheels move...
if i made some random dotted line image and set it would that work
how does it spread the sprite across the material
the material across the image i mean
sorry i have no idea how c# synthax works im a python synthax guy
You set the texture to repeat and if you made it tile properly it should be able to Tile on material as well assuming you enabled it
Line renderer itself has different modes of rendering
make sure it set to Tile or the other ones, not stretch though
line.startColor = PhotonVRManager.Colour; line.endColor = PhotonVRManager.Colour;
Now it says that it doesn't know what PhotonVRManager.Colour is
well that part is on you, i used it since that is what your example had
I say there was PhotonVRManager.SetColour in an another script
Wait actually it ssays this
that means you need a object of PhotonVRManager not just its class
which means ?
how do i know an object
i hate the fact ```csharp
void UpdateWheel(WheelCollider col, Transform trans) {
Vector3 pos;
Quaternion rot;
col.GetWorldPose(out pos, out rot);
trans.position = pos;
trans.rotation = rot;
}
Break the problem down. It's either the repositioning, new rotation or both.
im not sure though. the car does this
Assuming the logic you're trying to apply makes any sense at all.
i copied the code from a youtube tutorial and it worked fine for that guy
Maybe you've missed a step
i mean i can always try again a third time
i'll try something rq and i'll be back if it dfoesnt work
nah. works well now. thanks
im unfamiliar with this error, what is it?
you have compile errors in those scripts
is there anywhere I can download a texture
The errors are cut off 🤷♂️
sorry didnt ss right
Assets\Scripts\iswoodplacing.cs(5,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'iswoodplacing'
thats the error
and same for the start function
Assets\Scripts\iswoodplacing.cs(12,10): error CS0111: Type 'iswoodplacing' already defines a member called 'Start' with the same parameter types
Looks like a duplicate script
same with all functions in the script
If your IDE is not underlining these errors in red you need to configure it. !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
hes right
it was
Always gotta be careful when someone posts pictures of compiler errors in the console window
fair
is this how you'd enter an if statement on the condition it is the specific collider, im just guessing
cause rn it's not doing what I want it to
but if i know this is valid i should be able to bug fix
Better question, can a trigger collider trigger another trigger collider
Yes
Does one have a rigid body component?
no
Then no collision will happen
Yes
Collisions are physics
These are physics callback methods
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html
Note: Trigger events are only sent if one of the Colliders also has a Rigidbody2D attached.
how do i split unity render pipline scales into two
what does that mean, and what does it have to do with code
my bad
I want it to move like the upper wave and not this bouncy type movement, which i dont understand how that even happens?
you can probably draw out what the path will be with a line renderer, did you get this from a guide (or ai?) these comments look mighty suspicious.
this formula you are using is basically just the formula for a circle, as time goes on (0 to 2pi) it does waveDensity number of spins around the circle of radius waveIntensity.
I think you can easily get your result by just using the sin or cos and adding that as a perpendicular vector to your direction. the vectors magnitude is the value of sin or cos at that point
used it a bit for a fireball, then i had to myself change the script to fit the magicballs, but yes i was assisted with the basics
so you are suggesting to change the direction vector itself
that does kinda make more sense
i'm working on my first game, it's a 3d world but there's an arcade machine i want the user to be able to play a little 2d mini-game on.
I've basically got it all setup but I don't know if I'm taking the correct approach to it.
In the picture I will provide, the scene to the right there's a cinemachine virtual camera that will be close up to the arcade machine screen.
in the right scene i have another camera that renders a 2dGames layer and the arcade machine has a render texture for the monitor.
this works just fine if i'm just taking in keyboard input to move the spaceship around. but i want aiming to be done with the mouse and i'm struggling to find out how to correctly translate screen points of the mouse position so that the 2d spaceship will rotate and aim at the mouse position.
what should I try to get this to work? is there a way to just get where the mouse position is at on the screen like viewport and just use that as where the mouse would be located for the render camera?
also i'm not sure if it matters but the arcade machine is away far away from the 2d render camera and they are oriented differently. for example, the arcade machine is facing east lets say and the render camera is pointing north
Idk if you know but you can add a scene inside of another scene. Called additive scenes I think. Look that up on google or YouTube
That is indeed what it is called. You just pass LoadSceneMode.Additive as the second parameter of LoadScene
Super easy
so I've got this null reference that I just don't know what to do about: I have a game object that has a 'Representative' class attached (a player character), and I have a 'Specialisation' class (a class that describes a skill) that I have a method in that requires a 'rep' object to calculate the skill's score. Problem is the rep object is null and all the 'getComponent' tricks I know are insufficient to fetch the required data. I'm beginning to think that this is one knot I just can't undo...
i love when someone explains their code setup horribly instead of just pasting it
I would have, but it's a decent chunk of code; and I wasn't sure if anyone was interested...
idk if i can really help you without understanding this properly though...
yeah, it'd take a better understanding of the problem than even I have 😦
also it sounds like you just need to show the func that "calculates the skills score"
if the rep obj is null how will you get data from it?
this is really bad
I have a rep object that isn't null - I need to find a way to get that particular object
I didn't claim it was pretty
GameObject.FindGameObjectWithTag should work for now
its very inefficient tho
yeah, okay - thanks
I'll give it a go; but I think that works on things via thier inspector tag
yeah what else would it work off of?
it's looking for a string input, not what I had in mind
I'm trying to get an object that exists as an attachment to a game object
i am so confused as to what youre talking abt. you need to find a gameobject so use GameObject.FindGameObjectWithTag. then you can access the data attached to that object. whats the problem with this?
additive scenes sounds like a really cool feature but i'm not sure how that's going to help me.
can you switch between the mouse input from each scene or something? like get mousePosition from the camera in the 2d game scene.
because what i'm trying to do is use the virtual cameras mouse position to mirror on the 2d games camera screen
Additive scenes means whatever is in the other scene gets added to your current scene, but under the parent hierarchy of that scene. When a player reaches the arcade machine it could prompt if they want to enter, if yes, it could add the new scene then disable the current camera, or of course not and just use one camera from the main scene, again the additive scene is just adding more objects to your scene
hmm for the mouse position im not sure. possibly youtube making something follow the cursor, and keep the object(fake mouse) that follows the cursor in bounds of the machine screen
could stack ur rendertexture camera and (everything it see's on top of ur main camera) and just cull out the machine and everything you're looking at.. taht way ur mouse positions would be the same for both camera's
it is inheriting monobehaviour
what's the error in the console?
ok so the issue is that your class name is different from the file name
PLayerMovemeny is spelt different from PlayerMovemeny
fix the spelling of both the file and the class name
ah let me try
also note that this is not an issue in unity 2022.2+
Hello i am a begginer and i have a problem with my PlayerController i did all tutorials but every has a error
see #854851968446365696 for what to include when asking for help
i got it, im just stupid ,thanks for the response
Hi, I have ran into a problem, the problem being that I want to Instantiate a prefab exactly where I hit my raycast but, since I am usin hit.point (its not a Transform) the Instantiate wants a Transform how should I approach this problem?
use a different overload of Instantiate https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
ok cool, THX 👍
oh and i strongly recommend looking into object pooling for damage numbers rather than instantiating an object every single time something takes damage
Lovely people on the Unity Discord code-beginner chat. I need help.
As you can see in the video, an enemy throws a bomb towards the player and the bomb explodes after a few seconds. I'm trying to instantiate an object at the location of the bomb explosion when it explodes, but I can't figure out how to do it. What I'm struggling to figure out, is how to get the position of the explosion. If anyone has any ideas, I'd really apprecaite it
transform.position?
yeah the position of the explosion would be the position of that thrown object at the time the explosion happens. i'm honestly confused as to how that isn't obvious
Tried that, but it instantiates it at the source of the particles
The thrown object is a particle
So If I do the transform.position of the particle system, it uses the position of the particle system, not the particle itself
My bad, forgot to mention it's particles
looks like it's working in the video no?
How do I make the pieces fall down if it is paused?
private void EnginParticle(bool engineStarted)
{
for (int i = 0; i < engineParticles.Length; i++)
{
if (engineStarted)
{
engineParticles[i].Play();
}
else
{
engineParticles[i].Pause();
}
}
}
```\
do you notice that once you fly up again the previous particle disappear
dont pause them
actually I see the problem. I don't use the shuriken system much, but you probably want to stop emitting, but not pausing the system
otherwise pool independent systems
Does the number of components affects performance? For example, I have 2 methods I want execute in Update but since they deal different matters, I prefer to have 2 different components. Will it run slower than having 1 component Update doing both methods in the same loop? Obviously for a difference of 1, it won't matter but if we stretch that to having 10 small components instead of 1 big component and then having 10 of this gameobject in the scene?
Yes everything affects performance. It's always a tradeoff.
eh, worrying about micro optimizations, but ideally you want to keep your game objects less populated with components (specifically the ones with colliders) so GetComponent can grab what it's looking for quicker.
More of an issue when these checks are happening per update.
Ok Thanks
When I say "affects performance" that doesn't mean "significantly"
In the same way dropping a bucket of water in the ocean "affects" the sea level.
Ahah, got it. Thanks 🙂
Technically at the scale of lets say 10,000 it is better to do 10,000 methods cals inside a single Update, than having 10,000 individual updates.
use Debug.DrawRay to draw out your ray so you can see where it's actually firing
They are... They just haven't posted any of it
oops
for sure but it doesn't appear
Do you have gizmos enabled?
gizmos?
Hey, I’m spawning multiple defenders with the same tag “defender”. How can I make it so they ignore collision?
Like I don’t want collision to happen between them
you should explain what the collision has to do with their tag
Yeah but I mean can you send a documentation?
i've enabled gizmo but it dosen't work
Because i tried ignorelayercollision it didnt work
Use the layer collision matrix
The defenders have the same layer how can I use the collision matrix
Shouldn’t they be 2 different layers in order to make it eork?
Ok I’ll try
Thanks ❤️
Check whether the code is running at all. If it's not, you probably have a compiler error and your code never compiled
Using the debugger or a log
thks i check and i fix the code now it work thks!
How can i solve this problem?
https://newclarityex.itch.io/kitty-sledding-xtreme
Hello! I need some help with undestanding how to make a plane sprite to actually "fly" and slowly go down, like in this game example: (after you make some upgrades you are able to slowly fly around the map)
Thank you for helping!
Few ways, one is being give every Health class a reference to your MainGame object which you probably have one of
The more typical ways people use these game manager objects is by making them into singletons which means that they become the only instance of that object type
This way you can just reference the class type (with an extra dot operation) without worrying about passing that reference into all of your objects
is there a reason you can't create a MainGame type variable in Health.cs and assign it like you did for mainOver in MainGame?
I recommend going through this guide and see which one works for you
I suspect Dependency Injection would be suitable for your case
Do you mean this?
Ah, so you do pass the reference in, but as a gameobject.
Either be more specific on the type (make it a type of MainMenu and add it on the inspector) or do a GetComponent call assuming you know the GameObject has a MainMenu component
but this isnt working
Consider doing it all on the inspector though
You may be assigning the wrong object then ^
Stick to calling the GameOver method since it's more relevant to the GameManager than the player
Sorry, I'm a beginner i don't know exactly what you mean.
public MainGame mainOver;
public void TakeDamage(float damage)
{
if(dead)
{
mainOver.GameOver();
}
}```
line.startColor = PhotonVRManager.Colour;
line.endColor = PhotonVRManager.Colour;
```I have this error in this part of my script
Which means ?(sorry im a beginner in Unity)
This is my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Photon.VR;
public class Line : MonoBehaviour
{
public LineRenderer line;
public Transform pos1;
public Transform pos2;
// Start is called before the first frame update
void Start()
{
line.positionCount = 2;
}
// Update is called once per frame
void Update()
{ line.startColor = PhotonVRManager.Colour;
line.endColor = PhotonVRManager.Colour;
line.SetPosition(0, pos1.position);
line.SetPosition(1, pos2.position);
}
}
i made an if statement for when the parameter of ontrigger is a certain collider, is it valid
Is PhotonVRManager being referenced anywhere? If it's a singleton then you need to specificy the instance extension
nvm i know whats wrong
PhotonVRManager works well in this script so idk why it's not working in mine
how do i get this function to appear in the onclick dropdown? trying to make it so when i click a button, a seperate image canvas ui object changes its position
@timber tide
Ah, maybe you need to new the color instance because it's just a property field here, but usually that's another error if I'm mistaken.
Kill unity from the task manager
👍
so if i didnt save it will have to go?
What will have to go ?
it has error
anyone know?
and i have GameOver event in this code
Show the type of mainover in the class scope
you still have it as GameObject
Unsaved progress on what? The scene ? The game? The code? This is why I am asking the question.
MainMenu is a component of GameObject, but if you assign it as GameObject you need to use GetComponent to grab it from it. Otherwise, change the type to MainMenu specifically and assign it as is in the inspector
Maybe let him respond instead of “thinking” on his behalf?
Like this?
Hey guys, I downloaded a project from github, when I tried to open it it needed a a specicefic unity version so I downloaded it , but when I open the project it has errors, but they all the same.
and when I open Rider, they don't have any context for any unity calss like System,UnityEngine...etc?
You can't name the types used in an action
Sorry I'm lost
Oh
Wait
protected Action<Character, Character> onHit;
Like this ?
Yes
Generic type parameters never have names, yes
List<int coolestIntegersEverInvented> myList;``` is forbidden
You can name them in a delegate tho
public delegate void OnHitDelegate(Character attacker, Character victim);
protected OnHitDelegate onHit;
protected Character attacker;
protected Action<Character, Character> onHit;
//set bullet data for bullet
public virtual void OnInit(Character attacker, Action<Character, Character> onHit/*Truyen vao mot Action*/)
{
this.attacker = attacker;
this.onHit = onHit;
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Enemy"))
{
//Character victim = Cache.GetCharacter(other);
//onHit?.Invoke(attacker, victim);
}
}
Hey guys, idk what's that
Cache.GetCharacter(other);
you could also use an anonymous type, if you really want names
Action<(int myNamedVariabel, int someOthername)> callback;
but imo, it makes both the invocation, and the subscriber signature a little messy. but up to you
the text component in Unity gets overridden to nothing when the function is called; how can I fix this?
the getText function i mean
Why are u even trying to get a new reference?
Why not have it assigned from the start?
is it a good idea to put movement/attack behaviour of an actor into animation state machine behaviour?
I'm a beginner at coding c#. I have never coded before where do you think I should start? I know how to use unity/know the basics.
using UnityEngine;
using UnityEngine.Audio;
public enum AudioOutput
{
Music,
SFX,
Dialogue
}
public class AudioManager : MonoBehaviour
{
public static AudioManager Instance;
[Header("Mixer")]
public AudioMixerGroup musicMixerGroup;
public AudioMixerGroup sfxMixerGroup;
public AudioMixerGroup dialogueMixerGroup;
private void Awake()
{
Instance = this;
}
public void PlaySound(AudioClip clip, AudioOutput output)
{
GameObject newObject = new GameObject("Sound");
newObject.transform.parent = this.transform;
AudioSource audioSource = newObject.AddComponent<AudioSource>();
if(output == AudioOutput.Music)
{
audioSource.outputAudioMixerGroup = musicMixerGroup;
}
else if(output == AudioOutput.SFX)
{
audioSource.outputAudioMixerGroup = sfxMixerGroup;
}
else if(output == AudioOutput.Dialogue)
{
audioSource.outputAudioMixerGroup = dialogueMixerGroup;
}
audioSource.PlayOneShot(clip);
Destroy(newObject, clip.length + 0.25f);
}
}```
why is it causing a clicking noise?
when i destroy the sound object
its like a really quiet click noise
u probably wont be able to hear it on video
well you're playing a sound, no?
yes but im destroying the sound after its finished playing
Destroy(newObject, clip.length + 0.25f);
i even added 0.25f just to be safe
i tried destroying it with a coroutine as well
and setting the volume to 0 just before i destroy it
also didnt work
I'm confused, when is the clicking happening?
when i destory the object
i'll try and record it
like when you call destroy or when it actually gets destroyed?
Well, i created a whole audio system for the "clicking noise" before. If you don't wan't that behaviour, use a third party audio system because you will encounter later on even you fix that one. FMOD Suggested.
yeah i dont even know if u can hear it
when it actually gets destroyed
yeah
Basically, the clicking noise happens when the music stops, a small gap happens between frequencies if the frequency is high enough. This gap causes a "clicking noise". How to fix it? Only way is to delete that high frequency when you stop the audio. In other words, mute or fade out. But yeah FMOD is all good they thought about everything.
maybe just shoot once so it's not masked haha
wait it doesnt happen for the ak
maybe its cause the sound doesnt fade out properly?
yeah the ak works
i'll just try to make a coroutine which fades the volume to 0 before destroying it
guys i have a bit of a unique problem that idk if it has a fix or not
so basically i have this lighting attack that bounces from enemy to enemy using the script below (on top there is "OnCollissionEnter2D")
the thing is since this is "OnCollissionEnter2D" and not "OnCollissionStay2D" if 2 enemies and really close to each other to the point the collision box of the lighting projectile that this script is attached to dosent leave the collider of the the first enemy hit when it hits the second enemy it targets back to the first enemy since its the closet enemy but since the colliders are still touching from the first time he got hit it dosent register it as a collision enter
a logical fix would be to change OnCollissionEnter2D to OnCollissionStay2D but that would make the first enemy get hit 3 times instead of the projectile bouncing 3 times
is there a way to fix this?
😄 Goodluck
another solution i came up with is to the make the projectile colider smaller but that makes the problem rarer but not completely gone and makes it harder to hit the projectile
i just used an online tool to fade out the glock clip
and it works
guess i'll just have to make sure each audio fades out properly
but thats fine
Hey guys, I have 2 game objects, one of them has "Is Trigger" collider, the other doesn't.
I also have a script that has "OnTriggerEnter(Collider other)" and I attach that to the game object what has "Is Trigger" collider.
What will happen ?
hello, so i'm trynna fix my character's diagonal movement and apprently only one condition can be true and so the player can't walk diagonally. if i press the right arrow key, then the up arrow, the right movement is cancelled and the player goes up
both of them can be true but you're overwriting the move vector in the second one
that makes sense
as far as i know if its a trigger it just goes through things (i might be wrong try)
shall i make another condition where left or right and up or down are pressed?
Try something like this @ornate lynx
Vector2 move = Vector2.zero;
if (horizontalStuff) {
move += new Vector2(...);
}
if (verticalStuff) {
move += new Vector2(...);
}
transform.Translate(move...);
see how I'm using +=?
So they can both affect it
yeah yeah
that being said you overcomplicated this entirely
so it's like i'm summing the old vector wh=ith the new one is that right?
you should just do this:
Vector2 move = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
transform.Translate(...);```
much simpler
yeah, i misunderstood the problem
no need for if statements, checking individual keys, etc..
Are you having trouble understanding this one?
will make it more compact at a later point
What part is confusing?
no, well, idk, seems easier for me in if statement
what does the if statement add here? Input.GetAxis already tells us the value of the axis (aka the keys being pressed)
if they're not being pressed, it will be 0
which is as expected
i wrote that line at first, and forgot to transform.translate and i thought using that line was wrong 💀
It's very common to jump to conclusions as a beginner and change all your code
try to resist that urge lol
Hi! Can someone help with questions concering data persistence and input fields? It's something I've found a ton about online, but I'm failing to understand how to apply what I'm reading. What I want to achieve is:
- Type the player name in an Input Field on Scene 0
- Load Scene 1
- Display the text from the Input Field in a TextMeshPro in Scene 1, as part of the scoring text (which alreadys works). It would be: "<player name>'s score: xx"
How would I do this? I'm struggling with:
- Writing code that takes the player input
- Storing/saving that player input somewhere
- Sending that input as text to display to my other scene
Here's 2 screenshots of my current game.
For data that there can be only one copy of, a static field is a reasonable choice.
a static field is part of its class, rather than being part of instances of that class
so, you can access it from anywhere
Thanks for the advice. This is what I've found online too. The thing is, I just don't understand what to do. Where do I start, what code do I use? Appreciate any advice you can give.
figure out how to log the contents of your input box when you click a button
then you just need to store the text into a field instead of logging it
Think I got that part. Can you help me along what's next?
okay, so instead of printing it, you need to store it in a static field
creating a static field is easy: just add the static modifier to a field defintion
public static string playerName;
for example
public static string playerNameInput;
public void ReadStringInput(string playerNameString)
{
playerNameInput = playerNameString;
Debug.Log("Player name: " + playerNameString);
}
Like this? 🙂
i would avoid declaring static variables, man. that is bad juju
i’ll always take a singleton over a static field, even tho a singleton uses a static field to function
that would work, but because it is static, it is 1) harder to debug, 2) persists, 3) hard to track down changes
It’s fine.
You write to it on the menu scene and then read from it elsewhere
You don’t need to create an elaborate contraption to hold the string
i wouldn’t call a singleton an elaborate contraption, if you just inherit from a class someone else wrote
Thanks for your help both. I'm now going to do some experimenting with showing the input field in another TMP on the Menu scene. if that works, I'll try to get it to show on the next Scene.
It’s trivial to find who changes the field.
Once you’ve written something to the static field, you can access it from anywhere else
Static fields live for the entire duration of the game
which is why I have a kneejerk reaction to defining static fields
Even when moving to another scene? 🙂
They live for the entire duration of the game.
Static fields have nothing to do with Unity at all.
of the whole program
maybe you should work on controlling that reflex
i’ve been screwed over by static fields a lot, so it is hard to unlearn
creating a static field to store a reference to a class that holds a single field is functionally equivalent to creating a static field in this situation. there are certainly scenarios where they aren't equivalent, but this isn't one of them
my concern is abuse/overuse associated with starting to use them, and never learning the downsides
Hello, guys! I want to implement a Game Mechanic for my game. So, I am making a flappy bird game and I want to increase speed of my tree logs everytime I am making +10 score. Here is how it looks like right now because I am currently increasing the speed gradually. Can someone help me with that please I stuck on that and don't know how to make it?
just follow the tutorial from game maker’s toolkit
That goes for me?
🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then gi...
he literally makes flappy bird from start to finish
The problem is that I am already at the end of the process
I have only one game mechanic to make and I am fine
Thank you very much, that's helpful to understand. Could you also help me along to display the input into a TextMeshPro object in my game? Here's a screenshot, where you can see where the input should be displayed.
Maybe consider showing your implementation
It works for both UI and non-UI text.
You will need to add using TMPro; up top, since that's the namespace this class comes form.
TMP_Text.text lets you set the text it displays.
public class MovingUpDownLogs : MonoBehaviour
{
[SerializeField] private float currentSpeed;
[SerializeField] private float minY;
[SerializeField] private float maxY;
[SerializeField] private float speedIncreaseFactor;
[SerializeField] private float maxSpeed;
private bool movingUp = true;
private void Update()
{
if (movingUp)
{
transform.Translate(Vector3.up * currentSpeed * Time.deltaTime);
if (transform.position.y >= maxY)
{
movingUp = false;
}
}
else
{
transform.Translate(Vector3.down * currentSpeed * Time.deltaTime);
if (transform.position.y <= minY)
{
movingUp = true;
}
}
IncreasingSpeedOfTreeLogs();
}
public void IncreasingSpeedOfTreeLogs()
{
if (currentSpeed < maxSpeed)
{
currentSpeed += speedIncreaseFactor * Time.deltaTime;
currentSpeed = Mathf.Min(currentSpeed, maxSpeed); // Ensure speed doesn't exceed maxSpeed
}
}
}
Here is my class that moves the tree logs!
OK I will give this a try. I think I had something like you are explaining, but it did nothing for me. No erros eithers. I'll start over and share my results.
So, I am thinking to use my IncreaseSpeedOfTreeLogs() inside my UpdateScore() method
Maybe only call the increase speed function when score has changed
Yeah maybe let me try give me a minute
hi, how can i add a one time force to a rigidbody?
AddForce using ForceMode.Impulse
Wow I think I figured it out!
public static string playerNameInput;
public TextMeshProUGUI playerName;
public void ReadStringInput(string playerNameString)
{
playerNameInput = playerNameString;
Debug.Log("Player name: " + playerNameString);
}
public void Update()
{
playerName.text = playerNameInput;
}
it's gonna happen only once?
Also, you probably don't need to be multiplying current speed by delta time in the accumulation of speed - Update would be relative to this frame thus why it's necessary in Update.
yup, there you go (:
that's the general idea for a lot of tasks
get a reference to the thing you need (usually by dragging it into the inspector) and then do stuff to it
is it gonna happen only once?
Awesome, thanks a lot. I'm now going to try and bring that playerName to my next scene. If I understood you right, the public static should allow me that.
as long as you call it only once
Right.
Non-static members (fields, methods, etc.) are part of a specific object, like public TextMeshProUGUI playerName
You can assign them in the inspector for each instance of the component
Static members are part of the class, like public static string playerNameInput
exactly, i'm calling it every frame
is there a way to call it once in update method?
sure, slap a bool field in that you set to true after the first time you run the method
should i make all my player stats as in attakc damage / health / range.... as public static?
i'm not sure why you're putting this in Update, though
so any script that wants to change them can instantly do
no, because a specific player object has stats
my player is sliding so i'm adding a brief force as counter movement to stop it
what
It would make a lot more sense to just pass the player themselves to the components that need to modify the player
You could make the player a singleton, I suppose.
im still new i don't know what a singeton is
i'm working on a top down view 2D game
stats are a property of the player in the scene (a Player component on a game object), not just the abstract concept of a player (the Player class)
ah, I see -- then a bool called stoppedSliding would be reasonable
alr alr
Set it to true when you apply the force and set it to false when you move again
got it
i try to avoid doing things in Update unless I kind of need to
i'm programming the player's movement sooo
so whenever i wanna change something in the player
Script that changes attack damage:
private PlayerScript player;
Start
player = GetComponent<PlayerScript>();
player.attackDamage += 10;
?
To be honest, I'm lost again. 😅 It's mainly a thing of not understand how to describe what I'm trying to do. I'm still missing some of the vocabulary, is what I'm feeling... Anyway. In my other scene, where I want the player name to show up: how do bring over the static string? I know how to get text to display in my scene. But how do I get the string from Scene 0, to Scene 1?
then the force should be added in response to an invocation of player jump or something
Yes I am going to remove that. Also, you know I am thinking maybe the issue persists because I am instantiating these tree logs game objects. Maybe the calculation of the current speed with increase speed factor works only for the original game object?
update should generally be used to capture input tho
yes?
but actually applying force would be done once per fixed update
when is fixedUpdate called?
Yes, they would be per tree basis where the tree would only increase in speed if it were present when score increased.
@swift crag
by default, 50/s
GetComponent looks for a component on your game object.
soo fixedUpdate is not a solution is it?
regular update could be called 50 to 600 times in a second
The player's component is probably not attached to the enemy
Maybe set the speed once after instantiating the tree based on score
partially
yeah -- with the exception of one-off impulse forces, which make sense in Update
rb.AddForce(whatever, ForceMode.Impulse);
so Input.GetKeyDown is true for exactly one frame, which may or may not be a fixed frame
yes i have this exact line in update
Yes, I have done that I put my IncreaseSpeedOfTreeLogs() inside my updatescore() but nothing thats why I am thinking maybe the calculation is not applied to the instances.
Where you'd cache the instantiated tree and modify its speed value based on your stored score.
@swift crag look
i have a script and i wnat to it change a value in another script
should do that private variable and get that componenet and change it or make the variable i wnat to change a static or what
but you should not do physics things in regular update, since the timing can get wacky, since physics sim isn’t even done that frame!
this is my condition except "up" and it's gonna be true every frame, and if it is, i would add the force every frame
If you went ahead and followed the steps shown in https://unity.huh.how/references/singletons, you'd just do this:
Player.Instance.attackDamage += 100;
so in general, with the default Input system, you want to query player input and store variables in Update. Then actually action on them in FixedUpdate
Alternatively, if you didn't use a singleton, you'd need to provide a reference to whoever needs to modify the player
public void GivePowerup(Player player) {
player.attackDamage += 100;
}
As you've got it (fired when score increases), they'll be default slow unless present when score is increased. Assuming you want new trees to be faster and not just older trees gradually increasing in speed, set the speed when instantiating relative to your score.
This could be called when the player collides with the powerup
In that situation, you would use GetComponent to get the Player component after colliding with the player
ok but the force would still be applied 50 times a second if a certain condition is true
let’s say I were to somehow press jump twice between physics frames, but there are real frames in between. If you invoke jump to add force in update, the physics sim hasn’t resolved anything yet, so you could add double the force by just mashing
void OnTriggerEnter2D(Collider other) {
if (other.TryGetComponent(out Player player) {
player.attackDamage + 100;
}
}
That would be reasonable.
TryGetComponent returns true if it manages to find the component you asked for
that....kinda makes sense?
Good point -- you'd want to avoid that
except the last sentence
that’s why the only physics activity you want to do in update is gather info, and NOT act on it until fixed update
thanks @swift crag
you might have 20 frames between fixed frames
you might have 1
or zero
you don’t know
i'm sorry mb but i still don't get it
so the code needs to handle the distinction
quote exactly the part you dont understand
unity has frames and fixed frames
why i should use fixed update
yeah alr, what's the difference
physics simulation only happens on fixed update
physics like adding force?
AddForce just adds your force to a running total.
the whole putting of bodies in motion, changing velocities, collision callbacks, contacts… NONE of this shit happens on non-fixed frames
The force is acted upon in the next physics update.
I wouldn't call them "fixed frames", since they're not frames at all
it's just an update loop that runs at a fixed cadence -- 50 times per second
so u suggest that i detect the input in Update and actually do that physics stuff in fixedUpdate
that means you get 0, 1, or many fixed updates per rendered frame
bingo
Reading input in Update is important because things like Input.GetKeyDown care about exact frames
GetKeyDown is true for one frame
im a beginner at coding c# i know how to use unitiy/know the basics. whats the fastest/best way to learn c#
If you check for input in FixedUpdate, you might miss that frame entirely
c#?
if you give a grounded player +5 Y velocity in update, then next update check that he is on ground to try a jump, the player will still be on the ground if a physics update/fixed update hasn’t happened yet!
you gave the player velocity, but physics system doesn’t DO anything with it until it is time for physics sim.
which happens on fixed frames, and not on non-fixed frames
do you understand?
Hello, I have a problem that I can't find the answer for online, so I was hoping someone could help here is what im trying to do: I want to make a "Bullet" hit a "Enemy" by using tags but when I shoot the "Enemy" nothing happens not even my Debug output, Here is my line of code, if you need more I could screen shot my whole thing: void OnCollisionEnter()
{
if (GameObject.FindWithTag("Test"))
{
TakeDamage(20);
Debug.Log("HIT");
}
}
your method's parameters are wrong.
this is why you don’t want to do anything physics related in Update. Because that is not the frequency with which physics updates happen
Go through these pages.
Thanks
the frame after i got my finger off the space bar, the player starts jumping
I've tried something, but get an error. The error is:
NullReferenceException: Object reference not set to an instance of an object
Menu.Update () (at Assets/Scripts/Menu.cs:23)
My scripts are:
Menu script in Scene 0: https://gdl.space/duhequcipo.cpp
GameManager script in Scene 1: https://gdl.space/bupuwofasi.cpp
a NRE means you have a null variable you're trying to do something with
therefore, something on line 23 is null
anyway, i hope that clears things up
i'm reading over and over to better understand it
wait
i kinda get it now
so when i press the spacebar, the player doesn't jump at the exact moment i pressed, he actually jumps when a fixed frame happens while i'm pressing the spacebar
Input goes off EVERY frame, fixed or not. So if you ask Input if this is the frame where spacebar was pressed down, it may or may not be on a fixed frame
yes
So you need to capture wtf Input is doing in Update, then actually do physics in FixedUpdate
ok so i need to detect the input from Update(), make some variables to work with to add the force in FixedUpdate()
