using System;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
public class MeatIncrementer : MonoBehaviour
{
private const string ntpServerAddress = "time.google.com";
private const int ntpPort = 123;
private DateTime lastSyncTime;
private double meatIncrementInterval = 2 * 60; // 2분마다 증가
private double timeSinceLastIncrement;
private UdpClient ntpClient;
private void Start()
{
ntpClient = new UdpClient(ntpServerAddress, ntpPort);
ntpClient.Connect(ntpServerAddress, ntpPort);
SyncTime(); // 최초 시간 동기화
}
private void Update()
{
timeSinceLastIncrement += Time.deltaTime;
if (timeSinceLastIncrement >= meatIncrementInterval)
{
if (sv.meat < 10)
{
sv.meat++;
PlayerPrefs.SetInt("meat", sv.meat);
}
timeSinceLastIncrement = 0; // 타이머 초기화
}
// 2분마다 시간 동기화
if (DateTime.Now - lastSyncTime > TimeSpan.FromMinutes(2))
{
SyncTime();
}
}
private void SyncTime()
{
try
{
byte[] data = new byte[48];
data[0] = 0x1B;
ntpClient.Send(data, data.Length);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
data = ntpClient.Receive(ref endPoint);
// 데이터의 길이 확인
if (data != null && data.Length >= 48)
{
ulong intPart = BitConverter.ToUInt32(data, 43);
ulong fractPart = BitConverter.ToUInt32(data, 47);
ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
DateTime networkTime = new DateTime(1900, 1, 1) + TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
lastSyncTime = DateTime.Now;
}
else
{
Debug.LogError("Received incomplete or null NTP packet.");
}
}
catch (Exception e)
{
Debug.LogError("Failed to sync time: " + e.Message);
}
}
private void OnDestroy()
{
if (ntpClient != null)
{
ntpClient.Close();
}
}
}
Failed to sync time: Destination array is not long enough to copy all the items in the collection. Check array index and length.
Parameter name: value
UnityEngine.Debug:LogError (object)
MeatIncrementer:SyncTime () (at Assets/TimeManager.cs:75)
MeatIncrementer:Update () (at Assets/TimeManager.cs:42)
오류 내용입니다!
서버로부터 받아온 데이터의 길이 문제인데
몇번 수정해봐도 안되고 잘 모르겠습니다 ㅠㅠ 도와주세요
try문 안에 data = ntpClient.Receive~~~ 이 코드인가? 보여준 코드에서 array는 data밖에 없고 문제 생길 거 같은 부분은 저기 혹은 세 줄 위에 ntpClient.Send~~~인 거 같은데 디버깅 해봄?