r/UnityHelp • • Aug 17 '21

PROGRAMMING Unity Problems with Photon

3 Upvotes

When i try to "play" the game an error message with yellow pops up saying:
"PUN is in development mode (development build). As the 'dev region' is not empty (eu) it overrides the found best region. See PhotonServerSettings.

UnityEngine.Debug:LogWarning (object)"

I know from tutorials that i should get a message saying: "Received your UserID from server. Updating local value to: [Number]"

But i don't get that message...

So beside this error i am unsure if it is best to use Photon Pun or another service, for a multiplayer 12 player game :)

using UnityEngine;

using Photon.Pun;

using Photon.Realtime;

using UnityEngine.UI;

public class NetworkScript : MonoBehaviourPunCallbacks

{

public static NetworkScript lobby;

public Button joinPlay;

public Button cancelSearch;

// Start is called before the first frame update

private void Avake()

{

lobby = this;

}

void Start()

{

//PhotonNetwork.LeaveRoom();

//PhotonNetwork.LeaveLobby();

PhotonNetwork.Disconnect();

PhotonNetwork.ConnectUsingSettings();

}

void OnEnable()

{

//Register Button Events

joinPlay.onClick.AddListener(() => PlayGame());

cancelSearch.onClick.AddListener(() => CancelGame());

}

public void PlayGame()

{

PhotonNetwork.JoinRandomRoom();

}

public override void OnJoinRandomFailed(short returnCode, string message)

{

Debug.Log("Tried to join and failed");

CreateRoom();

}

void CreateRoom()

{

int randomRoomName = Random.Range(0, 10000);

RoomOptions roomOps = new RoomOptions() { IsVisible = true, IsOpen = true, MaxPlayers = 12 };

PhotonNetwork.CreateRoom("Room" + randomRoomName, roomOps);

Debug.Log("Room Created :) ");

}

public override void OnJoinedRoom()

{

Debug.Log("Room had been joined");

}

public override void OnCreateRoomFailed(short returnCode, string message)

{

Debug.Log("Tried to make a room, makes a new one.");

CreateRoom();

}

public override void OnConnectedToMaster()

{

Debug.Log("Player has connected to the Photon master server");

}

void CancelGame()

{

PhotonNetwork.LeaveRoom();

}

public void OnFailedToConnectToPhoton()

{

Debug.Log("doens't connect to server...");

}

}


r/UnityHelp • • Aug 17 '21

Solved New to C#, have literally no clue how to solve this. Please help.

3 Upvotes

r/UnityHelp • • Aug 07 '21

UNITY Check for null on collider?

3 Upvotes

I have an object that shoots bullets, those bullets makes this error when they collide whit a clone of themselve.

NullReferenceException: Object reference not set to an instance of an object

BulletShot.OnTriggerEnter (UnityEngine.Collider collision_Unit) (at Assets/Prefabs/BulletShot.cs:43)

This comes up because the bullet doesn't have a parent. But as far as i understand it shouldn't be a problem since i tjek if there is a parent in line 43 with != null.

So how do i make sure that the if statement triggers the right way?

And yes i am completely new :D

​ <using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class BulletShot : MonoBehaviour {

public float damage;

public float speed;

public float deathTimer;

public string enemyTag;

private Vector2 EnemyPosition;

private Vector2 MyPosition;

public float m_Angle;

public Transform Owner;

public float poisonDamage;

public float poisonTimeInteval;

public float poisonTotalTime;

//public Target health;

private void Start()

{

}

private void Update()

{

transform.Translate(Vector3.forward * speed * Time.deltaTime);

Destroy(gameObject, deathTimer);

}

public void OnTriggerEnter(Collider collision_Unit)

{

if (collision_Unit.tag == "Enemy")

{

collision_Unit.gameObject.GetComponent<HealthScript>().TakeDamage(damage);

Destroy(gameObject);

}

else if (collision_Unit.transform.parent.gameObject != null && collision_Unit.transform.parent.gameObject == Owner.gameObject)

{

//if (collision_Unit.transform.parent.gameObject == Owner.gameObject)

//{

Debug.Log("Hallo");

//}

}

else if (collision_Unit.tag != "Spell")

{

Destroy(gameObject);

Debug.Log("non spell random obejct");

}

}

}>


r/UnityHelp • • Aug 03 '21

Question: How Do You Disable Specific Collisions

3 Upvotes

I am attempting to create a sort of dodge ability for the player in my 2D platformer. But, I do not know how you are supposed to disable/enable certain collisions. Is it possible to put colliders on layers so that they only collide with other colliders on that layer, or something to that effect? Or do you have to manually enable and disable specific collisions?


r/UnityHelp • • Aug 01 '21

Moderator Post Updating the look of Unity Help over the next little bit.

3 Upvotes

Hello, I am /u/Bonejob and I am a new moderator here are Unity Help. I will be working on cleaning up the look and feel of the sub over the next while. This will include;

  • Fix the old.reddit.com/r/unityhelp style, modernize it and get the colours of the new style and old to align. Used Legere as the base will be modifying some more as we go. https://old.reddit.com/r/legere/

  • Creating a header.

  • Modifying /r/unityhelp colours Switched to same colours as new unity interface for consistency.

  • Creating a graphic for the logo for mobile, Reddit new and old. - Created a logo out of the Unity logo and Reddit logo. Not great but I am a programmer after all :)

  • Updating RES tools code, to integrate into RES echo system. - Added RES embed

  • Creating a wiki. - Created, nothing to write yet, but it's been created :)

  • Creating a sidebar.

  • Adding code formatting to make posted code easier to work with. Still don't think I can do colour code, but I have no tried for a few years... Code formatting fixed, still, not colour coded for they still won't let us embed Javascript. Tried with CSS only but failed miserably.

  • Updating flairs, colours, and topics. Updated personal flairs and added a Moderator Message flair.

More to come.

I have moderated for Reddit for 7 years. I have been a professional developer for 30 years, 15 of which have been in .NET. I started when .NET was called NGWS, and it became my main programming language in 2005 with the release of .NET 2.0.

I will be cross-posting a lot of topics from unity_tutorials, unity 3d, and unity 2d for a lot of people ask questions on those subs.

I will of course be helping with answering posts, drop a mod message if you have any questions about what is going on.


r/UnityHelp • • Jul 20 '21

PROGRAMMING hi this my code an it gives me an error called idenefier expected on line 55 pls any help will be really appreciated thanks

3 Upvotes

using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveMent : MonoBehaviour {
[SerializeField]public Transform groundcheckTransform = null;
[SerializeField]private LayerMask playerMask;
private bool jumpkeywaspressed;
private float horizontalInput;
private Rigidbody RB;
public int SuperJumpsRemaining;

// Start is called before the first frame update
void Start()
    {
RB = GetComponent<Rigidbody>();
    }
// Update is called once per frame
void Update()
    {   //jump
if(Input.GetKeyDown(KeyCode.Space))
        {
jumpkeywaspressed = true;
        }
horizontalInput = Input.GetAxis("Horizontal");
//debug check
if(Input.GetKeyDown(KeyCode.Space))
        {
Debug.Log("Hello");
        }  
    }
void FixedUpdate()
    {
//infinite air jump bug fixe
if(Physics.OverlapSphere(groundcheckTransform.position, 0.1f,playerMask).Length == 0)
        {
return;
        }
if(jumpkeywaspressed)
        {
float JumpPower = 5f;
if(SuperJumpsRemaining > 0)
            {
JumpPower *=2;
SuperJumpsRemaining--;
            }
ridboy.AddForce(Vector3.up*5, ForceMode.VelocityChange);
jumpkeywaspressed = false;

        }
RB. = new Vector3(horizontalInput,RB.velocity.y,0); // the error line
    }
void OnTriggerEnter(Collider other)
    {
if(other.gameObject.layer == 9)
        {
Destroy(other.gameObject);
SuperJumpsRemaining++;
        }
    }
}


r/UnityHelp • • Jun 20 '21

XR Recenter Not working in Oculus Quest 2

3 Upvotes

Hi,
I'm trying to make it so that when the user presses the "A" button on the oculus quest 2 controller.
It triggers this function and resets the camera.

In the attached image, the commented out code is the new and recommended way of doing it and the Uncommented one is the old/obsolete one.

Both methods work like a perfectly when I'm testing in the Unity editor with the Oculus Headset hooked up via Oculus Live link. When I build and run it on the headset, it doesn't work.

I'm not sure why this is happening. Can anyone help me please?

thanks


r/UnityHelp • • Jun 20 '21

Trying to change ResetState() to also Reset Score When hit wall or self heres my code

3 Upvotes

using System.Collections.Generic;

using UnityEngine;

/// <summary>

/// Handles the movement of the snake and growing in size.

/// </summary>

[RequireComponent(typeof(BoxCollider2D))]

public class Snake : MonoBehaviour

{

/// <summary>

/// The list of segments of the snake.

/// </summary>

private List<Transform> _segments = new List<Transform>();

/// <summary>

/// The object that is cloned when creating a new segment to grow the snake.

/// </summary>

[Tooltip("The object that is cloned when creating a new segment to grow the snake.")]

public Transform segmentPrefab;

/// <summary>

/// The number of segments the snake has initially.

/// </summary>

[Tooltip("The number of segments the snake has initially.")]

public int initialSize = 4;

/// <summary>

/// The direction the snake is moving.

/// </summary>

[HideInInspector]

public Vector2 direction = Vector2.right;

private void Start()

{

ResetState();

}

private void Update()

{

// If moving horizontal, then only allow turning up or down

if (this.direction.x != 0.0f)

{

// Set the direction based on the input key being pressed

if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) {

this.direction = Vector2.up;

} else if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) {

this.direction = Vector2.down;

}

}

// If moving vertical, then only allow turning left or right

else if (this.direction.y != 0.0f)

{

// Set the direction based on the input key being pressed

if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) {

this.direction = Vector2.right;

} else if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) {

this.direction = Vector2.left;

}

}

}

private void FixedUpdate()

{

// Set each segment's position to be the same as the one it follows. We

// must do this in reverse order so the position is set to the previous

// position, otherwise they will all be stacked on top of each other.

for (int i = _segments.Count - 1; i > 0; i--) {

_segments[i].position = _segments[i - 1].position;

}

// Increase the snake's position by one in the direction they are

// moving. Round the position to ensure it stays aligned to the grid.

this.transform.position = new Vector3(

Mathf.Round(this.transform.position.x) + this.direction.x,

Mathf.Round(this.transform.position.y) + this.direction.y);

}

public void Grow()

{

// Create a new segment

Transform segment = Instantiate(this.segmentPrefab);

// Position the segment at the same spot as the last segment

segment.position = _segments[_segments.Count - 1].position;

// Add the segment to the end of the list

_segments.Add(segment);

}

public void ResetState()

{

// Set the initial direction of the snake, starting at the origin

// (center of the grid)

this.direction = Vector2.right;

this.transform.position = Vector3.zero;

// Start at 1 to skip destroying the head

for (int i = 1; i < _segments.Count; i++) {

Destroy(_segments[i].gameObject);

}

// Clear the list then add the head (this) as the first segment

_segments.Clear();

_segments.Add(this.transform);

// Grow the snake to the initial size -1 since the head was already

// added

for (int i = 0; i < this.initialSize - 1; i++) {

Grow();

}

}

private void OnTriggerEnter2D(Collider2D other)

{

if (other.tag == "Food") {

Grow();

}

// Food eaten, increase the size of the snake

else if (other.tag == "Obstacle")

{

// Game over, reset the state of the snake

ResetState();

}

}

}

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

public class ScoreManager : MonoBehaviour

{

public static ScoreManager instance;

public Text scoreText;

public Text highscoreText;

int score = 0;

int highscore = 0;

private void Awake()

{

instance = this;

}

// Start is called before the first frame update

void Start()

{

highscore = PlayerPrefs.GetInt("highscore", 0);

scoreText.text = score.ToString() + " POINTS";

highscoreText.text = "HIGHSCORE: " + highscore.ToString();

}

public void AddPoint()

{

score += 1;

scoreText.text = score.ToString() + " POINTS";

if (highscore < score)

PlayerPrefs.SetInt("highscore", score);

}

}

using UnityEngine;

/// <summary>

/// Handles setting the position of the food.

/// </summary>

public class Food : MonoBehaviour

{

/// <summary>

/// The area marked by the collider that is considered in bounds.

/// </summary>

[Tooltip("The area marked by the collider that is considered in bounds.")]

public Collider2D gridArea;

private void Start()

{

// Give the food an initial random position

RandomizePosition();

}

public void RandomizePosition()

{

Bounds bounds = this.gridArea.bounds;

// Pick a random position inside the bounds

float x = Random.Range(bounds.min.x, bounds.max.x);

float y = Random.Range(bounds.min.y, bounds.max.y);

// Set the food position but round the values to ensure it aligns with

// the grid

this.transform.position = new Vector2(Mathf.Round(x), Mathf.Round(y));

}

private void OnTriggerEnter2D(Collider2D other)

{

ScoreManager.instance.AddPoint();

// Move the food to a new position when the snake eats it

RandomizePosition();

}

}


r/UnityHelp • • Jun 17 '21

PROGRAMMING Assets\Scripts\PlayerController.cs(31,2): error CS1513: } expected 📷

3 Upvotes

this error keeps coming up, idk why

heres my code

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour

{

private Rigidbody rb;

private float MovementX;

private float MovementY;

// Start is called before the first frame update

void Start()

{

rb = GetComponent<Rigidbody>();

}

void OnMove(InputValue MovementValue)

{

{ Vector2 movementVector = MovementValue.Get<Vector2>();

movementX = MovementVector.X;

movementY = MovementVector.Y;

}

void FixedUpdate()

{ Vector3 Movement = new Vector3(MovementX, 0.0f, MovementY);

{

rb.AddForce(Movement);

}

}


r/UnityHelp • • Jun 03 '21

AI Nav Mesh on a globe

3 Upvotes

Scripts:

  1. A script that generates a globe out of objects with custom meshes (the objects do connect perfectly)(it does also use prefabs)

  2. A script that rotates the object to "point" away from the globe

  3. A script that pulls the object to the globe

I have 3 issues:

  1. The agent doesn't rotate(the transform does but the agent outline doesn't)

  2. How do I tell it to use the objects that were created by the globe

  3. How would the agent make the mesh because it is normally used for "flat" senses, not globular ones


r/UnityHelp • • Jun 02 '21

UNITY my mesh keeps stopping me

3 Upvotes

my games area is a bunch of hallways extruded from a cube in blender with inverted normals, and the collision usually is fine with my character controlled, but in some parts of it, on some flat edges on the floor, it stops my player and im not sure why edit: yeah i probably shouldnt ask the internet whats wrong with my game with nothing to look at


r/UnityHelp • • May 29 '21

PROGRAMMING Whats wrong with my code?

3 Upvotes

This code is supposed to turn my flashlight sprite on and off when i press E, but right now it only turns it off and wont turn it back on. Heres the code

public class flashlightonoff : MonoBehavior { public static bool flashlightisoff = false; public GameObject Flashlight;

    void Start()
    {
            Flashlight.SetActive(true);
    }

   void Update()
   {
           If (Input.GetKeyDown(KeyCode.E)){
                   If (flashlightisoff)
                   {
                           ON();
                   }
                   else
                   {
                           OFF();
                   }
       }
}

void ON()
{
        Flashlight.SetActive(true);
        flashlightisoff =  false;
}

void OFF() { Flashlight.SetActive(false); flashlightisoff = true; } }


r/UnityHelp • • May 19 '21

Image target not appearing in the AR camera frame :/ 0

3 Upvotes

So when I presss the play button in order to see the image target on my laptop camera (AR camera) it doesn't appear on the screen, and the image target is also not visable in the scene tab. But when I press the play button again (play button off) the image target suddenly appears in the scene and is visable in the AR camera preview :/ I do seem to be able to see objects which are not image targets like a 3d object when using the AR camera, but the Imge target does not appear on the screen as previously mentioned. Any Idea how I could solve this issue?


r/UnityHelp • • Mar 28 '21

2D Scale

3 Upvotes

So I'm trying to make a game for a school project and its going to be a bullet hell, its top down yet I'm having issues with the Player Scaling System.

I'm trying to get my player to scale up when they press E so they can control their size (I will add down with Q later but for now I need this to work. I'm New to C# Please Help

Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scale : MonoBehaviour
{

    public float BaseSize;
    public Vector2 Rigidbody2D;
    float Size;
    public float PlusScale;
    // Start is called before the first frame update
    void Start()
    {
        Size = BaseSize;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.E))
        {
            transform.localScale += Vector2(PlusScale, PlusScale);
        }
    }
}

r/UnityHelp • • Mar 09 '21

PROGRAMMING Any good recommendations for a 3rd party app or something to transfer from Blender to Unity better?

3 Upvotes

Transferring my animations from Blender to Unity has thrown up one complication after another. I've tried multiple ways myself and I'm done with that. Is there any program that can do these:

  • transfer all my animations, not just one big one that I have to divide up later

  • make the animations not READ ONLY so I can add animation events to them

  • make it so it updates the original import of the blender model so it automatically updates anything using that model

I've already tried FBX exporting and dividing up the animation after I export, both of which are incredibly time consuming each time I straight up s much as make a little tweak to one animation, plus FBX just doesn't work for me for some reason


r/UnityHelp • • Mar 04 '21

Add Item Button in custom Inventory crashes Unity (2020.2.6.f1)

3 Upvotes

I'm following this tutorial: "Create a 90's Point and Click Adventure Game with Unity" and I'm stumped that every time I click the "Add Item" button that I coded (Visual Studio) Unity crashes. I've ran through the tutorial video for this section multiple times and can't figure out where problem is.

I appreciate any help.


r/UnityHelp • • Mar 02 '21

Gun recoil

3 Upvotes

I already have bullets and stuff planned for later, but for now I want to make it so that when I click the left mouse button, the player object gets propelled in the opposite direction. How would I do this?


r/UnityHelp • • Feb 05 '21

PROGRAMMING When I press space nothing happens. I think it's because the delay is not working. (If i remove the text in bold the player goes up as intented)

3 Upvotes

using System.Collections;

using System.Collections.Generic;

using System.Threading.Tasks;

using UnityEngine;

public class Jumping : MonoBehaviour

{

public float jumpHeight = 2;

public int airTime = 1000;

bool isAir = false;

void Update()

{

if (Input.GetKeyDown(KeyCode.Space))

{

//jumping

transform.position = new Vector3(0, 1 + jumpHeight, 0);

isAir = true;

}

if(isAir != false)

{

Task.Delay(airTime);

transform.position = new Vector3(0, 1, 0);

}

}

}


r/UnityHelp • • Feb 02 '21

2D Platformer Help

3 Upvotes

Can anybody help me understand why in my 2D platformer game i am making using tilemap the player will seemingly randomly run into an invisible wall while walking? I am new to unity and a don't know whether it is a problem with the players hit box or something.


r/UnityHelp • • Jan 20 '21

login system with mysql and phpmyadmin

3 Upvotes

i am making a really basic login system with database i added manually some data but when i try to login i always get username does not exist while i copied it from the database. the code: https://pastebin.com/8Q9ktfFD


r/UnityHelp • • Jan 17 '21

Unity Collision Detection Issue

3 Upvotes

Good day y'all. I've been working on the Brackey's Unity beginner's tutorial and I just noticed that whenever the player collides with it's first obstacle it goes straight through it. Unity still recognizes the collision because I've set it up to turn off controls whenever it collides with something. Does anybody know why this may be happening? Thank you for your time. I appreciate it. This subreddit has been a life saver for me.


r/UnityHelp • • Jan 17 '21

Help I need to know how to create a dialog box

3 Upvotes

Hey, so I'm new to Unity and I need to know, how do I add a dialogue box to the canvas?

Thanks!


r/UnityHelp • • Jan 14 '21

I Need Help Importing from Blender

3 Upvotes

Every time I try to import from Blender, it only transfers one of the animations for the rig, not all of them. Exporting to FBX used to be my fix, but now it doesn't work and I get the same error with it.


r/UnityHelp • • Jan 07 '21

UNITY Muted material colors?

3 Upvotes

I'm just getting into Brackeys Unity tutorial and I was wondering why my material colors are so muted compared to his? Thank you for your time. I appreciate it. (The right is the video and the left is the project I'm working on)